blob: 6f364df80f32245029522ac1d4788eb8fb156112 [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
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000013#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000014#include "ASTReaderInternals.h"
15#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/AST/ASTUnresolvedSet.h"
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +010018#include "clang/AST/AbstractTypeWriter.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000019#include "clang/AST/Attr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/Decl.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000021#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/AST/DeclCXX.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000023#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000024#include "clang/AST/DeclFriend.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000025#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000027#include "clang/AST/DeclarationName.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000028#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000029#include "clang/AST/ExprCXX.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/AST/LambdaCapture.h"
31#include "clang/AST/NestedNameSpecifier.h"
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +010032#include "clang/AST/OpenMPClause.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#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"
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +010067#include "clang/Serialization/ASTBitCodes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000068#include "clang/Serialization/ASTReader.h"
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +010069#include "clang/Serialization/ASTRecordWriter.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000070#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080071#include "clang/Serialization/ModuleFile.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000072#include "clang/Serialization/ModuleFileExtension.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000073#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000074#include "llvm/ADT/APFloat.h"
75#include "llvm/ADT/APInt.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000076#include "llvm/ADT/APSInt.h"
77#include "llvm/ADT/ArrayRef.h"
78#include "llvm/ADT/DenseMap.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000079#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000080#include "llvm/ADT/Optional.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000081#include "llvm/ADT/PointerIntPair.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000082#include "llvm/ADT/STLExtras.h"
Ilya Biryukov45643102018-07-09 11:33:23 +000083#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include "llvm/ADT/SmallSet.h"
85#include "llvm/ADT/SmallString.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000086#include "llvm/ADT/SmallVector.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000087#include "llvm/ADT/StringMap.h"
88#include "llvm/ADT/StringRef.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +000089#include "llvm/Bitstream/BitCodes.h"
90#include "llvm/Bitstream/BitstreamWriter.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000091#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +000092#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000093#include "llvm/Support/DJB.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000094#include "llvm/Support/Endian.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000095#include "llvm/Support/EndianStream.h"
George Rimarc39f5492017-01-17 15:45:31 +000096#include "llvm/Support/Error.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include "llvm/Support/ErrorHandling.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000098#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000099#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +0000100#include "llvm/Support/Path.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000101#include "llvm/Support/SHA1.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000102#include "llvm/Support/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000103#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000104#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000105#include <cassert>
106#include <cstdint>
107#include <cstdlib>
108#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000109#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000110#include <deque>
111#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000112#include <memory>
113#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000114#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000115#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000116#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000117
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000118using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000119using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000120
Sebastian Redl3df5a082010-07-30 17:03:48 +0000121template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000122static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000123 if (v.empty()) return StringRef();
124 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000125 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000126}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000127
128template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000129static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000130 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000131 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000132}
133
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000134//===----------------------------------------------------------------------===//
135// Type serialization
136//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000137
John McCalld505e572019-12-13 21:54:44 -0500138static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
139 switch (id) {
140#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
141 case Type::CLASS_ID: return TYPE_##CODE_ID;
142#include "clang/Serialization/TypeBitCodes.def"
143 case Type::Builtin:
144 llvm_unreachable("shouldn't be serializing a builtin type this way");
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000145 }
John McCalld505e572019-12-13 21:54:44 -0500146 llvm_unreachable("bad type kind");
Xiuli Pan9c14e282016-01-09 12:53:17 +0000147}
148
John McCall8f115c62009-10-16 21:56:05 +0000149namespace {
150
John McCalld505e572019-12-13 21:54:44 -0500151class ASTTypeWriter {
152 ASTWriter &Writer;
153 ASTWriter::RecordData Record;
154 ASTRecordWriter BasicWriter;
155
156public:
157 ASTTypeWriter(ASTWriter &Writer)
158 : Writer(Writer), BasicWriter(Writer, Record) {}
159
160 uint64_t write(QualType T) {
161 if (T.hasLocalNonFastQualifiers()) {
162 Qualifiers Qs = T.getLocalQualifiers();
163 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
164 BasicWriter.writeQualifiers(Qs);
165 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
166 }
167
168 const Type *typePtr = T.getTypePtr();
169 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
170 atw.write(typePtr);
171 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
172 /*abbrev*/ 0);
173 }
174};
175
John McCall8f115c62009-10-16 21:56:05 +0000176class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000177 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000178
179public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000180 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000181
John McCall17001972009-10-18 01:05:36 +0000182#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000183#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000184 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000185#include "clang/AST/TypeLocNodes.def"
186
John McCall17001972009-10-18 01:05:36 +0000187 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
188 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000189};
190
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000191} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000192
John McCall17001972009-10-18 01:05:36 +0000193void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
194 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000195}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000196
John McCall17001972009-10-18 01:05:36 +0000197void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000198 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000199 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000200 Record.push_back(TL.getWrittenTypeSpec());
201 Record.push_back(TL.getWrittenSignSpec());
202 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000203 Record.push_back(TL.hasModeAttr());
204 }
John McCall8f115c62009-10-16 21:56:05 +0000205}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000206
John McCall17001972009-10-18 01:05:36 +0000207void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000208 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000209}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000210
John McCall17001972009-10-18 01:05:36 +0000211void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000212 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000213}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000214
Reid Kleckner8a365022013-06-24 17:51:48 +0000215void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
216 // nothing to do
217}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000218
Reid Kleckner0503a872013-12-05 01:23:43 +0000219void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
220 // nothing to do
221}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000222
John McCall17001972009-10-18 01:05:36 +0000223void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000224 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000225}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000226
John McCall17001972009-10-18 01:05:36 +0000227void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000228 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000230
John McCall17001972009-10-18 01:05:36 +0000231void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000232 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000233}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000234
John McCall17001972009-10-18 01:05:36 +0000235void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000236 Record.AddSourceLocation(TL.getStarLoc());
237 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000238}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000239
John McCall17001972009-10-18 01:05:36 +0000240void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000241 Record.AddSourceLocation(TL.getLBracketLoc());
242 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000243 Record.push_back(TL.getSizeExpr() ? 1 : 0);
244 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000245 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000246}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000247
John McCall17001972009-10-18 01:05:36 +0000248void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
249 VisitArrayTypeLoc(TL);
250}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000251
John McCall17001972009-10-18 01:05:36 +0000252void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
253 VisitArrayTypeLoc(TL);
254}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000255
John McCall17001972009-10-18 01:05:36 +0000256void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
257 VisitArrayTypeLoc(TL);
258}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000259
John McCall17001972009-10-18 01:05:36 +0000260void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
261 DependentSizedArrayTypeLoc TL) {
262 VisitArrayTypeLoc(TL);
263}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000264
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000265void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
266 DependentAddressSpaceTypeLoc TL) {
267 Record.AddSourceLocation(TL.getAttrNameLoc());
268 SourceRange range = TL.getAttrOperandParensRange();
269 Record.AddSourceLocation(range.getBegin());
270 Record.AddSourceLocation(range.getEnd());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000271 Record.AddStmt(TL.getAttrExprOperand());
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000272}
273
John McCall17001972009-10-18 01:05:36 +0000274void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
275 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000276 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000277}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000278
John McCall17001972009-10-18 01:05:36 +0000279void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000280 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000281}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000282
Erich Keanef702b022018-07-13 19:46:04 +0000283void TypeLocWriter::VisitDependentVectorTypeLoc(
284 DependentVectorTypeLoc TL) {
285 Record.AddSourceLocation(TL.getNameLoc());
286}
287
John McCall17001972009-10-18 01:05:36 +0000288void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000289 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000290}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000291
Florian Hahn10658692020-05-11 17:45:51 +0100292void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
293 Record.AddSourceLocation(TL.getAttrNameLoc());
294 SourceRange range = TL.getAttrOperandParensRange();
295 Record.AddSourceLocation(range.getBegin());
296 Record.AddSourceLocation(range.getEnd());
297 Record.AddStmt(TL.getAttrRowOperand());
298 Record.AddStmt(TL.getAttrColumnOperand());
299}
300
301void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
302 DependentSizedMatrixTypeLoc TL) {
303 Record.AddSourceLocation(TL.getAttrNameLoc());
304 SourceRange range = TL.getAttrOperandParensRange();
305 Record.AddSourceLocation(range.getBegin());
306 Record.AddSourceLocation(range.getEnd());
307 Record.AddStmt(TL.getAttrRowOperand());
308 Record.AddStmt(TL.getAttrColumnOperand());
309}
310
John McCall17001972009-10-18 01:05:36 +0000311void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000312 Record.AddSourceLocation(TL.getLocalRangeBegin());
313 Record.AddSourceLocation(TL.getLParenLoc());
314 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000315 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000316 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000317 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000318 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000319}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000320
John McCall17001972009-10-18 01:05:36 +0000321void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
322 VisitFunctionTypeLoc(TL);
323}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000324
John McCall17001972009-10-18 01:05:36 +0000325void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
326 VisitFunctionTypeLoc(TL);
327}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000328
John McCallb96ec562009-12-04 22:46:56 +0000329void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000330 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000331}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000332
John McCall17001972009-10-18 01:05:36 +0000333void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000334 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000335}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000336
Manman Rene6be26c2016-09-13 17:25:08 +0000337void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
338 if (TL.getNumProtocols()) {
339 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
340 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
341 }
342 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
343 Record.AddSourceLocation(TL.getProtocolLoc(i));
344}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000345
John McCall17001972009-10-18 01:05:36 +0000346void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000347 Record.AddSourceLocation(TL.getTypeofLoc());
348 Record.AddSourceLocation(TL.getLParenLoc());
349 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000350}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000351
John McCall17001972009-10-18 01:05:36 +0000352void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000353 Record.AddSourceLocation(TL.getTypeofLoc());
354 Record.AddSourceLocation(TL.getLParenLoc());
355 Record.AddSourceLocation(TL.getRParenLoc());
356 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000357}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000358
John McCall17001972009-10-18 01:05:36 +0000359void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000360 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000361}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000362
Alexis Hunte852b102011-05-24 22:41:36 +0000363void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000364 Record.AddSourceLocation(TL.getKWLoc());
365 Record.AddSourceLocation(TL.getLParenLoc());
366 Record.AddSourceLocation(TL.getRParenLoc());
367 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000368}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000369
Richard Smith30482bc2011-02-20 03:19:35 +0000370void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000371 Record.AddSourceLocation(TL.getNameLoc());
Saar Razb481f022020-01-22 02:03:05 +0200372 Record.push_back(TL.isConstrained());
373 if (TL.isConstrained()) {
374 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
375 Record.AddSourceLocation(TL.getTemplateKWLoc());
376 Record.AddSourceLocation(TL.getConceptNameLoc());
377 Record.AddDeclRef(TL.getFoundDecl());
378 Record.AddSourceLocation(TL.getLAngleLoc());
379 Record.AddSourceLocation(TL.getRAngleLoc());
380 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
381 Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
382 TL.getArgLocInfo(I));
383 }
Richard Smith30482bc2011-02-20 03:19:35 +0000384}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000385
Richard Smith600b5262017-01-26 20:40:47 +0000386void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
387 DeducedTemplateSpecializationTypeLoc TL) {
388 Record.AddSourceLocation(TL.getTemplateNameLoc());
389}
390
John McCall17001972009-10-18 01:05:36 +0000391void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000392 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000393}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000394
John McCall17001972009-10-18 01:05:36 +0000395void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000396 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000397}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000398
John McCall81904512011-01-06 01:58:22 +0000399void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +0000400 Record.AddAttr(TL.getAttr());
John McCall81904512011-01-06 01:58:22 +0000401}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000402
John McCall17001972009-10-18 01:05:36 +0000403void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000404 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000405}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000406
John McCallcebee162009-10-18 09:09:24 +0000407void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
408 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000409 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000410}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000411
Douglas Gregorada4b792011-01-14 02:55:32 +0000412void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
413 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000414 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000415}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000416
John McCall17001972009-10-18 01:05:36 +0000417void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
418 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000419 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
420 Record.AddSourceLocation(TL.getTemplateNameLoc());
421 Record.AddSourceLocation(TL.getLAngleLoc());
422 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000423 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000424 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
425 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000426}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000427
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000428void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000429 Record.AddSourceLocation(TL.getLParenLoc());
430 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000431}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000432
Leonard Chanc72aaf62019-05-07 03:20:17 +0000433void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
434 Record.AddSourceLocation(TL.getExpansionLoc());
435}
436
Abramo Bagnara6150c882010-05-11 21:36:43 +0000437void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
439 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000440}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000441
John McCalle78aac42010-03-10 03:28:59 +0000442void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000444}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000445
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000446void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000447 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
448 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
449 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000450}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000451
John McCallc392f372010-06-11 00:33:02 +0000452void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
453 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000454 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
455 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
456 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
457 Record.AddSourceLocation(TL.getTemplateNameLoc());
458 Record.AddSourceLocation(TL.getLAngleLoc());
459 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000460 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000461 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
462 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000463}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000464
Douglas Gregord2fa7662010-12-20 02:24:11 +0000465void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000466 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000467}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000468
John McCall17001972009-10-18 01:05:36 +0000469void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000470 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000471}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000472
John McCall8b07ec22010-05-15 11:32:37 +0000473void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
474 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000475 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
476 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000477 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000478 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
479 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
480 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000481 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000482 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000483}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000484
John McCallfc93cf92009-10-22 22:37:11 +0000485void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000486 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000487}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000488
Eli Friedman0dfb8892011-10-06 23:00:33 +0000489void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000490 Record.AddSourceLocation(TL.getKWLoc());
491 Record.AddSourceLocation(TL.getLParenLoc());
492 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000493}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000494
Xiuli Pan9c14e282016-01-09 12:53:17 +0000495void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000496 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000497}
John McCall8f115c62009-10-16 21:56:05 +0000498
Erich Keane5f0903e2020-04-17 10:44:19 -0700499void TypeLocWriter::VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL) {
500 Record.AddSourceLocation(TL.getNameLoc());
501}
502void TypeLocWriter::VisitDependentExtIntTypeLoc(
503 clang::DependentExtIntTypeLoc TL) {
504 Record.AddSourceLocation(TL.getNameLoc());
505}
506
Richard Smith01b2cb42014-07-26 06:37:51 +0000507void ASTWriter::WriteTypeAbbrevs() {
508 using namespace llvm;
509
David Blaikieb44f0bf2017-01-04 22:36:43 +0000510 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000511
512 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000513 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000514 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
515 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
516 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000517 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000518
519 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000520 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000521 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
522 // FunctionType
523 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
524 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
525 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
526 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
527 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
528 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000529 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000530 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
Momchil Velikov080d0462020-03-24 09:32:51 +0000531 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // CmseNSCall
Richard Smith01b2cb42014-07-26 06:37:51 +0000532 // FunctionProtoType
533 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
534 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
535 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
536 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
537 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
538 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
539 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
540 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000541 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000542}
543
Chris Lattner19cea4e2009-04-22 05:57:30 +0000544//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000545// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000546//===----------------------------------------------------------------------===//
547
Chris Lattner28fa4e62009-04-26 22:26:21 +0000548static void EmitBlockID(unsigned ID, const char *Name,
549 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000550 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000551 Record.clear();
552 Record.push_back(ID);
553 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
554
555 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000556 if (!Name || Name[0] == 0)
557 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000558 Record.clear();
559 while (*Name)
560 Record.push_back(*Name++);
561 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
562}
563
564static void EmitRecordID(unsigned ID, const char *Name,
565 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000566 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000567 Record.clear();
568 Record.push_back(ID);
569 while (*Name)
570 Record.push_back(*Name++);
571 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000572}
573
574static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000575 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000576#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000577 RECORD(STMT_STOP);
578 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000579 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000580 RECORD(STMT_NULL);
581 RECORD(STMT_COMPOUND);
582 RECORD(STMT_CASE);
583 RECORD(STMT_DEFAULT);
584 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000585 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000586 RECORD(STMT_IF);
587 RECORD(STMT_SWITCH);
588 RECORD(STMT_WHILE);
589 RECORD(STMT_DO);
590 RECORD(STMT_FOR);
591 RECORD(STMT_GOTO);
592 RECORD(STMT_INDIRECT_GOTO);
593 RECORD(STMT_CONTINUE);
594 RECORD(STMT_BREAK);
595 RECORD(STMT_RETURN);
596 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000597 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000598 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000599 RECORD(EXPR_PREDEFINED);
600 RECORD(EXPR_DECL_REF);
601 RECORD(EXPR_INTEGER_LITERAL);
Vince Bridgers161fc1d2020-04-07 14:46:08 -0500602 RECORD(EXPR_FIXEDPOINT_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000603 RECORD(EXPR_FLOATING_LITERAL);
604 RECORD(EXPR_IMAGINARY_LITERAL);
605 RECORD(EXPR_STRING_LITERAL);
606 RECORD(EXPR_CHARACTER_LITERAL);
607 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000608 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000609 RECORD(EXPR_UNARY_OPERATOR);
610 RECORD(EXPR_SIZEOF_ALIGN_OF);
611 RECORD(EXPR_ARRAY_SUBSCRIPT);
612 RECORD(EXPR_CALL);
613 RECORD(EXPR_MEMBER);
614 RECORD(EXPR_BINARY_OPERATOR);
615 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
616 RECORD(EXPR_CONDITIONAL_OPERATOR);
617 RECORD(EXPR_IMPLICIT_CAST);
618 RECORD(EXPR_CSTYLE_CAST);
619 RECORD(EXPR_COMPOUND_LITERAL);
620 RECORD(EXPR_EXT_VECTOR_ELEMENT);
621 RECORD(EXPR_INIT_LIST);
622 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000623 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000624 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000625 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000626 RECORD(EXPR_VA_ARG);
627 RECORD(EXPR_ADDR_LABEL);
628 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000629 RECORD(EXPR_CHOOSE);
630 RECORD(EXPR_GNU_NULL);
631 RECORD(EXPR_SHUFFLE_VECTOR);
632 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000633 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000634 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000635 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000636 RECORD(EXPR_OBJC_ARRAY_LITERAL);
637 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000638 RECORD(EXPR_OBJC_ENCODE);
639 RECORD(EXPR_OBJC_SELECTOR_EXPR);
640 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
641 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
642 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
643 RECORD(EXPR_OBJC_KVC_REF_EXPR);
644 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000645 RECORD(STMT_OBJC_FOR_COLLECTION);
646 RECORD(STMT_OBJC_CATCH);
647 RECORD(STMT_OBJC_FINALLY);
648 RECORD(STMT_OBJC_AT_TRY);
649 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
650 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000651 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000652 RECORD(STMT_CXX_CATCH);
653 RECORD(STMT_CXX_TRY);
654 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000655 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000656 RECORD(EXPR_CXX_MEMBER_CALL);
Richard Smith778dc0f2019-10-19 00:04:38 +0000657 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000658 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000659 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000660 RECORD(EXPR_CXX_STATIC_CAST);
661 RECORD(EXPR_CXX_DYNAMIC_CAST);
662 RECORD(EXPR_CXX_REINTERPRET_CAST);
663 RECORD(EXPR_CXX_CONST_CAST);
Anastasia Stulovaa6a237f2020-05-18 11:02:01 +0100664 RECORD(EXPR_CXX_ADDRSPACE_CAST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000665 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000666 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000667 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000668 RECORD(EXPR_CXX_BOOL_LITERAL);
669 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000670 RECORD(EXPR_CXX_TYPEID_EXPR);
671 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000672 RECORD(EXPR_CXX_THIS);
673 RECORD(EXPR_CXX_THROW);
674 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000675 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000676 RECORD(EXPR_CXX_BIND_TEMPORARY);
677 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
678 RECORD(EXPR_CXX_NEW);
679 RECORD(EXPR_CXX_DELETE);
680 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
681 RECORD(EXPR_EXPR_WITH_CLEANUPS);
682 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
683 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
684 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
685 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
686 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000687 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000688 RECORD(EXPR_CXX_NOEXCEPT);
689 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000690 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
691 RECORD(EXPR_TYPE_TRAIT);
692 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000693 RECORD(EXPR_PACK_EXPANSION);
694 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000695 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000696 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000697 RECORD(EXPR_FUNCTION_PARM_PACK);
698 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000699 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000700 RECORD(EXPR_CXX_UUIDOF_EXPR);
701 RECORD(EXPR_CXX_UUIDOF_TYPE);
702 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000703#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000704}
Mike Stump11289f42009-09-09 15:08:12 +0000705
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000706void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000707 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000708 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000709
Sebastian Redl539c5062010-08-18 23:57:32 +0000710#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
711#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000712
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000713 // Control Block.
714 BLOCK(CONTROL_BLOCK);
715 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000716 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000717 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000718 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000719 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000720 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000721 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000722 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000723 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000724
725 BLOCK(OPTIONS_BLOCK);
726 RECORD(LANGUAGE_OPTIONS);
727 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000728 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000729 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000730 RECORD(PREPROCESSOR_OPTIONS);
731
Douglas Gregor108cb222012-10-19 00:45:00 +0000732 BLOCK(INPUT_FILES_BLOCK);
733 RECORD(INPUT_FILE);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +0000734 RECORD(INPUT_FILE_HASH);
Douglas Gregor108cb222012-10-19 00:45:00 +0000735
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000736 // AST Top-Level Block.
737 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000738 RECORD(TYPE_OFFSET);
739 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000740 RECORD(IDENTIFIER_OFFSET);
741 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000742 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +0000743 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000744 RECORD(SPECIAL_TYPES);
745 RECORD(STATISTICS);
746 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000747 RECORD(SELECTOR_OFFSETS);
748 RECORD(METHOD_POOL);
749 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000750 RECORD(SOURCE_LOCATION_OFFSETS);
751 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000752 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000753 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000754 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000755 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000756 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000757 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000758 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000759 RECORD(SEMA_DECL_REFS);
760 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
761 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000762 RECORD(UPDATE_VISIBLE);
763 RECORD(DECL_UPDATE_OFFSETS);
764 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000765 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000766 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000767 RECORD(FP_PRAGMA_OPTIONS);
768 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +0000769 RECORD(OPENCL_EXTENSION_TYPES);
770 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000771 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000772 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000773 RECORD(MODULE_OFFSET_MAP);
774 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000775 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000776 RECORD(FILE_SORTED_DECLS);
777 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000778 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000779 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000780 RECORD(INTERESTING_IDENTIFIERS);
781 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000782 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000783 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000784 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000785 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000786 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000787 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +0000788 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000789 RECORD(PP_CONDITIONAL_STACK);
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -0500790 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
Douglas Gregor358cd442012-01-15 16:58:34 +0000791
Chris Lattner28fa4e62009-04-26 22:26:21 +0000792 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000793 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000794 RECORD(SM_SLOC_FILE_ENTRY);
795 RECORD(SM_SLOC_BUFFER_ENTRY);
796 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000797 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000798 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner28fa4e62009-04-26 22:26:21 +0000800 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000801 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000802 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000803 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000804 RECORD(PP_MACRO_OBJECT_LIKE);
805 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000806 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000807
Richard Smithfa715652015-08-31 22:43:10 +0000808 // Submodule Block.
809 BLOCK(SUBMODULE_BLOCK);
810 RECORD(SUBMODULE_METADATA);
811 RECORD(SUBMODULE_DEFINITION);
812 RECORD(SUBMODULE_UMBRELLA_HEADER);
813 RECORD(SUBMODULE_HEADER);
814 RECORD(SUBMODULE_TOPHEADER);
815 RECORD(SUBMODULE_UMBRELLA_DIR);
816 RECORD(SUBMODULE_IMPORTS);
817 RECORD(SUBMODULE_EXPORTS);
818 RECORD(SUBMODULE_REQUIRES);
819 RECORD(SUBMODULE_EXCLUDED_HEADER);
820 RECORD(SUBMODULE_LINK_LIBRARY);
821 RECORD(SUBMODULE_CONFIG_MACRO);
822 RECORD(SUBMODULE_CONFLICT);
823 RECORD(SUBMODULE_PRIVATE_HEADER);
824 RECORD(SUBMODULE_TEXTUAL_HEADER);
825 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +0000826 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +0000827 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +0000828
829 // Comments Block.
830 BLOCK(COMMENTS_BLOCK);
831 RECORD(COMMENTS_RAW_COMMENT);
832
Douglas Gregor12bfa382009-10-17 00:13:19 +0000833 // Decls and Types block.
834 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000835 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000836 RECORD(TYPE_COMPLEX);
837 RECORD(TYPE_POINTER);
838 RECORD(TYPE_BLOCK_POINTER);
839 RECORD(TYPE_LVALUE_REFERENCE);
840 RECORD(TYPE_RVALUE_REFERENCE);
841 RECORD(TYPE_MEMBER_POINTER);
842 RECORD(TYPE_CONSTANT_ARRAY);
843 RECORD(TYPE_INCOMPLETE_ARRAY);
844 RECORD(TYPE_VARIABLE_ARRAY);
845 RECORD(TYPE_VECTOR);
846 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000847 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000848 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000849 RECORD(TYPE_TYPEDEF);
850 RECORD(TYPE_TYPEOF_EXPR);
851 RECORD(TYPE_TYPEOF);
852 RECORD(TYPE_RECORD);
853 RECORD(TYPE_ENUM);
854 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000855 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000856 RECORD(TYPE_DECLTYPE);
857 RECORD(TYPE_ELABORATED);
858 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
859 RECORD(TYPE_UNRESOLVED_USING);
860 RECORD(TYPE_INJECTED_CLASS_NAME);
861 RECORD(TYPE_OBJC_OBJECT);
862 RECORD(TYPE_TEMPLATE_TYPE_PARM);
863 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
864 RECORD(TYPE_DEPENDENT_NAME);
865 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
866 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
867 RECORD(TYPE_PAREN);
Leonard Chanc72aaf62019-05-07 03:20:17 +0000868 RECORD(TYPE_MACRO_QUALIFIED);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000869 RECORD(TYPE_PACK_EXPANSION);
870 RECORD(TYPE_ATTRIBUTED);
871 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000872 RECORD(TYPE_AUTO);
873 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000874 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000875 RECORD(TYPE_DECAYED);
876 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +0000877 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +0000878 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000879 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000880 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000881 RECORD(DECL_ENUM);
882 RECORD(DECL_RECORD);
883 RECORD(DECL_ENUM_CONSTANT);
884 RECORD(DECL_FUNCTION);
885 RECORD(DECL_OBJC_METHOD);
886 RECORD(DECL_OBJC_INTERFACE);
887 RECORD(DECL_OBJC_PROTOCOL);
888 RECORD(DECL_OBJC_IVAR);
889 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000890 RECORD(DECL_OBJC_CATEGORY);
891 RECORD(DECL_OBJC_CATEGORY_IMPL);
892 RECORD(DECL_OBJC_IMPLEMENTATION);
893 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
894 RECORD(DECL_OBJC_PROPERTY);
895 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000896 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +0000897 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000898 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000899 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000900 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000901 RECORD(DECL_FILE_SCOPE_ASM);
902 RECORD(DECL_BLOCK);
903 RECORD(DECL_CONTEXT_LEXICAL);
904 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000905 RECORD(DECL_NAMESPACE);
906 RECORD(DECL_NAMESPACE_ALIAS);
907 RECORD(DECL_USING);
908 RECORD(DECL_USING_SHADOW);
909 RECORD(DECL_USING_DIRECTIVE);
910 RECORD(DECL_UNRESOLVED_USING_VALUE);
911 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
912 RECORD(DECL_LINKAGE_SPEC);
913 RECORD(DECL_CXX_RECORD);
914 RECORD(DECL_CXX_METHOD);
915 RECORD(DECL_CXX_CONSTRUCTOR);
916 RECORD(DECL_CXX_DESTRUCTOR);
917 RECORD(DECL_CXX_CONVERSION);
918 RECORD(DECL_ACCESS_SPEC);
919 RECORD(DECL_FRIEND);
920 RECORD(DECL_FRIEND_TEMPLATE);
921 RECORD(DECL_CLASS_TEMPLATE);
922 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
923 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000924 RECORD(DECL_VAR_TEMPLATE);
925 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
926 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000927 RECORD(DECL_FUNCTION_TEMPLATE);
928 RECORD(DECL_TEMPLATE_TYPE_PARM);
929 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
930 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Saar Razd7aae332019-07-10 21:25:49 +0000931 RECORD(DECL_CONCEPT);
Saar Raza0f50d72020-01-18 09:11:43 +0200932 RECORD(DECL_REQUIRES_EXPR_BODY);
Richard Smithefc884a2016-04-13 07:41:35 +0000933 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000934 RECORD(DECL_STATIC_ASSERT);
935 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +0000936 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000937 RECORD(DECL_INDIRECTFIELD);
938 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +0000939 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
940 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
941 RECORD(DECL_IMPORT);
942 RECORD(DECL_OMP_THREADPRIVATE);
943 RECORD(DECL_EMPTY);
944 RECORD(DECL_OBJC_TYPE_PARAM);
945 RECORD(DECL_OMP_CAPTUREDEXPR);
946 RECORD(DECL_PRAGMA_COMMENT);
947 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
948 RECORD(DECL_OMP_DECLARE_REDUCTION);
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000949 RECORD(DECL_OMP_ALLOCATE);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000950
Douglas Gregor03412ba2011-06-03 02:27:19 +0000951 // Statements and Exprs can occur in the Decls and Types block.
952 AddStmtsExprs(Stream, Record);
953
Douglas Gregor92a96f52011-02-08 21:58:10 +0000954 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000955 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +0000956 RECORD(PPD_MACRO_DEFINITION);
957 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000958
959 // Decls and Types block.
960 BLOCK(EXTENSION_BLOCK);
961 RECORD(EXTENSION_METADATA);
962
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000963 BLOCK(UNHASHED_CONTROL_BLOCK);
964 RECORD(SIGNATURE);
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +0100965 RECORD(AST_BLOCK_HASH);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000966 RECORD(DIAGNOSTIC_OPTIONS);
967 RECORD(DIAG_PRAGMA_MAPPINGS);
968
Chris Lattner28fa4e62009-04-26 22:26:21 +0000969#undef RECORD
970#undef BLOCK
971 Stream.ExitBlock();
972}
973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000974/// Prepares a path for being written to an AST file by converting it
Richard Smith54cc3c22014-12-11 20:50:24 +0000975/// to an absolute path and removing nested './'s.
976///
977/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000978static bool cleanPathForOutput(FileManager &FileMgr,
979 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +0000980 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000981 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +0000982}
983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000984/// Adjusts the given filename to only write out the portion of the
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000985/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000986///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000987/// \param Filename the file name to adjust.
988///
Richard Smith7ed1bc92014-12-05 22:42:13 +0000989/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
990/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000991///
992/// \returns either the original filename (if it needs no adjustment) or the
993/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000994static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +0000995adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000996 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000997
Richard Smith7ed1bc92014-12-05 22:42:13 +0000998 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000999 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001000
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001001 // Verify that the filename and the system root have the same prefix.
1002 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001003 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1004 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001005 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001006
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001007 // We hit the end of the filename before we hit the end of the system root.
1008 if (!Filename[Pos])
1009 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001010
Richard Smith7ed1bc92014-12-05 22:42:13 +00001011 // If there's not a path separator at the end of the base directory nor
1012 // immediately after it, then this isn't within the base directory.
1013 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1014 if (!llvm::sys::path::is_separator(BaseDir.back()))
1015 return Filename;
1016 } else {
1017 // If the file name has a '/' at the current position, skip over the '/'.
1018 // We distinguish relative paths from absolute paths by the
1019 // absence of '/' at the beginning of relative paths.
1020 //
1021 // FIXME: This is wrong. We distinguish them by asking if the path is
1022 // absolute, which isn't the same thing. And there might be multiple '/'s
1023 // in a row. Use a better mechanism to indicate whether we have emitted an
1024 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001025 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001028 return Filename + Pos;
1029}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001030
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001031std::pair<ASTFileSignature, ASTFileSignature>
1032ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001033 llvm::SHA1 Hasher;
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001034 Hasher.update(ASTBlockBytes);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001035 auto Hash = Hasher.result();
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001036 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hash);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001037
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001038 // Add the remaining bytes (i.e. bytes before the unhashed control block that
1039 // are not part of the AST block).
1040 Hasher.update(
1041 AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1042 Hasher.update(
1043 AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1044 Hash = Hasher.result();
1045 ASTFileSignature Signature = ASTFileSignature::create(Hash);
1046
1047 return std::make_pair(ASTBlockHash, Signature);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001048}
1049
1050ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1051 ASTContext &Context) {
1052 // Flush first to prepare the PCM hash (signature).
1053 Stream.FlushToWord();
1054 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1055
1056 // Enter the block and prepare to write records.
1057 RecordData Record;
1058 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1059
1060 // For implicit modules, write the hash of the PCM as its signature.
1061 ASTFileSignature Signature;
1062 if (WritingModule &&
1063 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001064 ASTFileSignature ASTBlockHash;
1065 auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1066 auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1067 std::tie(ASTBlockHash, Signature) = createSignature(
1068 StringRef(Buffer.begin(), StartOfUnhashedControl),
1069 StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1070
1071 Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1072 Stream.EmitRecord(AST_BLOCK_HASH, Record);
1073 Record.clear();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001074 Record.append(Signature.begin(), Signature.end());
1075 Stream.EmitRecord(SIGNATURE, Record);
1076 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001077 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001078
1079 // Diagnostic options.
1080 const auto &Diags = Context.getDiagnostics();
1081 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1082#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1083#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1084 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1085#include "clang/Basic/DiagnosticOptions.def"
1086 Record.push_back(DiagOpts.Warnings.size());
1087 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1088 AddString(DiagOpts.Warnings[I], Record);
1089 Record.push_back(DiagOpts.Remarks.size());
1090 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1091 AddString(DiagOpts.Remarks[I], Record);
1092 // Note: we don't serialize the log or serialization file names, because they
1093 // are generally transient files and will almost always be overridden.
1094 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1095
1096 // Write out the diagnostic/pragma mappings.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001097 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001098
1099 // Leave the options block.
1100 Stream.ExitBlock();
1101 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001102}
1103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001104/// Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001105void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1106 StringRef isysroot,
1107 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001108 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001109
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001110 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001111 RecordData Record;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001112
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001113 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001114 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001115 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1116 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1117 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1118 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1119 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1120 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001121 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001122 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001123 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1124 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001125 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001126 assert((!WritingModule || isysroot.empty()) &&
1127 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001128 {
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001129 RecordData::value_type Record[] = {
1130 METADATA,
1131 VERSION_MAJOR,
1132 VERSION_MINOR,
1133 CLANG_VERSION_MAJOR,
1134 CLANG_VERSION_MINOR,
1135 !isysroot.empty(),
1136 IncludeTimestamps,
1137 Context.getLangOpts().BuildingPCHWithObjectFile,
1138 ASTHasCompilerErrors};
Mehdi Amini57a41912015-09-10 01:46:39 +00001139 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1140 getClangFullRepositoryVersion());
1141 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001142
Richard Smith8b706102017-05-31 20:56:55 +00001143 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001144 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001145 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001146 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001148 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001149 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001150 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1151 }
1152
Richard Smith7ed1bc92014-12-05 22:42:13 +00001153 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001154 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001155 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001156
1157 // If the home of the module is the current working directory, then we
1158 // want to pick up the cwd of the build process loading the module, not
1159 // our cwd, when we load this module.
1160 if (!PP.getHeaderSearchInfo()
1161 .getHeaderSearchOpts()
1162 .ModuleMapFileHomeIsCwd ||
1163 WritingModule->Directory->getName() != StringRef(".")) {
1164 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001165 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001166 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1167 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001168 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001169
Mehdi Amini57a41912015-09-10 01:46:39 +00001170 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001171 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1172 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001173
1174 // Write out all other paths relative to the base directory if possible.
1175 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1176 } else if (!isysroot.empty()) {
1177 // Write out paths relative to the sysroot if possible.
Benjamin Krameradcd0262020-01-28 20:23:46 +01001178 BaseDirectory = std::string(isysroot);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001179 }
1180
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001181 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001182 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001183 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001184
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001185 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001186 AddPath(WritingModule->PresumedModuleMapFile.empty()
1187 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1188 : StringRef(WritingModule->PresumedModuleMapFile),
1189 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001190
1191 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001192 if (auto *AdditionalModMaps =
1193 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001194 Record.push_back(AdditionalModMaps->size());
1195 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001196 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001197 } else {
1198 Record.push_back(0);
1199 }
1200
1201 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001202 }
1203
Douglas Gregor112b9072012-10-18 05:31:06 +00001204 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001205 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001206 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001207 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001208
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001209 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001210 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001211 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001212 continue;
1213
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001214 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1215 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001216
1217 // If we have calculated signature, there is no need to store
1218 // the size or timestamp.
1219 Record.push_back(M.Signature ? 0 : M.File->getSize());
1220 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1221
1222 for (auto I : M.Signature)
1223 Record.push_back(I);
1224
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001225 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001226 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001227 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001228 Stream.EmitRecord(IMPORTS, Record);
1229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
Richard Smith0516b182015-09-08 19:40:14 +00001231 // Write the options block.
1232 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1233
Douglas Gregor112b9072012-10-18 05:31:06 +00001234 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001235 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001236 const LangOptions &LangOpts = Context.getLangOpts();
1237#define LANGOPT(Name, Bits, Default, Description) \
1238 Record.push_back(LangOpts.Name);
1239#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1240 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001241#include "clang/Basic/LangOptions.def"
1242#define SANITIZER(NAME, ID) \
1243 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001244#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001245
Ben Langmuircd98cb72015-06-23 18:20:18 +00001246 Record.push_back(LangOpts.ModuleFeatures.size());
1247 for (StringRef Feature : LangOpts.ModuleFeatures)
1248 AddString(Feature, Record);
1249
Douglas Gregor112b9072012-10-18 05:31:06 +00001250 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1251 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001252
1253 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001254
1255 // Comment options.
1256 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001257 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1258 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001259 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001260 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001261
Samuel Antaoee8fb302016-01-06 13:42:12 +00001262 // OpenMP offloading options.
1263 Record.push_back(LangOpts.OMPTargetTriples.size());
1264 for (auto &T : LangOpts.OMPTargetTriples)
1265 AddString(T.getTriple(), Record);
1266
1267 AddString(LangOpts.OMPHostIRFile, Record);
1268
Douglas Gregor112b9072012-10-18 05:31:06 +00001269 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1270
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001271 // Target options.
1272 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001273 const TargetInfo &Target = Context.getTargetInfo();
1274 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001275 AddString(TargetOpts.Triple, Record);
1276 AddString(TargetOpts.CPU, Record);
1277 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001278 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1279 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1280 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1281 }
1282 Record.push_back(TargetOpts.Features.size());
1283 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1284 AddString(TargetOpts.Features[I], Record);
1285 }
1286 Stream.EmitRecord(TARGET_OPTIONS, Record);
1287
Douglas Gregorc6317db2012-10-24 15:49:58 +00001288 // File system options.
1289 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001290 const FileSystemOptions &FSOpts =
1291 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001292 AddString(FSOpts.WorkingDir, Record);
1293 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1294
Douglas Gregor2d302362012-10-24 16:50:34 +00001295 // Header search options.
1296 Record.clear();
1297 const HeaderSearchOptions &HSOpts
1298 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1299 AddString(HSOpts.Sysroot, Record);
1300
1301 // Include entries.
1302 Record.push_back(HSOpts.UserEntries.size());
1303 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1304 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1305 AddString(Entry.Path, Record);
1306 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001307 Record.push_back(Entry.IsFramework);
1308 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001309 }
1310
1311 // System header prefixes.
1312 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1313 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1314 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1315 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1316 }
1317
1318 AddString(HSOpts.ResourceDir, Record);
1319 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001320 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001321 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001322 Record.push_back(HSOpts.ImplicitModuleMaps);
1323 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001324 Record.push_back(HSOpts.UseBuiltinIncludes);
1325 Record.push_back(HSOpts.UseStandardSystemIncludes);
1326 Record.push_back(HSOpts.UseStandardCXXIncludes);
1327 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001328 // Write out the specific module cache path that contains the module files.
1329 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001330 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1331
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001332 // Preprocessor options.
1333 Record.clear();
1334 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1335
1336 // Macro definitions.
1337 Record.push_back(PPOpts.Macros.size());
1338 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1339 AddString(PPOpts.Macros[I].first, Record);
1340 Record.push_back(PPOpts.Macros[I].second);
1341 }
1342
1343 // Includes
1344 Record.push_back(PPOpts.Includes.size());
1345 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1346 AddString(PPOpts.Includes[I], Record);
1347
1348 // Macro includes
1349 Record.push_back(PPOpts.MacroIncludes.size());
1350 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1351 AddString(PPOpts.MacroIncludes[I], Record);
1352
Douglas Gregorb6368752012-10-24 23:41:50 +00001353 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001354 // Detailed record is important since it is used for the module cache hash.
1355 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001356 AddString(PPOpts.ImplicitPCHInclude, Record);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001357 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1358 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1359
Richard Smith0516b182015-09-08 19:40:14 +00001360 // Leave the options block.
1361 Stream.ExitBlock();
1362
Douglas Gregora3b20262011-05-06 21:43:30 +00001363 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001364 SourceManager &SM = Context.getSourceManager();
1365 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001366 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001367 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1368 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001369 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001370 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001371
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001372 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001373 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001374 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001375 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001376 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001377
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001378 Record.clear();
1379 Record.push_back(SM.getMainFileID().getOpaqueValue());
1380 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1381
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001382 // Original PCH directory
1383 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001384 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001385 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001387 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001388
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001389 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001390
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001391 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001392 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1393
Mehdi Amini57a41912015-09-10 01:46:39 +00001394 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001395 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1396 }
1397
Douglas Gregor49491f72013-03-15 22:15:07 +00001398 WriteInputFiles(Context.SourceMgr,
1399 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001400 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001401 Stream.ExitBlock();
1402}
1403
Douglas Gregor49491f72013-03-15 22:15:07 +00001404namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001405
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001406/// An input file.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001407struct InputFileEntry {
1408 const FileEntry *File;
1409 bool IsSystemFile;
1410 bool IsTransient;
1411 bool BufferOverridden;
1412 bool IsTopLevelModuleMap;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001413 uint32_t ContentHash[2];
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001414};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001415
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001416} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001417
1418void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1419 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001420 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001421 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001422
Douglas Gregor72be3902012-10-19 00:38:02 +00001423 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001424
Douglas Gregor72be3902012-10-19 00:38:02 +00001425 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001426 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001427 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001428 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001429 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1430 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001431 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001432 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001433 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001434 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001435 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001436
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001437 // Create input file hash abbreviation.
1438 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1439 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1440 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1441 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1442 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1443
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001444 // Get all ContentCache objects for files, sorted by whether the file is a
1445 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001446 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001447 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1448 // Get this source location entry.
1449 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001450 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001451
1452 // We only care about file entries that were not overridden.
1453 if (!SLoc->isFile())
1454 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001455 const SrcMgr::FileInfo &File = SLoc->getFile();
1456 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001457 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001458 continue;
1459
Douglas Gregor49491f72013-03-15 22:15:07 +00001460 InputFileEntry Entry;
1461 Entry.File = Cache->OrigEntry;
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001462 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
Richard Smitha8cfffa2015-11-26 02:04:16 +00001463 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001464 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001465 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1466 File.getIncludeLoc().isInvalid();
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001467
1468 auto ContentHash = hash_code(-1);
1469 if (PP->getHeaderSearchInfo()
1470 .getHeaderSearchOpts()
1471 .ValidateASTInputFilesContent) {
1472 auto *MemBuff = Cache->getRawBuffer();
1473 if (MemBuff)
1474 ContentHash = hash_value(MemBuff->getBuffer());
1475 else
1476 // FIXME: The path should be taken from the FileEntryRef.
1477 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1478 << Entry.File->getName();
1479 }
1480 auto CH = llvm::APInt(64, ContentHash);
1481 Entry.ContentHash[0] =
1482 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1483 Entry.ContentHash[1] =
1484 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1485
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001486 if (Entry.IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001487 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001488 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001489 SortedFiles.push_front(Entry);
1490 }
1491
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001492 unsigned UserFilesNum = 0;
1493 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001494 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001495 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001496 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001497 if (InputFileID != 0)
1498 continue; // already recorded this file.
1499
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001500 // Record this entry's offset.
1501 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001502
1503 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001504
Douglas Gregor49491f72013-03-15 22:15:07 +00001505 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001506 ++UserFilesNum;
1507
Douglas Gregor72be3902012-10-19 00:38:02 +00001508 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001509 // And whether this file was overridden.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001510 {
1511 RecordData::value_type Record[] = {
1512 INPUT_FILE,
1513 InputFileOffsets.size(),
1514 (uint64_t)Entry.File->getSize(),
1515 (uint64_t)getTimestampForOutput(Entry.File),
1516 Entry.BufferOverridden,
1517 Entry.IsTransient,
1518 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001519
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001520 // FIXME: The path should be taken from the FileEntryRef.
1521 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1522 }
1523
1524 // Emit content hash for this file.
1525 {
1526 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1527 Entry.ContentHash[1]};
1528 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1529 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001530 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001531
Douglas Gregor112b9072012-10-18 05:31:06 +00001532 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001533
1534 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001535 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001536 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1537 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001538 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1539 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001540 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001541 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001542
1543 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001544 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1545 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001546 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001547}
1548
Douglas Gregora7f71a92009-04-10 03:52:48 +00001549//===----------------------------------------------------------------------===//
1550// Source Manager Serialization
1551//===----------------------------------------------------------------------===//
1552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001553/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001554/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001555static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001556 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001557
David Blaikieb44f0bf2017-01-04 22:36:43 +00001558 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001559 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001560 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001564 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001569 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001570}
1571
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001572/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001573/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001574static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001575 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001576
David Blaikieb44f0bf2017-01-04 22:36:43 +00001577 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001578 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001579 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1580 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001581 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001582 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1583 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001584 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001585}
1586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001587/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001588/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001589static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1590 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001591 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001592
David Blaikieb44f0bf2017-01-04 22:36:43 +00001593 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001594 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1595 : SM_SLOC_BUFFER_BLOB));
1596 if (Compressed)
1597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001599 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001600}
1601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001602/// Create an abbreviation for the SLocEntry that refers to a macro
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001603/// expansion.
1604static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001605 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001606
David Blaikieb44f0bf2017-01-04 22:36:43 +00001607 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001608 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1611 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1612 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Richard Smithb5f81712018-04-30 05:25:48 +00001613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
Douglas Gregor83243272009-04-15 18:05:10 +00001614 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001615 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001616}
1617
Douglas Gregor09b69892011-02-10 17:09:37 +00001618namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001619
Douglas Gregor09b69892011-02-10 17:09:37 +00001620 // Trait used for the on-disk hash table of header search information.
1621 class HeaderFileInfoTrait {
1622 ASTWriter &Writer;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001623
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001624 // Keep track of the framework names we've used during serialization.
1625 SmallVector<char, 128> FrameworkStringData;
1626 llvm::StringMap<unsigned> FrameworkNameOffset;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001627
Douglas Gregor09b69892011-02-10 17:09:37 +00001628 public:
Richard Smith040e1262017-06-02 01:55:39 +00001629 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1630
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001631 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001632 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001633 off_t Size;
1634 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001635 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001636 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001637
1638 using UnresolvedModule =
1639 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001640
Richard Smith040e1262017-06-02 01:55:39 +00001641 struct data_type {
1642 const HeaderFileInfo &HFI;
1643 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1644 UnresolvedModule Unresolved;
1645 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001646 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001647
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001648 using hash_value_type = unsigned;
1649 using offset_type = unsigned;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001650
Richard Smithe75ee0f2015-08-17 07:13:32 +00001651 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001652 // The hash is based only on size/time of the file, so that the reader can
1653 // match even when symlinking or excess path elements ("foo/../", "../")
1654 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001655 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001656 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001657
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001658 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001659 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001660 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001661
Peter Collingbournee3f65292018-05-18 19:46:24 +00001662 endian::Writer LE(Out, little);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001663 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001664 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001665 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001666 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001667 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1668 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001669 if (Data.Unresolved.getPointer())
1670 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001671 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001672 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001673 }
Richard Smith040e1262017-06-02 01:55:39 +00001674
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001675 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001676 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001677
Peter Collingbournee3f65292018-05-18 19:46:24 +00001678 endian::Writer LE(Out, little);
Richard Smith040e1262017-06-02 01:55:39 +00001679 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001680 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001681 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001682 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001683 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001684 }
Richard Smith040e1262017-06-02 01:55:39 +00001685
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001686 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001687 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001688 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001689
Peter Collingbournee3f65292018-05-18 19:46:24 +00001690 endian::Writer LE(Out, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001691 uint64_t Start = Out.tell(); (void)Start;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001692
Richard Smithf3f84612017-06-29 02:19:42 +00001693 unsigned char Flags = (Data.HFI.isImport << 5)
1694 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001695 | (Data.HFI.DirInfo << 1)
1696 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001697 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001698 LE.write<uint16_t>(Data.HFI.NumIncludes);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001699
Richard Smith040e1262017-06-02 01:55:39 +00001700 if (!Data.HFI.ControllingMacro)
1701 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001702 else
Richard Smith040e1262017-06-02 01:55:39 +00001703 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1704
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001705 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001706 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001707 // If this header refers into a framework, save the framework name.
1708 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00001709 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001710 if (Pos == FrameworkNameOffset.end()) {
1711 Offset = FrameworkStringData.size() + 1;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001712 FrameworkStringData.append(Data.HFI.Framework.begin(),
Richard Smith040e1262017-06-02 01:55:39 +00001713 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001714 FrameworkStringData.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001715
Richard Smith040e1262017-06-02 01:55:39 +00001716 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001717 } else
1718 Offset = Pos->second;
1719 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001720 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001721
Richard Smith040e1262017-06-02 01:55:39 +00001722 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1723 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1724 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00001725 assert((Value >> 2) == ModID && "overflow in header module info");
1726 LE.write<uint32_t>(Value);
1727 }
Richard Smith040e1262017-06-02 01:55:39 +00001728 };
1729
1730 // FIXME: If the header is excluded, we should write out some
1731 // record of that fact.
1732 for (auto ModInfo : Data.KnownHeaders)
1733 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1734 if (Data.Unresolved.getPointer())
1735 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001736
Douglas Gregor09b69892011-02-10 17:09:37 +00001737 assert(Out.tell() - Start == DataLen && "Wrong data length");
1738 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001739
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001740 const char *strings_begin() const { return FrameworkStringData.begin(); }
1741 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001742 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001743
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001744} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00001745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001746/// Write the header search block for the list of files that
Douglas Gregor09b69892011-02-10 17:09:37 +00001747///
1748/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001749void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00001750 HeaderFileInfoTrait GeneratorTrait(*this);
1751 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1752 SmallVector<const char *, 4> SavedStrings;
1753 unsigned NumHeaderSearchEntries = 0;
1754
1755 // Find all unresolved headers for the current module. We generally will
1756 // have resolved them before we get here, but not necessarily: we might be
1757 // compiling a preprocessed module, where there is no requirement for the
1758 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00001759 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00001760 if (WritingModule) {
1761 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1762 while (!Worklist.empty()) {
1763 Module *M = Worklist.pop_back_val();
Richard Smith6bc75022020-04-17 20:25:15 -07001764 // We don't care about headers in unimportable submodules.
1765 if (M->isUnimportable())
Richard Smith040e1262017-06-02 01:55:39 +00001766 continue;
1767
1768 // Map to disk files where possible, to pick up any missing stat
1769 // information. This also means we don't need to check the unresolved
1770 // headers list when emitting resolved headers in the first loop below.
1771 // FIXME: It'd be preferable to avoid doing this if we were given
1772 // sufficient stat information in the module map.
1773 HS.getModuleMap().resolveHeaderDirectives(M);
1774
1775 // If the file didn't exist, we can still create a module if we were given
1776 // enough information in the module map.
1777 for (auto U : M->MissingHeaders) {
1778 // Check that we were given enough information to build a module
1779 // without this file existing on disk.
1780 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1781 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1782 << WritingModule->getFullModuleName() << U.Size.hasValue()
1783 << U.FileName;
1784 continue;
1785 }
1786
1787 // Form the effective relative pathname for the file.
1788 SmallString<128> Filename(M->Directory->getName());
1789 llvm::sys::path::append(Filename, U.FileName);
1790 PreparePathForOutput(Filename);
1791
1792 StringRef FilenameDup = strdup(Filename.c_str());
1793 SavedStrings.push_back(FilenameDup.data());
1794
1795 HeaderFileInfoTrait::key_type Key = {
1796 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1797 };
1798 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00001799 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00001800 };
1801 // FIXME: Deal with cases where there are multiple unresolved header
1802 // directives in different submodules for the same header.
1803 Generator.insert(Key, Data, GeneratorTrait);
1804 ++NumHeaderSearchEntries;
1805 }
1806
1807 Worklist.append(M->submodule_begin(), M->submodule_end());
1808 }
1809 }
1810
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001811 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001812 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001813
Douglas Gregor09b69892011-02-10 17:09:37 +00001814 if (FilesByUID.size() > HS.header_file_size())
1815 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00001816
Douglas Gregor09b69892011-02-10 17:09:37 +00001817 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1818 const FileEntry *File = FilesByUID[UID];
1819 if (!File)
1820 continue;
1821
Richard Smith386bb072015-08-18 23:42:23 +00001822 // Get the file info. This will load info from the external source if
1823 // necessary. Skip emitting this file if we have no information on it
1824 // as a header file (in which case HFI will be null) or if it hasn't
1825 // changed since it was loaded. Also skip it if it's for a modular header
1826 // from a different module; in that case, we rely on the module(s)
1827 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001828 const HeaderFileInfo *HFI =
1829 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1830 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001831 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001832
Richard Smith7ed1bc92014-12-05 22:42:13 +00001833 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001834 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001835 SmallString<128> FilenameTmp(Filename);
1836 if (PreparePathForOutput(FilenameTmp)) {
1837 // If we performed any translation on the file name at all, we need to
1838 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001839 Filename = StringRef(strdup(FilenameTmp.c_str()));
1840 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00001841 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001842
Richard Smith040e1262017-06-02 01:55:39 +00001843 HeaderFileInfoTrait::key_type Key = {
1844 Filename, File->getSize(), getTimestampForOutput(File)
1845 };
1846 HeaderFileInfoTrait::data_type Data = {
Richard Smith0a088ea2020-04-28 18:22:34 -07001847 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
Richard Smith040e1262017-06-02 01:55:39 +00001848 };
1849 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001850 ++NumHeaderSearchEntries;
1851 }
Richard Smith040e1262017-06-02 01:55:39 +00001852
Douglas Gregor09b69892011-02-10 17:09:37 +00001853 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001854 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001855 uint32_t BucketOffset;
1856 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001857 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001858
Douglas Gregor09b69892011-02-10 17:09:37 +00001859 llvm::raw_svector_ostream Out(TableData);
1860 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00001861 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001862 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1863 }
1864
1865 // Create a blob abbreviation
1866 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001867
David Blaikieb44f0bf2017-01-04 22:36:43 +00001868 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00001869 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00001874 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001875
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001876 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001877 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1878 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001879 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001880 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001881
Douglas Gregor09b69892011-02-10 17:09:37 +00001882 // Free all of the strings we had to duplicate.
1883 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001884 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001885}
1886
George Rimarc39f5492017-01-17 15:45:31 +00001887static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1888 unsigned SLocBufferBlobCompressedAbbrv,
1889 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001890 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00001891
1892 // Compress the buffer if possible. We expect that almost all PCM
1893 // consumers will not want its contents.
1894 SmallString<0> CompressedBuffer;
1895 if (llvm::zlib::isAvailable()) {
1896 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1897 if (!E) {
1898 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1899 Blob.size() - 1};
1900 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1901 CompressedBuffer);
1902 return;
1903 }
1904 llvm::consumeError(std::move(E));
1905 }
1906
1907 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1908 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1909}
1910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001911/// Writes the block containing the serialized form of the
Douglas Gregora7f71a92009-04-10 03:52:48 +00001912/// source manager.
1913///
1914/// TODO: We should probably use an on-disk hash table (stored in a
1915/// blob), indexed based on the file name, so that we only create
1916/// entries for files that we actually need. In the common case (no
1917/// errors), we probably won't have to create file entries for any of
1918/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001919void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001920 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001921 RecordData Record;
1922
Chris Lattner0910e3b2009-04-10 17:16:57 +00001923 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001924 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01001925 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
Douglas Gregora7f71a92009-04-10 03:52:48 +00001926
1927 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001928 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1929 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001930 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1931 unsigned SLocBufferBlobCompressedAbbrv =
1932 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001933 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001934
Douglas Gregor258ae542009-04-27 06:38:32 +00001935 // Write out the source location entry table. We skip the first
1936 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001937 std::vector<uint32_t> SLocEntryOffsets;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001938 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
Douglas Gregor258ae542009-04-27 06:38:32 +00001939 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001940 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1941 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001942 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001943 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001944 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001945 FileID FID = FileID::get(I);
1946 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001947
Douglas Gregor258ae542009-04-27 06:38:32 +00001948 // Record the offset of this source-location entry.
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001949 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
1950 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
1951 SLocEntryOffsets.push_back(Offset);
Douglas Gregor258ae542009-04-27 06:38:32 +00001952
1953 // Figure out which record code to use.
1954 unsigned Code;
1955 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001956 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1957 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001958 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001959 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001960 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001961 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001962 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001963 Record.clear();
1964 Record.push_back(Code);
1965
Douglas Gregor925296b2011-07-19 16:10:42 +00001966 // Starting offset of this entry within this module, so skip the dummy.
1967 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001968 if (SLoc->isFile()) {
1969 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001970 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001971 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1972 Record.push_back(File.hasLineDirectives());
1973
1974 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001975 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001976 if (Content->OrigEntry) {
1977 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001978 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001979
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001980 // The source location entry is a file. Emit input file ID.
1981 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1982 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001984 Record.push_back(File.NumCreatedFIDs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001985
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001986 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001987 if (FDI != FileDeclIDs.end()) {
1988 Record.push_back(FDI->second->FirstDeclIndex);
1989 Record.push_back(FDI->second->DeclIDs.size());
1990 } else {
1991 Record.push_back(0);
1992 Record.push_back(0);
1993 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001994
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001995 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001996
Richard Smithaada85c2016-02-06 02:06:43 +00001997 if (Content->BufferOverridden || Content->IsTransient)
1998 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001999 } else {
2000 // The source location entry is a buffer. The blob associated
2001 // with this entry contains the contents of the buffer.
2002
2003 // We add one to the size so that we capture the trailing NULL
2004 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2005 // the reader side).
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00002006 const llvm::MemoryBuffer *Buffer =
2007 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00002008 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002009 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00002010 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00002011 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00002012
Mehdi Amini99d1b292016-10-01 16:38:28 +00002013 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00002014 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00002015 }
Richard Smithaada85c2016-02-06 02:06:43 +00002016
2017 if (EmitBlob) {
2018 // Include the implicit terminating null character in the on-disk buffer
2019 // if we're writing it uncompressed.
2020 const llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00002021 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Richard Smithaada85c2016-02-06 02:06:43 +00002022 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00002023 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2024 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00002025 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002026 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002027 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002028 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002029 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2030 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2031 AddSourceLocation(Expansion.isMacroArgExpansion()
2032 ? SourceLocation()
2033 : Expansion.getExpansionLocEnd(),
2034 Record);
Richard Smithb5f81712018-04-30 05:25:48 +00002035 Record.push_back(Expansion.isExpansionTokenRange());
Douglas Gregor258ae542009-04-27 06:38:32 +00002036
2037 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002038 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002039 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002040 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002041 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002042 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002043 }
2044 }
2045
Douglas Gregor8f45df52009-04-16 22:23:12 +00002046 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002047
2048 if (SLocEntryOffsets.empty())
2049 return;
2050
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002051 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002052 // table is used for lazily loading source-location information.
2053 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002054
David Blaikieb44f0bf2017-01-04 22:36:43 +00002055 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002056 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002057 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002058 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002059 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
Douglas Gregor258ae542009-04-27 06:38:32 +00002060 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00002061 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002062 {
2063 RecordData::value_type Record[] = {
2064 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002065 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01002066 SLocEntryOffsetsBase - SourceManagerBlockOffset};
Mehdi Amini57a41912015-09-10 01:46:39 +00002067 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2068 bytes(SLocEntryOffsets));
2069 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002070 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002071 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002072 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002073
2074 // Write the line table. It depends on remapping working, so it must come
2075 // after the source location offsets.
2076 if (SourceMgr.hasLineTable()) {
2077 LineTableInfo &LineTable = SourceMgr.getLineTable();
2078
2079 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002080
2081 // Emit the needed file names.
2082 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002083 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002084 for (const auto &L : LineTable) {
2085 if (L.first.ID < 0)
2086 continue;
2087 for (auto &LE : L.second) {
2088 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002089 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002090 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2091 }
2092 }
2093 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002094
2095 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002096 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002097 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002098 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002099 continue;
2100
2101 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002102 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002103
2104 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002105 Record.push_back(L.second.size());
2106 for (const auto &LE : L.second) {
2107 Record.push_back(LE.FileOffset);
2108 Record.push_back(LE.LineNo);
2109 Record.push_back(FilenameMap[LE.FilenameID]);
2110 Record.push_back((unsigned)LE.FileKind);
2111 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002112 }
2113 }
Richard Smith63078492015-09-01 07:41:55 +00002114
Douglas Gregor925296b2011-07-19 16:10:42 +00002115 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2116 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002117}
2118
Douglas Gregorc5046832009-04-27 18:38:38 +00002119//===----------------------------------------------------------------------===//
2120// Preprocessor Serialization
2121//===----------------------------------------------------------------------===//
2122
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002123static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2124 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002125 if (MacroInfo *MI = MD->getMacroInfo())
2126 if (MI->isBuiltinMacro())
2127 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002128
2129 if (IsModule) {
2130 SourceLocation Loc = MD->getLocation();
2131 if (Loc.isInvalid())
2132 return true;
2133 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2134 return true;
2135 }
2136
2137 return false;
2138}
2139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002140/// Writes the block containing the serialized form of the
Chris Lattnereeffaef2009-04-10 17:15:23 +00002141/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002142void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002143 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2144
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002145 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2146 if (PPRec)
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002147 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002148
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002149 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002150 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002151
Chris Lattner0af3ba12009-04-13 01:29:17 +00002152 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2153 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002154 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002155 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002156 }
2157
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002158 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2159 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002160 auto SkipInfo = PP.getPreambleSkipInfo();
2161 if (SkipInfo.hasValue()) {
2162 Record.push_back(true);
2163 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2164 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2165 Record.push_back(SkipInfo->FoundNonSkipPortion);
2166 Record.push_back(SkipInfo->FoundElse);
2167 AddSourceLocation(SkipInfo->ElseLoc, Record);
2168 } else {
2169 Record.push_back(false);
2170 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002171 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2172 AddSourceLocation(Cond.IfLoc, Record);
2173 Record.push_back(Cond.WasSkipping);
2174 Record.push_back(Cond.FoundNonSkip);
2175 Record.push_back(Cond.FoundElse);
2176 }
2177 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2178 Record.clear();
2179 }
2180
Douglas Gregoreda6a892009-04-26 00:07:37 +00002181 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002182 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002184 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002185 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002186 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002187 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002188
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002190 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002191
Richard Smithee977932015-05-01 21:22:17 +00002192 // Construct the list of identifiers with macro directives that need to be
2193 // serialized.
2194 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2195 for (auto &Id : PP.getIdentifierTable())
2196 if (Id.second->hadMacroDefinition() &&
2197 (!Id.second->isFromAST() ||
2198 Id.second->hasChangedSinceDeserialization()))
2199 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002200 // Sort the set of macro definitions that need to be serialized by the
2201 // name of the macro, to provide a stable ordering.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00002202 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002203
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002204 // Emit the macro directives as a list and associate the offset with the
2205 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002206 for (const IdentifierInfo *Name : MacroIdentifiers) {
2207 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002208 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2209 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
Richard Smithd7329392015-04-21 21:46:32 +00002210
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002211 // Emit the macro directives in reverse source order.
2212 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002213 // Once we hit an ignored macro, we're done: the rest of the chain
2214 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002215 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002216 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002217
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002218 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002219 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002220 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002221 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002222 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002223 Record.push_back(VisMD->isPublic());
2224 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002225 }
Richard Smithd7329392015-04-21 21:46:32 +00002226
Richard Smithb8b2ed62015-04-23 18:18:26 +00002227 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002228 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002229 // We write out exported module macros for PCH as well.
2230 auto Leafs = PP.getLeafModuleMacros(Name);
2231 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2232 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2233 while (!Worklist.empty()) {
2234 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002235
Manman Ren33d80292016-05-31 18:19:32 +00002236 // Emit a record indicating this submodule exports this macro.
2237 ModuleMacroRecord.push_back(
2238 getSubmoduleID(Macro->getOwningModule()));
2239 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2240 for (auto *M : Macro->overrides())
2241 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002242
Manman Ren33d80292016-05-31 18:19:32 +00002243 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2244 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002245
Manman Ren33d80292016-05-31 18:19:32 +00002246 // Enqueue overridden macros once we've visited all their ancestors.
2247 for (auto *M : Macro->overrides())
2248 if (++Visits[M] == M->getNumOverridingMacros())
2249 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002250
Manman Ren33d80292016-05-31 18:19:32 +00002251 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002252 }
Richard Smithd7329392015-04-21 21:46:32 +00002253
Richard Smithee977932015-05-01 21:22:17 +00002254 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002255 continue;
2256
Richard Smithd7329392015-04-21 21:46:32 +00002257 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002258 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2259 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002260 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002262 /// Offsets of each of the macros into the bitstream, indexed by
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002263 /// the local macro ID
2264 ///
2265 /// For each identifier that is associated with a macro, this map
2266 /// provides the offset into the bitstream where that macro is
2267 /// defined.
2268 std::vector<uint32_t> MacroOffsets;
2269
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002270 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2271 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2272 MacroInfo *MI = MacroInfosToEmit[I].MI;
2273 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002274
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002275 if (ID < FirstMacroID) {
2276 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2277 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002278 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002279
2280 // Record the local offset of this macro.
2281 unsigned Index = ID - FirstMacroID;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002282 if (Index >= MacroOffsets.size())
2283 MacroOffsets.resize(Index + 1);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002284
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002285 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2286 assert((Offset >> 32) == 0 && "Macro offset too large");
2287 MacroOffsets[Index] = Offset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002288
2289 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002290 AddSourceLocation(MI->getDefinitionLoc(), Record);
2291 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2292 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002293 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002294 unsigned Code;
2295 if (MI->isObjectLike()) {
2296 Code = PP_MACRO_OBJECT_LIKE;
2297 } else {
2298 Code = PP_MACRO_FUNCTION_LIKE;
2299
2300 Record.push_back(MI->isC99Varargs());
2301 Record.push_back(MI->isGNUVarargs());
2302 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002303 Record.push_back(MI->getNumParams());
2304 for (const IdentifierInfo *Param : MI->params())
2305 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002306 }
2307
2308 // If we have a detailed preprocessing record, record the macro definition
2309 // ID that corresponds to this macro.
2310 if (PPRec)
2311 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2312
2313 Stream.EmitRecord(Code, Record);
2314 Record.clear();
2315
2316 // Emit the tokens array.
2317 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2318 // Note that we know that the preprocessor does not have any annotation
2319 // tokens in it because they are created by the parser, and thus can't
2320 // be in a macro definition.
2321 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002322 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002323 Stream.EmitRecord(PP_TOKEN, Record);
2324 Record.clear();
2325 }
2326 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002327 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002328
Douglas Gregor92a96f52011-02-08 21:58:10 +00002329 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002330
2331 // Write the offsets table for macro IDs.
2332 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002333
David Blaikieb44f0bf2017-01-04 22:36:43 +00002334 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002335 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2336 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002338 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002339 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2340
David Blaikieb44f0bf2017-01-04 22:36:43 +00002341 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002342 {
2343 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002344 FirstMacroID - NUM_PREDEF_MACRO_IDS,
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01002345 MacroOffsetsBase - ASTBlockStartOffset};
Mehdi Amini57a41912015-09-10 01:46:39 +00002346 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2347 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002348}
2349
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002350void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2351 uint64_t MacroOffsetsBase) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002352 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002353 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002354
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002355 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002356
Douglas Gregor92a96f52011-02-08 21:58:10 +00002357 // Enter the preprocessor block.
2358 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002359
Douglas Gregoraae92242010-03-19 21:51:54 +00002360 // If the preprocessor has a preprocessing record, emit it.
2361 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002362 using namespace llvm;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002363
2364 // Set up the abbreviation for
Douglas Gregor92a96f52011-02-08 21:58:10 +00002365 unsigned InclusionAbbrev = 0;
2366 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002367 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002368 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002374 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002375 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002376
2377 unsigned FirstPreprocessorEntityID
2378 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002379 + NUM_PREDEF_PP_ENTITY_IDS;
2380 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002381 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002382 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2383 EEnd = PPRec.local_end();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002384 E != EEnd;
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002385 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002386 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002387
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002388 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2389 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
Richard Smith66a81862015-05-04 02:25:31 +00002390 PreprocessedEntityOffsets.push_back(
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002391 PPEntityOffset((*E)->getSourceRange(), Offset));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002392
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002393 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002394 // Record this macro definition's ID.
2395 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002396
Douglas Gregor92a96f52011-02-08 21:58:10 +00002397 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002398 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2399 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002400 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002401
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002402 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002403 Record.push_back(ME->isBuiltinMacro());
2404 if (ME->isBuiltinMacro())
2405 AddIdentifierRef(ME->getName(), Record);
2406 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002407 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002408 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002409 continue;
2410 }
2411
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002412 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002413 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002414 Record.push_back(ID->getFileName().size());
2415 Record.push_back(ID->wasInQuotes());
2416 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002417 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002418 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002419 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002420 // Check that the FileEntry is not null because it was not resolved and
2421 // we create a PCH even with compiler errors.
2422 if (ID->getFile())
2423 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002424 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002425 continue;
2426 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002427
Douglas Gregor92a96f52011-02-08 21:58:10 +00002428 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2429 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002430 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002431
Douglas Gregoraae92242010-03-19 21:51:54 +00002432 // Write the offsets table for the preprocessing record.
2433 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002434 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2435
Douglas Gregoraae92242010-03-19 21:51:54 +00002436 // Write the offsets table for identifier IDs.
2437 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002438
David Blaikieb44f0bf2017-01-04 22:36:43 +00002439 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002440 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002441 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002443 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002444
Mehdi Amini57a41912015-09-10 01:46:39 +00002445 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2446 FirstPreprocessorEntityID -
2447 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002448 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002449 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002450 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002451
2452 // Write the skipped region table for the preprocessing record.
2453 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2454 if (SkippedRanges.size() > 0) {
2455 std::vector<PPSkippedRange> SerializedSkippedRanges;
2456 SerializedSkippedRanges.reserve(SkippedRanges.size());
2457 for (auto const& Range : SkippedRanges)
2458 SerializedSkippedRanges.emplace_back(Range);
2459
2460 using namespace llvm;
2461 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2462 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2464 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2465
2466 Record.clear();
2467 Record.push_back(PPD_SKIPPED_RANGES);
2468 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2469 bytes(SerializedSkippedRanges));
2470 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002471}
2472
Richard Smith386bb072015-08-18 23:42:23 +00002473unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002474 if (!Mod)
2475 return 0;
2476
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002477 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2478 if (Known != SubmoduleIDs.end())
2479 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002480
Richard Smithdc1f0422016-07-20 19:10:16 +00002481 auto *Top = Mod->getTopLevelModule();
2482 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002483 (getLangOpts().CompilingPCH ||
2484 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002485 return 0;
2486
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002487 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2488}
2489
Richard Smith386bb072015-08-18 23:42:23 +00002490unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2491 // FIXME: This can easily happen, if we have a reference to a submodule that
2492 // did not result in us loading a module file for that submodule. For
2493 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2494 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2495 assert((ID || !Mod) &&
2496 "asked for module ID for non-local, non-imported module");
2497 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002498}
2499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002500/// Compute the number of modules within the given tree (including the
Douglas Gregor253eefe2011-12-01 00:59:36 +00002501/// given module).
2502static unsigned getNumberOfModules(Module *Mod) {
2503 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002504 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002505 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002506 ChildModules += getNumberOfModules(*Sub);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002507
Douglas Gregor253eefe2011-12-01 00:59:36 +00002508 return ChildModules + 1;
2509}
2510
Douglas Gregorde3ef502011-11-30 23:21:26 +00002511void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002512 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002513 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002514
Douglas Gregor69021972011-11-30 17:33:56 +00002515 // Write the abbreviations needed for the submodules block.
2516 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002517
David Blaikieb44f0bf2017-01-04 22:36:43 +00002518 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002519 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002521 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002522 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
Douglas Gregor69021972011-11-30 17:33:56 +00002532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002533 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002534
David Blaikieb44f0bf2017-01-04 22:36:43 +00002535 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002536 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002537 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002538 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002539
David Blaikieb44f0bf2017-01-04 22:36:43 +00002540 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002541 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002543 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002544
David Blaikieb44f0bf2017-01-04 22:36:43 +00002545 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002546 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002548 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002549
David Blaikieb44f0bf2017-01-04 22:36:43 +00002550 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002551 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002553 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002554
David Blaikieb44f0bf2017-01-04 22:36:43 +00002555 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002556 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002559 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002560
David Blaikieb44f0bf2017-01-04 22:36:43 +00002561 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002562 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002564 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002565
David Blaikieb44f0bf2017-01-04 22:36:43 +00002566 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002567 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002569 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002570
David Blaikieb44f0bf2017-01-04 22:36:43 +00002571 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002572 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2573 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002574 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002575
David Blaikieb44f0bf2017-01-04 22:36:43 +00002576 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002577 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2578 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002579 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002580
David Blaikieb44f0bf2017-01-04 22:36:43 +00002581 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002582 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2583 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002585 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002586
David Blaikieb44f0bf2017-01-04 22:36:43 +00002587 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002588 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002590 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002591
David Blaikieb44f0bf2017-01-04 22:36:43 +00002592 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002593 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2594 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2595 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002596 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002597
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002598 Abbrev = std::make_shared<BitCodeAbbrev>();
2599 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2601 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2602
Douglas Gregor253eefe2011-12-01 00:59:36 +00002603 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002604 RecordData::value_type Record[] = {
2605 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002606 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002607 Stream.EmitRecord(SUBMODULE_METADATA, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002608
Douglas Gregor69021972011-11-30 17:33:56 +00002609 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002610 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002611 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002612 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002613 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002614 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002615 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002616
2617 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002618 if (Mod->Parent) {
2619 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002620 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002621 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002622
2623 // Emit the definition of the block.
2624 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002625 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2626 ID,
2627 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002628 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002629 Mod->IsFramework,
2630 Mod->IsExplicit,
2631 Mod->IsSystem,
2632 Mod->IsExternC,
2633 Mod->InferSubmodules,
2634 Mod->InferExplicitSubmodules,
2635 Mod->InferExportWildcard,
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002636 Mod->ConfigMacrosExhaustive,
2637 Mod->ModuleMapIsPrivate};
Mehdi Amini57a41912015-09-10 01:46:39 +00002638 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2639 }
2640
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002641 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002642 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002643 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002644 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002645 }
2646
Douglas Gregor69021972011-11-30 17:33:56 +00002647 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002648 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002649 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002650 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2651 UmbrellaHeader.NameAsWritten);
2652 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002653 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2654 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002655 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002656 }
Richard Smith306d8922014-10-22 23:50:56 +00002657
Douglas Gregor69021972011-11-30 17:33:56 +00002658 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002659 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002660 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002661 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002662 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002663 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002664 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2665 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2666 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002667 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002668 Module::HK_PrivateTextual},
2669 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002670 };
2671 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002672 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002673 for (auto &H : Mod->Headers[HL.HeaderKind])
2674 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2675 }
2676
2677 // Emit the top headers.
2678 {
2679 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002680 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002681 for (auto *H : TopHeaders)
2682 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002683 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002684
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002685 // Emit the imports.
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002686 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002687 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002688 for (auto *I : Mod->Imports)
2689 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002690 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2691 }
2692
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002693 // Emit the exports.
Douglas Gregor24bb9232011-12-02 18:58:38 +00002694 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002695 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002696 for (const auto &E : Mod->Exports) {
2697 // FIXME: This may fail; we don't require that all exported modules
2698 // are local or imported.
2699 Record.push_back(getSubmoduleID(E.getPointer()));
2700 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002701 }
2702 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2703 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002704
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002705 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2706 // Might be unnecessary as use declarations are only used to build the
2707 // module itself.
2708
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002709 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002710 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002711 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2712 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002713 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002714 }
2715
Douglas Gregorfb912652013-03-20 21:10:35 +00002716 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002717 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002718 // FIXME: This may fail; we don't require that all conflicting modules
2719 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002720 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2721 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002722 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002723 }
2724
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002725 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002726 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002727 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002728 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002729 }
2730
Richard Smithdc1f0422016-07-20 19:10:16 +00002731 // Emit the initializers, if any.
2732 RecordData Inits;
2733 for (Decl *D : Context->getModuleInitializers(Mod))
2734 Inits.push_back(GetDeclRef(D));
2735 if (!Inits.empty())
2736 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2737
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002738 // Emit the name of the re-exported module, if any.
2739 if (!Mod->ExportAsModule.empty()) {
2740 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2741 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2742 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002743
Douglas Gregor69021972011-11-30 17:33:56 +00002744 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002745 for (auto *M : Mod->submodules())
2746 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002747 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002748
Douglas Gregor69021972011-11-30 17:33:56 +00002749 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002750
Richard Smith23d8d032015-05-14 00:45:20 +00002751 assert((NextSubmoduleID - FirstSubmoduleID ==
2752 getNumberOfModules(WritingModule)) &&
2753 "Wrong # of submodules; found a reference to a non-local, "
2754 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002755}
2756
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002757void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2758 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002759 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2760 DiagStateIDMap;
2761 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002762 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002763
Richard Smithe37391c2017-05-03 00:28:49 +00002764 auto EncodeDiagStateFlags =
2765 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2766 unsigned Result = (unsigned)DS->ExtBehavior;
2767 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00002768 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2769 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2770 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00002771 Result = (Result << 1) | Val;
2772 return Result;
2773 };
2774
2775 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2776 Record.push_back(Flags);
2777
Richard Smithd230de22017-01-26 01:01:01 +00002778 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2779 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00002780 // Ensure that the diagnostic state wasn't modified since it was created.
2781 // We will not correctly round-trip this information otherwise.
2782 assert(Flags == EncodeDiagStateFlags(State) &&
2783 "diag state flags vary in single AST file");
2784
Richard Smithd230de22017-01-26 01:01:01 +00002785 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002786 Record.push_back(DiagStateID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002787
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002788 if (DiagStateID == 0) {
2789 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002790
2791 // Add a placeholder for the number of mappings.
2792 auto SizeIdx = Record.size();
2793 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00002794 for (const auto &I : *State) {
2795 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002796 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00002797 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002798 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002799 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002800 // Update the placeholder.
2801 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00002802 }
2803 };
2804
2805 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00002806
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002807 // Reserve a spot for the number of locations with state transitions.
2808 auto NumLocationsIdx = Record.size();
2809 Record.emplace_back();
2810
2811 // Emit the state transitions.
2812 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00002813 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2814 if (!FileIDAndFile.first.isValid() ||
2815 !FileIDAndFile.second.HasLocalTransitions)
2816 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002817 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00002818
2819 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2820 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2821 AddSourceLocation(Loc, Record);
2822
Richard Smithd230de22017-01-26 01:01:01 +00002823 Record.push_back(FileIDAndFile.second.StateTransitions.size());
2824 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2825 Record.push_back(StatePoint.Offset);
2826 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002827 }
2828 }
2829
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002830 // Backpatch the number of locations.
2831 Record[NumLocationsIdx] = NumLocations;
2832
2833 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00002834 //
2835 // This also protects against a hypothetical corner case with simulating
2836 // -Werror settings for implicit modules in the ASTReader, where reading
2837 // CurDiagState out of context could change whether warning pragmas are
2838 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002839 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2840 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2841
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00002842 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002843}
2844
Douglas Gregorc5046832009-04-27 18:38:38 +00002845//===----------------------------------------------------------------------===//
2846// Type Serialization
2847//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002848
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002849/// Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002850void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002851 TypeIdx &IdxRef = TypeIdxs[T];
2852 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2853 IdxRef = TypeIdx(NextTypeID++);
2854 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002855
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002856 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002857
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002858 // Emit the type's representation.
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01002859 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
John McCall8ccfcb52009-09-24 19:53:00 +00002860
Richard Smith290d8012016-04-06 17:06:00 +00002861 // Record the offset for this type.
2862 unsigned Index = Idx.getIndex() - FirstTypeID;
2863 if (TypeOffsets.size() == Index)
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002864 TypeOffsets.emplace_back(Offset);
Richard Smith290d8012016-04-06 17:06:00 +00002865 else if (TypeOffsets.size() < Index) {
2866 TypeOffsets.resize(Index + 1);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002867 TypeOffsets[Index].setBitOffset(Offset);
John McCall8ccfcb52009-09-24 19:53:00 +00002868 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002869 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002870 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002871}
2872
Douglas Gregorc5046832009-04-27 18:38:38 +00002873//===----------------------------------------------------------------------===//
2874// Declaration Serialization
2875//===----------------------------------------------------------------------===//
2876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002877/// Write the block containing all of the declaration IDs
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002878/// lexically declared within the given DeclContext.
2879///
2880/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002881/// bitstream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002882uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002883 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002884 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002885 return 0;
2886
Douglas Gregor8f45df52009-04-16 22:23:12 +00002887 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002888 SmallVector<uint32_t, 128> KindDeclPairs;
2889 for (const auto *D : DC->decls()) {
2890 KindDeclPairs.push_back(D->getKind());
2891 KindDeclPairs.push_back(GetDeclRef(D));
2892 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002893
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002894 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002895 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002896 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2897 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002898 return Offset;
2899}
2900
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002901void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002902 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002903
2904 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002905 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002906 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002907 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002908 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002910 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002911 {
2912 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2913 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2914 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2915 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002916
2917 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002918 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002919 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002920 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002922 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002923 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002924 {
2925 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2926 FirstDeclID - NUM_PREDEF_DECL_IDS};
2927 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2928 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002929}
2930
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002931void ASTWriter::WriteFileDeclIDsMap() {
2932 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002933
David Blaikie409df392020-04-28 18:05:28 -07002934 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
2935 SortedFileDeclIDs.reserve(FileDeclIDs.size());
2936 for (const auto &P : FileDeclIDs)
2937 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
Fangrui Song55fab262018-09-26 22:16:28 +00002938 llvm::sort(SortedFileDeclIDs, llvm::less_first());
Chandler Carruthb306d732015-03-27 00:31:20 +00002939
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002940 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002941 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2942 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2943 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2944 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2945 for (auto &LocDeclEntry : Info.DeclIDs)
2946 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002947 }
2948
David Blaikieb44f0bf2017-01-04 22:36:43 +00002949 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002950 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002951 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002952 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002953 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002954 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2955 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002956 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002957}
2958
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002959void ASTWriter::WriteComments() {
2960 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Ilya Biryukov45643102018-07-09 11:33:23 +00002961 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2962 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2963 return;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002964 RecordData Record;
Jan Korousf31d8df2019-08-13 18:11:44 +00002965 for (const auto &FO : Context->Comments.OrderedComments) {
2966 for (const auto &OC : FO.second) {
2967 const RawComment *I = OC.second;
2968 Record.clear();
2969 AddSourceRange(I->getSourceRange(), Record);
2970 Record.push_back(I->getKind());
2971 Record.push_back(I->isTrailingComment());
2972 Record.push_back(I->isAlmostTrailingComment());
2973 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2974 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002975 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002976}
2977
Douglas Gregorc5046832009-04-27 18:38:38 +00002978//===----------------------------------------------------------------------===//
2979// Global Method Pool and Selector Serialization
2980//===----------------------------------------------------------------------===//
2981
Douglas Gregore84a9da2009-04-20 20:36:09 +00002982namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002983
Douglas Gregorc78d3462009-04-24 21:10:55 +00002984// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002985class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002986 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002987
2988public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002989 using key_type = Selector;
2990 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00002991
Sebastian Redl834bb972010-08-04 17:20:04 +00002992 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002993 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002994 ObjCMethodList Instance, Factory;
2995 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002996 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002997
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002998 using hash_value_type = unsigned;
2999 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003000
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003001 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00003002
Justin Bogner25463f12014-04-18 20:27:24 +00003003 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00003004 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003007 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003008 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00003009 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003010 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003011
Peter Collingbournee3f65292018-05-18 19:46:24 +00003012 endian::Writer LE(Out, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003013 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00003014 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00003015 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3016 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003017 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003018 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003019 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00003020 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003021 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003022 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003023 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00003024 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003025 return std::make_pair(KeyLen, DataLen);
3026 }
Mike Stump11289f42009-09-09 15:08:12 +00003027
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003028 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003029 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003030
Peter Collingbournee3f65292018-05-18 19:46:24 +00003031 endian::Writer LE(Out, little);
Mike Stump11289f42009-09-09 15:08:12 +00003032 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003033 assert((Start >> 32) == 0 && "Selector key offset too large");
3034 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003035 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00003036 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037 if (N == 0)
3038 N = 1;
3039 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00003040 LE.write<uint32_t>(
3041 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003044 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003045 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003046 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003047
Peter Collingbournee3f65292018-05-18 19:46:24 +00003048 endian::Writer LE(Out, little);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003049 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00003050 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003051 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003052 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003053 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003054 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003055 ++NumInstanceMethods;
3056
3057 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003058 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003059 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003060 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003061 ++NumFactoryMethods;
3062
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003063 unsigned InstanceBits = Methods.Instance.getBits();
3064 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003065 unsigned InstanceHasMoreThanOneDeclBit =
3066 Methods.Instance.hasMoreThanOneDecl();
3067 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3068 (InstanceHasMoreThanOneDeclBit << 2) |
3069 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003070 unsigned FactoryBits = Methods.Factory.getBits();
3071 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003072 unsigned FactoryHasMoreThanOneDeclBit =
3073 Methods.Factory.hasMoreThanOneDecl();
3074 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3075 (FactoryHasMoreThanOneDeclBit << 2) |
3076 FactoryBits;
3077 LE.write<uint16_t>(FullInstanceBits);
3078 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003079 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003080 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003081 if (Method->getMethod())
3082 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003083 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003084 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003085 if (Method->getMethod())
3086 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003087
3088 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003089 }
3090};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003091
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003092} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003094/// Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003095///
3096/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003097/// in an on-disk hash table indexed by the selector. The hash table also
3098/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003099void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003100 using namespace llvm;
3101
Sebastian Redla19a67f2010-08-03 21:58:15 +00003102 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003103 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003104 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003105 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003106 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003107 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003108 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003109 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003110
Sebastian Redla19a67f2010-08-03 21:58:15 +00003111 // Create the on-disk hash table representation. We walk through every
3112 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003113 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003114 for (auto &SelectorAndID : SelectorIDs) {
3115 Selector S = SelectorAndID.first;
3116 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003117 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003118 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003119 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003120 ObjCMethodList(),
3121 ObjCMethodList()
3122 };
3123 if (F != SemaRef.MethodPool.end()) {
3124 Data.Instance = F->second.first;
3125 Data.Factory = F->second.second;
3126 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003127 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003128 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003129 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003130 // Selector already exists. Did it change?
3131 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003132 for (ObjCMethodList *M = &Data.Instance;
3133 !changed && M && M->getMethod(); M = M->getNext()) {
3134 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003135 changed = true;
3136 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003137 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003138 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003139 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003140 changed = true;
3141 }
3142 if (!changed)
3143 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003144 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003145 // A new method pool entry.
3146 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003147 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003148 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003149 }
3150
Douglas Gregorc78d3462009-04-24 21:10:55 +00003151 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003152 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003153 uint32_t BucketOffset;
3154 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003155 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003156
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003157 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003158 llvm::raw_svector_ostream Out(MethodPool);
3159 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003160 endian::write<uint32_t>(Out, 0, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003161 BucketOffset = Generator.Emit(Out, Trait);
3162 }
3163
3164 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003165 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003166 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003167 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003170 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003171
Douglas Gregor95c13f52009-04-25 17:48:32 +00003172 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003173 {
3174 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3175 NumTableEntries};
3176 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3177 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003178
3179 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003180 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003181 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003183 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003184 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003185 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003186
3187 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003188 {
3189 RecordData::value_type Record[] = {
3190 SELECTOR_OFFSETS, SelectorOffsets.size(),
3191 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3192 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3193 bytes(SelectorOffsets));
3194 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003195 }
3196}
3197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003198/// Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003199void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003200 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003201
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003202 if (SemaRef.ReferencedSelectors.empty())
3203 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003204
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003205 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003206 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003207
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003208 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003209 // very tricky to fix, and given that @selector shouldn't really appear in
3210 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003211 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3212 Selector Sel = SelectorAndLocation.first;
3213 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003214 Writer.AddSelectorRef(Sel);
3215 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003216 }
Richard Smithe64e7452016-04-18 21:54:58 +00003217 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003218}
3219
Douglas Gregorc5046832009-04-27 18:38:38 +00003220//===----------------------------------------------------------------------===//
3221// Identifier Table Serialization
3222//===----------------------------------------------------------------------===//
3223
Richard Smithb3761912015-02-05 23:08:52 +00003224/// Determine the declaration that should be put into the name lookup table to
3225/// represent the given declaration in this module. This is usually D itself,
3226/// but if D was imported and merged into a local declaration, we want the most
3227/// recent local declaration instead. The chosen declaration will be the most
3228/// recent declaration in any module that imports this one.
3229static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3230 NamedDecl *D) {
3231 if (!LangOpts.Modules || !D->isFromASTFile())
3232 return D;
3233
3234 if (Decl *Redecl = D->getPreviousDecl()) {
3235 // For Redeclarable decls, a prior declaration might be local.
3236 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003237 // If we find a local decl, we're done.
3238 if (!Redecl->isFromASTFile()) {
3239 // Exception: in very rare cases (for injected-class-names), not all
3240 // redeclarations are in the same semantic context. Skip ones in a
3241 // different context. They don't go in this lookup table at all.
3242 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3243 D->getDeclContext()->getRedeclContext()))
3244 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003245 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003246 }
3247
Richard Smithfe620d22015-03-05 23:24:12 +00003248 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003249 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003250 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003251 break;
3252 }
3253 } else if (Decl *First = D->getCanonicalDecl()) {
3254 // For Mergeable decls, the first decl might be local.
3255 if (!First->isFromASTFile())
3256 return cast<NamedDecl>(First);
3257 }
3258
3259 // All declarations are imported. Our most recent declaration will also be
3260 // the most recent one in anyone who imports us.
3261 return D;
3262}
3263
Douglas Gregorc78d3462009-04-24 21:10:55 +00003264namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003265
Richard Smithcf97cf62015-04-19 01:34:23 +00003266class ASTIdentifierTableTrait {
3267 ASTWriter &Writer;
3268 Preprocessor &PP;
3269 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003270 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003271 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003272 ASTWriter::RecordData *InterestingIdentifierOffsets;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003273
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003274 /// Determines whether this is an "interesting" identifier that needs a
Richard Smithcf97cf62015-04-19 01:34:23 +00003275 /// full IdentifierInfo structure written into the hash table. Notably, this
3276 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3277 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003278 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003279 if (MacroOffset ||
3280 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003281 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003282 II->hasRevertedTokenIDToIdentifier() ||
Bruno Ricci366ba732018-09-21 12:53:22 +00003283 (NeedDecls && II->getFETokenInfo()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003284 return true;
3285
3286 return false;
3287 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003288
Douglas Gregore84a9da2009-04-20 20:36:09 +00003289public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003290 using key_type = IdentifierInfo *;
3291 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003292
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003293 using data_type = IdentID;
3294 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003295
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003296 using hash_value_type = unsigned;
3297 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003298
Richard Smithd7329392015-04-21 21:46:32 +00003299 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003300 IdentifierResolver &IdResolver, bool IsModule,
3301 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003302 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003303 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3304 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003305
Richard Smithd79514e2016-02-05 19:03:40 +00003306 bool needDecls() const { return NeedDecls; }
3307
Justin Bogner25463f12014-04-18 20:27:24 +00003308 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003309 return llvm::djbHash(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003310 }
Mike Stump11289f42009-09-09 15:08:12 +00003311
Richard Smith33e0f7e2015-07-22 02:08:40 +00003312 bool isInterestingIdentifier(const IdentifierInfo *II) {
3313 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3314 return isInterestingIdentifier(II, MacroOffset);
3315 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003316
Richard Smith9c254182015-07-19 21:41:12 +00003317 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3318 return isInterestingIdentifier(II, 0);
3319 }
3320
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003321 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003322 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003323 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003324 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003325 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3326 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003327 DataLen += 2; // 2 bytes for builtin ID
3328 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003329 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003330 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003331
Richard Smitha534a312015-07-21 23:54:07 +00003332 if (NeedDecls) {
3333 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3334 DEnd = IdResolver.end();
3335 D != DEnd; ++D)
3336 DataLen += 4;
3337 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003338 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003339
Justin Bognere1c147c2014-03-28 22:03:19 +00003340 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003341
Peter Collingbournee3f65292018-05-18 19:46:24 +00003342 endian::Writer LE(Out, little);
Justin Bognere1c147c2014-03-28 22:03:19 +00003343
Richard Smithdf8a8312015-03-13 04:05:01 +00003344 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003345 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003346 // We emit the key length after the data length so that every
3347 // string is preceded by a 16-bit length. This matches the PTH
3348 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003349 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003350 return std::make_pair(KeyLen, DataLen);
3351 }
Mike Stump11289f42009-09-09 15:08:12 +00003352
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003353 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003354 unsigned KeyLen) {
3355 // Record the location of the key data. This is used when generating
3356 // the mapping from persistent IDs to strings.
3357 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003358
3359 // Emit the offset of the key/data length information to the interesting
3360 // identifiers table if necessary.
3361 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3362 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3363
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003364 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003365 }
Mike Stump11289f42009-09-09 15:08:12 +00003366
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003367 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003368 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003369 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003370
Peter Collingbournee3f65292018-05-18 19:46:24 +00003371 endian::Writer LE(Out, little);
Richard Smithcf97cf62015-04-19 01:34:23 +00003372
Richard Smithd7329392015-04-21 21:46:32 +00003373 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3374 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003375 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003376 return;
3377 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003378
Justin Bognere1c147c2014-03-28 22:03:19 +00003379 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003380 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3381 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003382 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003383 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003384 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003385 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003386 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3387 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003388 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003389 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003390 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003391 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003392
Richard Smithd7329392015-04-21 21:46:32 +00003393 if (HadMacroDefinition)
3394 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003395
Richard Smitha534a312015-07-21 23:54:07 +00003396 if (NeedDecls) {
3397 // Emit the declaration IDs in reverse order, because the
3398 // IdentifierResolver provides the declarations as they would be
3399 // visible (e.g., the function "stat" would come before the struct
3400 // "stat"), but the ASTReader adds declarations to the end of the list
3401 // (so we need to see the struct "stat" before the function "stat").
3402 // Only emit declarations that aren't from a chained PCH, though.
3403 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3404 IdResolver.end());
3405 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3406 DEnd = Decls.rend();
3407 D != DEnd; ++D)
3408 LE.write<uint32_t>(
3409 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3410 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003411 }
3412};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003413
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003414} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003415
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003416/// Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003417///
3418/// The identifier table consists of a blob containing string data
3419/// (the actual identifiers themselves) and a separate "offsets" index
3420/// that maps identifier IDs to locations within the blob.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003421void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003422 IdentifierResolver &IdResolver,
3423 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003424 using namespace llvm;
3425
Richard Smith33e0f7e2015-07-22 02:08:40 +00003426 RecordData InterestingIdents;
3427
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003428 // Create and write out the blob that contains the identifier
3429 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003430 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003431 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003432 ASTIdentifierTableTrait Trait(
3433 *this, PP, IdResolver, IsModule,
3434 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregore6648fb2009-04-28 20:33:11 +00003436 // Look for any identifiers that were named while processing the
3437 // headers, but are otherwise not needed. We add these to the hash
3438 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003439 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003440 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003441 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003442 for (const auto &ID : PP.getIdentifierTable())
3443 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003444 // Sort the identifiers lexicographically before getting them references so
3445 // that their order is stable.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00003446 llvm::sort(IIs, llvm::deref<std::less<>>());
Chandler Carruth8440c982015-03-26 23:54:15 +00003447 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003448 if (Trait.isInterestingNonMacroIdentifier(II))
3449 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003450
Sebastian Redlff4a2952010-07-23 23:49:55 +00003451 // Create the on-disk hash table representation. We only store offsets
3452 // for identifiers that appear here for the first time.
3453 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003454 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003455 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003456 IdentID ID = IdentIDPair.second;
3457 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003458 // Write out identifiers if either the ID is local or the identifier has
3459 // changed since it was loaded.
3460 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3461 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003462 (Trait.needDecls() &&
3463 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003464 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003465 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003466
Douglas Gregore84a9da2009-04-20 20:36:09 +00003467 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003468 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003469 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003470 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003471 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003472
Douglas Gregore84a9da2009-04-20 20:36:09 +00003473 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003474 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003475 endian::write<uint32_t>(Out, 0, little);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003476 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003477 }
3478
3479 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003480 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003481 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003484 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003485
3486 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003487 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003488 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003489 }
3490
3491 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003492 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003493 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003494 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003496 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003497 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003498
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003499#ifndef NDEBUG
3500 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3501 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3502#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003503
3504 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3505 IdentifierOffsets.size(),
3506 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003507 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003508 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003509
3510 // In C++, write the list of interesting identifiers (those that are
3511 // defined as macros, poisoned, or similar unusual things).
3512 if (!InterestingIdents.empty())
3513 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003514}
3515
Douglas Gregorc5046832009-04-27 18:38:38 +00003516//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003517// DeclContext's Name Lookup Table Serialization
3518//===----------------------------------------------------------------------===//
3519
3520namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003521
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003522// Trait used for the on-disk hash table used in the method pool.
3523class ASTDeclContextNameLookupTrait {
3524 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003525 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003526
3527public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003528 using key_type = DeclarationNameKey;
3529 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003530
Richard Smithd88a7f12015-09-01 20:35:42 +00003531 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003532 using data_type = std::pair<unsigned, unsigned>;
3533 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003534
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003535 using hash_value_type = unsigned;
3536 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003537
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003538 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003539
Richard Smithd88a7f12015-09-01 20:35:42 +00003540 template<typename Coll>
3541 data_type getData(const Coll &Decls) {
3542 unsigned Start = DeclIDs.size();
3543 for (NamedDecl *D : Decls) {
3544 DeclIDs.push_back(
3545 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3546 }
3547 return std::make_pair(Start, DeclIDs.size());
3548 }
3549
3550 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3551 unsigned Start = DeclIDs.size();
3552 for (auto ID : FromReader)
3553 DeclIDs.push_back(ID);
3554 return std::make_pair(Start, DeclIDs.size());
3555 }
3556
3557 static bool EqualKey(key_type_ref a, key_type_ref b) {
3558 return a == b;
3559 }
3560
Richard Smitha06c7e62015-08-26 23:55:49 +00003561 hash_value_type ComputeHash(DeclarationNameKey Name) {
3562 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003563 }
3564
Richard Smithd88a7f12015-09-01 20:35:42 +00003565 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3566 assert(Writer.hasChain() &&
3567 "have reference to loaded module file but no chain?");
3568
3569 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003570
Peter Collingbournee3f65292018-05-18 19:46:24 +00003571 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
Richard Smithd88a7f12015-09-01 20:35:42 +00003572 }
3573
Richard Smitha06c7e62015-08-26 23:55:49 +00003574 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3575 DeclarationNameKey Name,
3576 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003577 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003578
Peter Collingbournee3f65292018-05-18 19:46:24 +00003579 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003580 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003581 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003582 case DeclarationName::Identifier:
3583 case DeclarationName::ObjCZeroArgSelector:
3584 case DeclarationName::ObjCOneArgSelector:
3585 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003586 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003587 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003588 KeyLen += 4;
3589 break;
3590 case DeclarationName::CXXOperatorName:
3591 KeyLen += 1;
3592 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003593 case DeclarationName::CXXConstructorName:
3594 case DeclarationName::CXXDestructorName:
3595 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003596 case DeclarationName::CXXUsingDirective:
3597 break;
3598 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003599 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003600
Richard Smithf02662d2015-07-30 03:17:16 +00003601 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003602 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3603 assert(uint16_t(DataLen) == DataLen &&
3604 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003605 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003606
3607 return std::make_pair(KeyLen, DataLen);
3608 }
3609
Richard Smitha06c7e62015-08-26 23:55:49 +00003610 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003611 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003612
Peter Collingbournee3f65292018-05-18 19:46:24 +00003613 endian::Writer LE(Out, little);
Richard Smitha06c7e62015-08-26 23:55:49 +00003614 LE.write<uint8_t>(Name.getKind());
3615 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003616 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003617 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003618 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003619 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003620 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003621 case DeclarationName::ObjCZeroArgSelector:
3622 case DeclarationName::ObjCOneArgSelector:
3623 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003624 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003625 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003626 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003627 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003628 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003629 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003630 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003631 case DeclarationName::CXXConstructorName:
3632 case DeclarationName::CXXDestructorName:
3633 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003634 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003635 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003636 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003637
3638 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003639 }
3640
Richard Smitha06c7e62015-08-26 23:55:49 +00003641 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3642 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003643 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003644
Peter Collingbournee3f65292018-05-18 19:46:24 +00003645 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003646 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003647 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3648 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003649 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3650 }
3651};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003652
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003653} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003654
Chandler Carruthe972c362015-03-26 03:11:40 +00003655bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3656 DeclContext *DC) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003657 return Result.hasExternalDecls() &&
3658 DC->hasNeedToReconcileExternalVisibleStorage();
Chandler Carruthe972c362015-03-26 03:11:40 +00003659}
3660
3661bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3662 DeclContext *DC) {
3663 for (auto *D : Result.getLookupResult())
3664 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3665 return false;
3666
3667 return true;
3668}
3669
Richard Smithd88a7f12015-09-01 20:35:42 +00003670void
Chandler Carruthe972c362015-03-26 03:11:40 +00003671ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003672 llvm::SmallVectorImpl<char> &LookupTable) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003673 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3674 !ConstDC->hasLazyExternalLexicalLookups() &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003675 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003676
Chandler Carruthe972c362015-03-26 03:11:40 +00003677 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003678 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003679 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3680
3681 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003682 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3683 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003684 ASTDeclContextNameLookupTrait Trait(*this);
3685
Chandler Carruthe972c362015-03-26 03:11:40 +00003686 // The first step is to collect the declaration names which we need to
3687 // serialize into the name lookup table, and to collect them in a stable
3688 // order.
3689 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003690
Chandler Carruthe972c362015-03-26 03:11:40 +00003691 // We also build up small sets of the constructor and conversion function
3692 // names which are visible.
3693 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003694
Chandler Carruthe972c362015-03-26 03:11:40 +00003695 for (auto &Lookup : *DC->buildLookup()) {
3696 auto &Name = Lookup.first;
3697 auto &Result = Lookup.second;
3698
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003699 // If there are no local declarations in our lookup result, we
3700 // don't need to write an entry for the name at all. If we can't
3701 // write out a lookup set without performing more deserialization,
3702 // just skip this entry.
3703 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003704 isLookupResultEntirelyExternal(Result, DC))
3705 continue;
3706
3707 // We also skip empty results. If any of the results could be external and
3708 // the currently available results are empty, then all of the results are
3709 // external and we skip it above. So the only way we get here with an empty
3710 // results is when no results could have been external *and* we have
3711 // external results.
3712 //
3713 // FIXME: While we might want to start emitting on-disk entries for negative
3714 // lookups into a decl context as an optimization, today we *have* to skip
3715 // them because there are names with empty lookup results in decl contexts
3716 // which we can't emit in any stable ordering: we lookup constructors and
3717 // conversion functions in the enclosing namespace scope creating empty
3718 // results for them. This in almost certainly a bug in Clang's name lookup,
3719 // but that is likely to be hard or impossible to fix and so we tolerate it
3720 // here by omitting lookups with empty results.
3721 if (Lookup.second.getLookupResult().empty())
3722 continue;
3723
3724 switch (Lookup.first.getNameKind()) {
3725 default:
3726 Names.push_back(Lookup.first);
3727 break;
3728
Richard Smithcd45dbc2014-04-19 03:48:30 +00003729 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003730 assert(isa<CXXRecordDecl>(DC) &&
3731 "Cannot have a constructor name outside of a class!");
3732 ConstructorNameSet.insert(Name);
3733 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003734
3735 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003736 assert(isa<CXXRecordDecl>(DC) &&
3737 "Cannot have a conversion function name outside of a class!");
3738 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003739 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003740 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003741 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003742
Chandler Carruthe972c362015-03-26 03:11:40 +00003743 // Sort the names into a stable order.
Fangrui Song55fab262018-09-26 22:16:28 +00003744 llvm::sort(Names);
Chandler Carruthe972c362015-03-26 03:11:40 +00003745
Chandler Carruthffbf7052015-03-26 22:27:09 +00003746 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003747 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003748 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003749
Chandler Carruthffbf7052015-03-26 22:27:09 +00003750 // First we try the easy case by forming the current context's constructor
3751 // name and adding that name first. This is a very useful optimization to
3752 // avoid walking the lexical declarations in many cases, and it also
3753 // handles the only case where a constructor name can come from some other
3754 // lexical context -- when that name is an implicit constructor merged from
3755 // another declaration in the redecl chain. Any non-implicit constructor or
3756 // conversion function which doesn't occur in all the lexical contexts
3757 // would be an ODR violation.
3758 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3759 Context->getCanonicalType(Context->getRecordType(D)));
3760 if (ConstructorNameSet.erase(ImplicitCtorName))
3761 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003762
Chandler Carruthffbf7052015-03-26 22:27:09 +00003763 // If we still have constructors or conversion functions, we walk all the
3764 // names in the decl and add the constructors and conversion functions
3765 // which are visible in the order they lexically occur within the context.
3766 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3767 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3768 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3769 auto Name = ChildND->getDeclName();
3770 switch (Name.getNameKind()) {
3771 default:
3772 continue;
3773
3774 case DeclarationName::CXXConstructorName:
3775 if (ConstructorNameSet.erase(Name))
3776 Names.push_back(Name);
3777 break;
3778
3779 case DeclarationName::CXXConversionFunctionName:
3780 if (ConversionNameSet.erase(Name))
3781 Names.push_back(Name);
3782 break;
3783 }
3784
3785 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3786 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003787 }
3788
Chandler Carruthe972c362015-03-26 03:11:40 +00003789 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3790 "constructors by walking all the "
3791 "lexical members of the context.");
3792 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3793 "conversion functions by walking all "
3794 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003795 }
3796
Chandler Carruthe972c362015-03-26 03:11:40 +00003797 // Next we need to do a lookup with each name into this decl context to fully
3798 // populate any results from external sources. We don't actually use the
3799 // results of these lookups because we only want to use the results after all
3800 // results have been loaded and the pointers into them will be stable.
3801 for (auto &Name : Names)
3802 DC->lookup(Name);
3803
3804 // Now we need to insert the results for each name into the hash table. For
3805 // constructor names and conversion function names, we actually need to merge
3806 // all of the results for them into one list of results each and insert
3807 // those.
3808 SmallVector<NamedDecl *, 8> ConstructorDecls;
3809 SmallVector<NamedDecl *, 8> ConversionDecls;
3810
3811 // Now loop over the names, either inserting them or appending for the two
3812 // special cases.
3813 for (auto &Name : Names) {
3814 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3815
3816 switch (Name.getNameKind()) {
3817 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003818 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003819 break;
3820
3821 case DeclarationName::CXXConstructorName:
3822 ConstructorDecls.append(Result.begin(), Result.end());
3823 break;
3824
3825 case DeclarationName::CXXConversionFunctionName:
3826 ConversionDecls.append(Result.begin(), Result.end());
3827 break;
3828 }
3829 }
3830
3831 // Handle our two special cases if we ended up having any. We arbitrarily use
3832 // the first declaration's name here because the name itself isn't part of
3833 // the key, only the kind of name is used.
3834 if (!ConstructorDecls.empty())
3835 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003836 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003837 if (!ConversionDecls.empty())
3838 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003839 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003840
Richard Smithd88a7f12015-09-01 20:35:42 +00003841 // Create the on-disk hash table. Also emit the existing imported and
3842 // merged table if there is one.
3843 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3844 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003845}
3846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003847/// Write the block containing all of the declaration IDs
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003848/// visible from the given DeclContext.
3849///
3850/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003851/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003852uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3853 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003854 // If we imported a key declaration of this namespace, write the visible
3855 // lookup results as an update record for it rather than including them
3856 // on this declaration. We will only look at key declarations on reload.
3857 if (isa<NamespaceDecl>(DC) && Chain &&
3858 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3859 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003860 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003861 Prev = Prev->getPreviousDecl())
3862 if (!Prev->isFromASTFile())
3863 return 0;
3864
3865 // Note that we need to emit an update record for the primary context.
3866 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3867
3868 // Make sure all visible decls are written. They will be recorded later. We
3869 // do this using a side data structure so we can sort the names into
3870 // a deterministic order.
3871 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3872 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3873 LookupResults;
3874 if (Map) {
3875 LookupResults.reserve(Map->size());
3876 for (auto &Entry : *Map)
3877 LookupResults.push_back(
3878 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3879 }
3880
Fangrui Song55fab262018-09-26 22:16:28 +00003881 llvm::sort(LookupResults, llvm::less_first());
Richard Smith5fc18a92015-07-12 23:43:21 +00003882 for (auto &NameAndResult : LookupResults) {
3883 DeclarationName Name = NameAndResult.first;
3884 DeclContext::lookup_result Result = NameAndResult.second;
3885 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3886 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3887 // We have to work around a name lookup bug here where negative lookup
3888 // results for these names get cached in namespace lookup tables (these
3889 // names should never be looked up in a namespace).
3890 assert(Result.empty() && "Cannot have a constructor or conversion "
3891 "function name in a namespace!");
3892 continue;
3893 }
3894
3895 for (NamedDecl *ND : Result)
3896 if (!ND->isFromASTFile())
3897 GetDeclRef(ND);
3898 }
3899
3900 return 0;
3901 }
3902
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003903 if (DC->getPrimaryContext() != DC)
3904 return 0;
3905
Chandler Carruthe972c362015-03-26 03:11:40 +00003906 // Skip contexts which don't support name lookup.
3907 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003908 return 0;
3909
3910 // If not in C++, we perform name lookup for the translation unit via the
3911 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003912 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003913 return 0;
3914
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003915 // Serialize the contents of the mapping used for lookup. Note that,
3916 // although we have two very different code paths, the serialized
3917 // representation is the same for both cases: a declaration name,
3918 // followed by a size, followed by references to the visible
3919 // declarations that have that name.
3920 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003921 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003922 if (!Map || Map->empty())
3923 return 0;
3924
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003925 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003926 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003927 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003928
3929 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003930 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003931 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003932 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003933 ++NumVisibleDeclContexts;
3934 return Offset;
3935}
3936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003937/// Write an UPDATE_VISIBLE block for the given context.
Sebastian Redla4071b42010-08-24 00:50:09 +00003938///
3939/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3940/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003941/// (in C++), for namespaces, and for classes with forward-declared unscoped
3942/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003943void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003944 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003945 if (!Map || Map->empty())
3946 return;
3947
Sebastian Redla4071b42010-08-24 00:50:09 +00003948 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003949 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003950 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003951
Richard Smith5fc18a92015-07-12 23:43:21 +00003952 // If we're updating a namespace, select a key declaration as the key for the
3953 // update record; those are the only ones that will be checked on reload.
3954 if (isa<NamespaceDecl>(DC))
3955 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3956
Sebastian Redla4071b42010-08-24 00:50:09 +00003957 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003958 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003959 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003960}
3961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003962/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
Melanie Blower95187632020-06-26 07:54:01 -07003963void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07003964 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003965 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3966}
3967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003968/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003969void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003970 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003971 return;
3972
3973 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3974 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00003975 for (const auto &I:Opts.OptMap) {
3976 AddString(I.getKey(), Record);
3977 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00003978 Record.push_back(V.Supported ? 1 : 0);
3979 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00003980 Record.push_back(V.Avail);
3981 Record.push_back(V.Core);
3982 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003983 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3984}
3985
Yaxun Liu5b746652016-12-18 05:18:55 +00003986void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3987 if (!SemaRef.Context.getLangOpts().OpenCL)
3988 return;
3989
Bruno Ricci2751b692019-04-18 15:13:27 +00003990 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3991 // without copying them.
3992 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3993 SemaRef.OpenCLTypeExtMap;
3994 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3995 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3996 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3997
3998 for (const auto &I : OpenCLTypeExtMap)
3999 StableOpenCLTypeExtMap.emplace_back(
4000 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
4001
4002 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4003 return E1.first < E2.first;
4004 };
4005 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
4006
Yaxun Liu5b746652016-12-18 05:18:55 +00004007 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00004008 for (const ElementTy &E : StableOpenCLTypeExtMap) {
4009 Record.push_back(E.first); // TypeID
4010 const std::set<std::string> *ExtSet = E.second;
4011 Record.push_back(static_cast<unsigned>(ExtSet->size()));
4012 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00004013 AddString(Ext, Record);
4014 }
Bruno Ricci2751b692019-04-18 15:13:27 +00004015
Yaxun Liu5b746652016-12-18 05:18:55 +00004016 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4017}
4018
4019void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4020 if (!SemaRef.Context.getLangOpts().OpenCL)
4021 return;
4022
Bruno Ricci2751b692019-04-18 15:13:27 +00004023 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
4024 // without copying them.
4025 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
4026 SemaRef.OpenCLDeclExtMap;
4027 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
4028 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
4029 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
4030
4031 for (const auto &I : OpenCLDeclExtMap)
4032 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4033
4034 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4035 return E1.first < E2.first;
4036 };
4037 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4038
Yaxun Liu5b746652016-12-18 05:18:55 +00004039 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00004040 for (const ElementTy &E : StableOpenCLDeclExtMap) {
4041 Record.push_back(E.first); // DeclID
4042 const std::set<std::string> *ExtSet = E.second;
4043 Record.push_back(static_cast<unsigned>(ExtSet->size()));
4044 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00004045 AddString(Ext, Record);
4046 }
Bruno Ricci2751b692019-04-18 15:13:27 +00004047
Yaxun Liu5b746652016-12-18 05:18:55 +00004048 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4049}
4050
Justin Lebar67a78a62016-10-08 22:15:58 +00004051void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4052 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4053 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4054 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4055 }
4056}
4057
Douglas Gregor404cdde2012-01-27 01:47:08 +00004058void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004059 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00004060 RecordData Categories;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004061
Douglas Gregor404cdde2012-01-27 01:47:08 +00004062 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4063 unsigned Size = 0;
4064 unsigned StartIndex = Categories.size();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004065
Douglas Gregor404cdde2012-01-27 01:47:08 +00004066 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004067
Douglas Gregor404cdde2012-01-27 01:47:08 +00004068 // Allocate space for the size.
4069 Categories.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004070
Douglas Gregor404cdde2012-01-27 01:47:08 +00004071 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004072 for (ObjCInterfaceDecl::known_categories_iterator
4073 Cat = Class->known_categories_begin(),
4074 CatEnd = Class->known_categories_end();
4075 Cat != CatEnd; ++Cat, ++Size) {
4076 assert(getDeclID(*Cat) != 0 && "Bogus category");
4077 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004078 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004079
Douglas Gregor404cdde2012-01-27 01:47:08 +00004080 // Update the size.
4081 Categories[StartIndex] = Size;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004082
Douglas Gregor404cdde2012-01-27 01:47:08 +00004083 // Record this interface -> category map.
4084 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4085 CategoriesMap.push_back(CatInfo);
4086 }
4087
4088 // Sort the categories map by the definition ID, since the reader will be
4089 // performing binary searches on this information.
4090 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4091
4092 // Emit the categories map.
4093 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004094
David Blaikieb44f0bf2017-01-04 22:36:43 +00004095 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004096 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4097 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4098 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004099 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004100
4101 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4102 Stream.EmitRecordWithBlob(AbbrevID, Record,
4103 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004104 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004105
Douglas Gregor404cdde2012-01-27 01:47:08 +00004106 // Emit the category lists.
4107 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4108}
4109
Richard Smithe40f2ba2013-08-07 21:41:30 +00004110void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4111 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4112
4113 if (LPTMap.empty())
4114 return;
4115
4116 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004117 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004118 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004119 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004120 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004121 AddDeclRef(LPT.D, Record);
4122 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004123
Justin Lebar28f09c52016-10-10 16:26:08 +00004124 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004125 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004126 }
4127 }
4128 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4129}
4130
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004131/// Write the state of 'pragma clang optimize' at the end of the module.
Dario Domizioli13a0a382014-05-23 12:13:25 +00004132void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4133 RecordData Record;
4134 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4135 AddSourceLocation(PragmaLoc, Record);
4136 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4137}
4138
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004139/// Write the state of 'pragma ms_struct' at the end of the module.
Nico Weber779355f2016-03-02 23:22:00 +00004140void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4141 RecordData Record;
4142 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4143 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4144}
4145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004146/// Write the state of 'pragma pointers_to_members' at the end of the
Nico Weber42932312016-03-03 00:17:35 +00004147//module.
4148void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4149 RecordData Record;
4150 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4151 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4152 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4153}
4154
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004155/// Write the state of 'pragma pack' at the end of the module.
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004156void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004157 // Don't serialize pragma pack state for modules, since it should only take
4158 // effect on a per-submodule basis.
4159 if (WritingModule)
4160 return;
4161
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004162 RecordData Record;
4163 Record.push_back(SemaRef.PackStack.CurrentValue);
4164 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4165 Record.push_back(SemaRef.PackStack.Stack.size());
4166 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4167 Record.push_back(StackEntry.Value);
4168 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004169 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004170 AddString(StackEntry.StackSlotLabel, Record);
4171 }
4172 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4173}
4174
Melanie Blowerf5360d42020-05-01 10:32:06 -07004175/// Write the state of 'pragma float_control' at the end of the module.
4176void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4177 // Don't serialize pragma float_control state for modules,
4178 // since it should only take effect on a per-submodule basis.
4179 if (WritingModule)
4180 return;
4181
4182 RecordData Record;
4183 Record.push_back(SemaRef.FpPragmaStack.CurrentValue);
4184 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4185 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4186 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4187 Record.push_back(StackEntry.Value);
4188 AddSourceLocation(StackEntry.PragmaLocation, Record);
4189 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4190 AddString(StackEntry.StackSlotLabel, Record);
4191 }
4192 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4193}
4194
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004195void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4196 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004197 // Enter the extension block.
4198 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4199
4200 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004201 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004202 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4203 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4204 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4205 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4206 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4207 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004208 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004209
4210 // Emit the metadata record.
4211 RecordData Record;
4212 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4213 Record.push_back(EXTENSION_METADATA);
4214 Record.push_back(Metadata.MajorVersion);
4215 Record.push_back(Metadata.MinorVersion);
4216 Record.push_back(Metadata.BlockName.size());
4217 Record.push_back(Metadata.UserInfo.size());
4218 SmallString<64> Buffer;
4219 Buffer += Metadata.BlockName;
4220 Buffer += Metadata.UserInfo;
4221 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4222
4223 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004224 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004225
4226 // Exit the extension block.
4227 Stream.ExitBlock();
4228}
4229
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004230//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004231// General Serialization Routines
4232//===----------------------------------------------------------------------===//
4233
Richard Smithe43e2b32018-08-20 21:47:29 +00004234void ASTRecordWriter::AddAttr(const Attr *A) {
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004235 auto &Record = *this;
Richard Smithe43e2b32018-08-20 21:47:29 +00004236 if (!A)
4237 return Record.push_back(0);
4238 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
Erich Keane6a24e802019-09-13 17:39:31 +00004239
4240 Record.AddIdentifierRef(A->getAttrName());
4241 Record.AddIdentifierRef(A->getScopeName());
Richard Smithe43e2b32018-08-20 21:47:29 +00004242 Record.AddSourceRange(A->getRange());
Erich Keane6a24e802019-09-13 17:39:31 +00004243 Record.AddSourceLocation(A->getScopeLoc());
4244 Record.push_back(A->getParsedKind());
4245 Record.push_back(A->getSyntax());
4246 Record.push_back(A->getAttributeSpellingListIndexRaw());
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004247
4248#include "clang/Serialization/AttrPCHWrite.inc"
Richard Smithe43e2b32018-08-20 21:47:29 +00004249}
4250
4251/// Emit the list of attributes to the specified record.
4252void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4253 push_back(Attrs.size());
4254 for (const auto *A : Attrs)
4255 AddAttr(A);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004256}
4257
John McCallf413f5e2013-05-03 00:10:13 +00004258void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4259 AddSourceLocation(Tok.getLocation(), Record);
4260 Record.push_back(Tok.getLength());
4261
4262 // FIXME: When reading literal tokens, reconstruct the literal pointer
4263 // if it is needed.
4264 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4265 // FIXME: Should translate token kind to a stable encoding.
4266 Record.push_back(Tok.getKind());
4267 // FIXME: Should translate token flags to a stable encoding.
4268 Record.push_back(Tok.getFlags());
4269}
4270
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004271void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004272 Record.push_back(Str.size());
4273 Record.insert(Record.end(), Str.begin(), Str.end());
4274}
4275
Richard Smith7ed1bc92014-12-05 22:42:13 +00004276bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004277 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004278
Richard Smith54cc3c22014-12-11 20:50:24 +00004279 bool Changed =
4280 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004281
4282 // Remove a prefix to make the path relative, if relevant.
4283 const char *PathBegin = Path.data();
4284 const char *PathPtr =
4285 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4286 if (PathPtr != PathBegin) {
4287 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4288 Changed = true;
4289 }
4290
4291 return Changed;
4292}
4293
4294void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4295 SmallString<128> FilePath(Path);
4296 PreparePathForOutput(FilePath);
4297 AddString(FilePath, Record);
4298}
4299
Mehdi Amini57a41912015-09-10 01:46:39 +00004300void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004301 StringRef Path) {
4302 SmallString<128> FilePath(Path);
4303 PreparePathForOutput(FilePath);
4304 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4305}
4306
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004307void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4308 RecordDataImpl &Record) {
4309 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004310 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004311 Record.push_back(*Minor + 1);
4312 else
4313 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004314 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004315 Record.push_back(*Subminor + 1);
4316 else
4317 Record.push_back(0);
4318}
4319
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004320/// Note that the identifier II occurs at the given offset
Douglas Gregore84a9da2009-04-20 20:36:09 +00004321/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004322void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004323 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004324 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004325 // up earlier in the chain and thus don't need an offset.
4326 if (ID >= FirstIdentID)
4327 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004328}
4329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004330/// Note that the selector Sel occurs at the given offset
Douglas Gregor95c13f52009-04-25 17:48:32 +00004331/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004332void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004333 unsigned ID = SelectorIDs[Sel];
4334 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004335 // Don't record offsets for selectors that are also available in a different
4336 // file.
4337 if (ID < FirstSelectorID)
4338 return;
4339 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004340}
4341
David Blaikie61137e12017-01-05 18:23:18 +00004342ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004343 SmallVectorImpl<char> &Buffer,
4344 InMemoryModuleCache &ModuleCache,
David Blaikie61137e12017-01-05 18:23:18 +00004345 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4346 bool IncludeTimestamps)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004347 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004348 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004349 for (const auto &Ext : Extensions) {
4350 if (auto Writer = Ext->createExtensionWriter(*this))
4351 ModuleFileExtensionWriters.push_back(std::move(Writer));
4352 }
4353}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004354
David Blaikie409df392020-04-28 18:05:28 -07004355ASTWriter::~ASTWriter() = default;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004356
Richard Smithb3761912015-02-05 23:08:52 +00004357const LangOptions &ASTWriter::getLangOpts() const {
4358 assert(WritingAST && "can't determine lang opts when not writing AST");
4359 return Context->getLangOpts();
4360}
4361
Richard Smithe75ee0f2015-08-17 07:13:32 +00004362time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4363 return IncludeTimestamps ? E->getModificationTime() : 0;
4364}
4365
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004366ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4367 const std::string &OutputFile,
4368 Module *WritingModule, StringRef isysroot,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004369 bool hasErrors,
4370 bool ShouldCacheASTInMemory) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004371 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004372
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004373 ASTHasCompilerErrors = hasErrors;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004374
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004375 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004376 Stream.Emit((unsigned)'C', 8);
4377 Stream.Emit((unsigned)'P', 8);
4378 Stream.Emit((unsigned)'C', 8);
4379 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004380
Chris Lattner28fa4e62009-04-26 22:26:21 +00004381 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004382
Douglas Gregoreda8e122011-08-09 15:13:55 +00004383 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004384 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004385 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004386 ASTFileSignature Signature =
4387 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004388 Context = nullptr;
4389 PP = nullptr;
4390 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004391 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004392
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004393 WritingAST = false;
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004394 if (ShouldCacheASTInMemory) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004395 // Construct MemoryBuffer and update buffer manager.
Rumeet Dhindsa57a2eaf2020-03-10 10:59:26 -07004396 ModuleCache.addBuiltPCM(OutputFile,
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004397 llvm::MemoryBuffer::getMemBufferCopy(
4398 StringRef(Buffer.begin(), Buffer.size())));
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004399 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004400 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004401}
4402
Douglas Gregora94a1542011-07-27 21:45:57 +00004403template<typename Vector>
4404static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4405 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004406 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4407 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004408 Writer.AddDeclRef(*I, Record);
4409 }
4410}
4411
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004412ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4413 const std::string &OutputFile,
4414 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004415 using namespace llvm;
4416
Craig Toppera13603a2014-05-22 05:54:18 +00004417 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004418
Douglas Gregorcf68c582011-12-01 22:20:10 +00004419 // Make sure that the AST reader knows to finalize itself.
4420 if (Chain)
4421 Chain->finalizeForWriting();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004422
Sebastian Redl143413f2010-07-12 22:02:52 +00004423 ASTContext &Context = SemaRef.Context;
4424 Preprocessor &PP = SemaRef.PP;
4425
Douglas Gregordab42432011-08-12 00:15:20 +00004426 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004427 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4428 if (D) {
4429 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4430 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004431 }
4432 };
4433 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4434 PREDEF_DECL_TRANSLATION_UNIT_ID);
4435 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4436 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4437 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4438 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4439 PREDEF_DECL_OBJC_PROTOCOL_ID);
4440 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4441 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4442 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4443 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4444 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004445 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004446 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4447 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smithbab6df82020-04-11 22:15:29 -07004448 RegisterPredefDecl(Context.MSGuidTagDecl,
4449 PREDEF_DECL_BUILTIN_MS_GUID_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004450 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004451 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4452 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004453 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4454 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004455 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4456 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004457 RegisterPredefDecl(Context.TypePackElementDecl,
4458 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004459
Chris Lattner0c797362009-09-08 18:19:27 +00004460 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004461 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004462 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004463 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004464 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004465
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004466 // Build a record containing all of the file scoped decls in this file.
4467 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004468 if (!isModule)
4469 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4470 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004471
Douglas Gregor851443c2011-08-12 01:39:19 +00004472 // Build a record containing all of the delegating constructors we still need
4473 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004474 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004475 if (!isModule)
4476 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004477
Douglas Gregor851443c2011-08-12 01:39:19 +00004478 // Write the set of weak, undeclared identifiers. We always write the
4479 // entire table, since later PCH files in a PCH chain are only interested in
4480 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004481 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004482 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4483 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4484 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4485 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4486 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4487 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4488 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004489 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004490
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004491 // Build a record containing all of the ext_vector declarations.
4492 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004493 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004494
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004495 // Build a record containing all of the VTable uses information.
4496 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004497 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004498 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4499 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4500 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4501 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4502 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004503 }
4504
Nico Weber72889432014-09-06 01:25:55 +00004505 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4506 RecordData UnusedLocalTypedefNameCandidates;
4507 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4508 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4509
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004510 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004511 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004512 for (const auto &I : SemaRef.PendingInstantiations) {
4513 AddDeclRef(I.first, PendingInstantiations);
4514 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004515 }
4516 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4517 "There are local ones at end of translation unit!");
4518
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004519 // Build a record containing some declaration references.
4520 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004521 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004522 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4523 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004524 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004525 }
4526
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004527 RecordData CUDASpecialDeclRefs;
4528 if (Context.getcudaConfigureCallDecl()) {
4529 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4530 }
4531
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004532 // Build a record containing all of the known namespaces.
4533 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004534 for (const auto &I : SemaRef.KnownNamespaces) {
4535 if (!I.second)
4536 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004537 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004538
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004539 // Build a record of all used, undefined objects that require definitions.
4540 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004541
4542 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004543 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004544 for (const auto &I : Undefined) {
4545 AddDeclRef(I.first, UndefinedButUsed);
4546 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004547 }
4548
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004549 // Build a record containing all delete-expressions that we would like to
4550 // analyze later in AST.
4551 RecordData DeleteExprsToAnalyze;
4552
Richard Smithf5262c62018-06-28 01:57:04 +00004553 if (!isModule) {
4554 for (const auto &DeleteExprsInfo :
4555 SemaRef.getMismatchingDeleteExpressions()) {
4556 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4557 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4558 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4559 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4560 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4561 }
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004562 }
4563 }
4564
Douglas Gregor112b9072012-10-18 05:31:06 +00004565 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004566 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004567
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004568 // Write the remaining AST contents.
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004569 Stream.FlushToWord();
4570 ASTBlockRange.first = Stream.GetCurrentBitNo();
Sebastian Redl539c5062010-08-18 23:57:32 +00004571 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004572 ASTBlockStartOffset = Stream.GetCurrentBitNo();
Douglas Gregor851443c2011-08-12 01:39:19 +00004573
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004574 // This is so that older clang versions, before the introduction
4575 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004576 {
4577 RecordData Record = {VERSION_MAJOR};
4578 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4579 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004580
Douglas Gregor851443c2011-08-12 01:39:19 +00004581 // Create a lexical update block containing all of the declarations in the
4582 // translation unit that do not come from other AST files.
4583 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004584 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4585 for (const auto *D : TU->noload_decls()) {
4586 if (!D->isFromASTFile()) {
4587 NewGlobalKindDeclPairs.push_back(D->getKind());
4588 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4589 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004590 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004591
David Blaikieb44f0bf2017-01-04 22:36:43 +00004592 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004593 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4594 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004595 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004596 {
4597 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4598 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4599 bytes(NewGlobalKindDeclPairs));
4600 }
4601
Douglas Gregor851443c2011-08-12 01:39:19 +00004602 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004603 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004604 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4605 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004606 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004607 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004608 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004609
4610 // If we have any extern "C" names, write out a visible update for them.
4611 if (Context.ExternCContext)
4612 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004613
Douglas Gregor851443c2011-08-12 01:39:19 +00004614 // If the translation unit has an anonymous namespace, and we don't already
4615 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004616 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004617 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4618 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004619 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004620 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004621 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004622
Richard Smith5652c0f2014-03-21 01:48:23 +00004623 // Add update records for all mangling numbers and static local numbers.
4624 // These aren't really update records, but this is a convenient way of
4625 // tagging this rare extra data onto the declarations.
4626 for (const auto &Number : Context.MangleNumbers)
4627 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004628 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4629 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004630 for (const auto &Number : Context.StaticLocalNumbers)
4631 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004632 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4633 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004634
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004635 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004636 // an AST file, are registered for serialization. Likewise for template
4637 // specializations added to imported templates.
4638 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004639 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004640 }
4641
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004642 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004643 // serialization, if we're storing decls with identifiers.
4644 if (!WritingModule || !getLangOpts().CPlusPlus) {
4645 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004646 for (const auto &ID : PP.getIdentifierTable()) {
4647 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004648 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4649 IIs.push_back(II);
4650 }
4651 // Sort the identifiers to visit based on their name.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00004652 llvm::sort(IIs, llvm::deref<std::less<>>());
Richard Smith79bf9202015-08-24 03:33:22 +00004653 for (const IdentifierInfo *II : IIs) {
4654 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4655 DEnd = SemaRef.IdResolver.end();
4656 D != DEnd; ++D) {
4657 GetDeclRef(*D);
4658 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004659 }
4660 }
4661
Manman Rena0f31a02016-04-29 19:04:05 +00004662 // For method pool in the module, if it contains an entry for a selector,
4663 // the entry should be complete, containing everything introduced by that
4664 // module and all modules it imports. It's possible that the entry is out of
4665 // date, so we need to pull in the new content here.
4666
4667 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4668 // safe, we copy all selectors out.
4669 llvm::SmallVector<Selector, 256> AllSelectors;
4670 for (auto &SelectorAndID : SelectorIDs)
4671 AllSelectors.push_back(SelectorAndID.first);
4672 for (auto &Selector : AllSelectors)
4673 SemaRef.updateOutOfDateSelector(Selector);
4674
Douglas Gregor5204bde2011-08-02 16:26:37 +00004675 // Form the record of special types.
4676 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004677 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004678 AddTypeRef(Context.getFILEType(), SpecialTypes);
4679 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4680 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4681 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4682 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004683 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004684 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004685
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004686 if (Chain) {
4687 // Write the mapping information describing our module dependencies and how
4688 // each of those modules were mapped into our own offset/ID space, so that
4689 // the reader can build the appropriate mapping to its own offset/ID space.
4690 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004691 // *(module-kind:i8
4692 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004693 // source-location-offset:i32
4694 // identifier-id:i32
4695 // preprocessed-entity-id:i32
4696 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004697 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004698 // selector-id:i32
4699 // declaration-id:i32
4700 // c++-base-specifiers-id:i32
4701 // type-id:i32)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004702 //
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004703 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4704 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4705 // module name. Otherwise, it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004706 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004707 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004709 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004710 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004711 {
4712 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004713 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004714 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004715
Peter Collingbournee3f65292018-05-18 19:46:24 +00004716 endian::Writer LE(Out, little);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004717 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004718 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004719 LE.write<uint16_t>(Name.size());
4720 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004721
Ben Langmuir785180e2014-10-20 16:27:30 +00004722 // Note: if a base ID was uint max, it would not be possible to load
4723 // another module after it or have more than one entity inside it.
4724 uint32_t None = std::numeric_limits<uint32_t>::max();
4725
4726 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4727 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4728 if (ShouldWrite)
4729 LE.write<uint32_t>(BaseID);
4730 else
4731 LE.write<uint32_t>(None);
4732 };
4733
Ben Langmuirfe971d92014-08-16 04:54:18 +00004734 // These values should be unique within a chain, since they will be read
4735 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004736 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4737 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4738 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4739 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4740 M.NumPreprocessedEntities);
4741 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4742 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4743 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4744 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004745 }
4746 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004747 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004748 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4749 Buffer.data(), Buffer.size());
4750 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004751
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05004752 // Build a record containing all of the DeclsToCheckForDeferredDiags.
4753 RecordData DeclsToCheckForDeferredDiags;
4754 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4755 AddDeclRef(D, DeclsToCheckForDeferredDiags);
4756
Richard Smithb9eab6d2014-03-20 19:44:17 +00004757 RecordData DeclUpdatesOffsetsRecord;
4758
Richard Smith59442b42014-03-20 20:07:19 +00004759 // Keep writing types, declarations, and declaration update records
4760 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004761 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004762 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
Richard Smith01b2cb42014-07-26 06:37:51 +00004763 WriteTypeAbbrevs();
4764 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004765 do {
4766 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4767 while (!DeclTypesToEmit.empty()) {
4768 DeclOrType DOT = DeclTypesToEmit.front();
4769 DeclTypesToEmit.pop();
4770 if (DOT.isType())
4771 WriteType(DOT.getType());
4772 else
4773 WriteDecl(Context, DOT.getDecl());
4774 }
4775 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004776 Stream.ExitBlock();
4777
Richard Smithb9eab6d2014-03-20 19:44:17 +00004778 DoneWritingDeclsAndTypes = true;
4779
4780 // These things can only be done once we've written out decls and types.
4781 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004782 if (!DeclUpdatesOffsetsRecord.empty())
4783 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004784 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004785 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004786 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004787 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004788 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004789 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004790 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004791 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004792 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Melanie Blower95187632020-06-26 07:54:01 -07004793 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004794 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004795 WriteOpenCLExtensionTypes(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004796 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004797
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004798 // If we're emitting a module, write out the submodule information.
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004799 if (WritingModule)
4800 WriteSubmodules(WritingModule);
4801
Andrew Savonichev52d674d2018-10-29 11:14:01 +00004802 // We need to have information about submodules to correctly deserialize
4803 // decls from OpenCLExtensionDecls block
4804 WriteOpenCLExtensionDecls(SemaRef);
4805
Douglas Gregor5204bde2011-08-02 16:26:37 +00004806 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4807
Douglas Gregord4df8652009-04-22 22:02:47 +00004808 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004809 if (!EagerlyDeserializedDecls.empty())
4810 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004811
David Blaikief63556d2017-04-12 20:58:33 +00004812 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004813 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4814
Douglas Gregord4df8652009-04-22 22:02:47 +00004815 // Write the record containing tentative definitions.
4816 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004817 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004818
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004819 // Write the record containing unused file scoped decls.
4820 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004821 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004822
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004823 // Write the record containing weak undeclared identifiers.
4824 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004825 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004826 WeakUndeclaredIdentifiers);
4827
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004828 // Write the record containing ext_vector type names.
4829 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004830 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004831
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004832 // Write the record containing VTable uses information.
4833 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004834 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004835
Nico Weber72889432014-09-06 01:25:55 +00004836 // Write the record containing potentially unused local typedefs.
4837 if (!UnusedLocalTypedefNameCandidates.empty())
4838 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4839 UnusedLocalTypedefNameCandidates);
4840
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004841 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004842 if (!PendingInstantiations.empty())
4843 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004844
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004845 // Write the record containing declaration references of Sema.
4846 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004847 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004848
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05004849 // Write the record containing decls to be checked for deferred diags.
4850 if (!DeclsToCheckForDeferredDiags.empty())
4851 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4852 DeclsToCheckForDeferredDiags);
4853
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004854 // Write the record containing CUDA-specific declaration references.
4855 if (!CUDASpecialDeclRefs.empty())
4856 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004857
Alexis Hunt27a761d2011-05-04 23:29:54 +00004858 // Write the delegating constructors.
4859 if (!DelegatingCtorDecls.empty())
4860 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004861
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004862 // Write the known namespaces.
4863 if (!KnownNamespaces.empty())
4864 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004865
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004866 // Write the undefined internal functions and variables, and inline functions.
4867 if (!UndefinedButUsed.empty())
4868 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004869
4870 if (!DeleteExprsToAnalyze.empty())
4871 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4872
Douglas Gregor851443c2011-08-12 01:39:19 +00004873 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004874 for (auto *DC : UpdatedDeclContexts)
4875 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004876
Douglas Gregor959bb062011-12-03 01:15:29 +00004877 if (!WritingModule) {
4878 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004879 struct ModuleInfo {
4880 uint64_t ID;
4881 Module *M;
4882 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4883 };
Richard Smith56be7542014-03-21 00:33:59 +00004884 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004885 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004886 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004887 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4888 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004889 }
Richard Smith56be7542014-03-21 00:33:59 +00004890
4891 if (!Imports.empty()) {
4892 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4893 return A.ID < B.ID;
4894 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004895 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4896 return A.ID == B.ID;
4897 };
Richard Smith56be7542014-03-21 00:33:59 +00004898
4899 // Sort and deduplicate module IDs.
Fangrui Song55fab262018-09-26 22:16:28 +00004900 llvm::sort(Imports, Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004901 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004902 Imports.end());
4903
4904 RecordData ImportedModules;
4905 for (const auto &Import : Imports) {
4906 ImportedModules.push_back(Import.ID);
4907 // FIXME: If the module has macros imported then later has declarations
4908 // imported, this location won't be the right one as a location for the
4909 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004910 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004911 }
4912
Douglas Gregor959bb062011-12-03 01:15:29 +00004913 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4914 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004915 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004916
Douglas Gregor404cdde2012-01-27 01:47:08 +00004917 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004918 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004919 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004920 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004921 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004922 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004923 WritePackPragmaOptions(SemaRef);
Melanie Blowerf5360d42020-05-01 10:32:06 -07004924 WriteFloatControlPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004925
Douglas Gregor08f01292009-04-17 22:13:46 +00004926 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004927 RecordData::value_type Record[] = {
4928 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004929 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004930 Stream.ExitBlock();
Daniel Grumbergbb8c7e72020-05-13 17:07:47 +01004931 Stream.FlushToWord();
4932 ASTBlockRange.second = Stream.GetCurrentBitNo();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004933
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004934 // Write the module file extension blocks.
4935 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004936 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004937
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004938 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004939}
4940
Richard Smithb9eab6d2014-03-20 19:44:17 +00004941void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004942 if (DeclUpdates.empty())
4943 return;
4944
Richard Smith59442b42014-03-20 20:07:19 +00004945 DeclUpdateMap LocalUpdates;
4946 LocalUpdates.swap(DeclUpdates);
4947
Richard Smith6ef42932014-03-20 21:02:00 +00004948 for (auto &DeclUpdate : LocalUpdates) {
4949 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004950
Richard Smithd28ac5b2014-03-22 23:33:22 +00004951 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004952 RecordData RecordData;
4953 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004954 for (auto &Update : DeclUpdate.second) {
4955 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4956
Richard Smith69c82bf2016-04-01 22:52:03 +00004957 // An updated body is emitted last, so that the reader doesn't need
4958 // to skip over the lazy body to reach statements for other records.
4959 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4960 HasUpdatedBody = true;
4961 else
4962 Record.push_back(Kind);
4963
Richard Smith6ef42932014-03-20 21:02:00 +00004964 switch (Kind) {
4965 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4966 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4967 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004968 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004969 Record.push_back(GetDeclRef(Update.getDecl()));
4970 break;
4971
Richard Smith4d235792014-08-07 18:53:08 +00004972 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004973 break;
4974
Richard Smith891fc7f2017-12-05 01:31:47 +00004975 case UPD_CXX_POINT_OF_INSTANTIATION:
4976 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00004977 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00004978 break;
4979
4980 case UPD_CXX_ADDED_VAR_DEFINITION: {
4981 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00004982 Record.push_back(VD->isInline());
4983 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00004984 if (VD->getInit()) {
4985 Record.push_back(!VD->isInitKnownICE() ? 1
4986 : (VD->isInitICE() ? 3 : 2));
4987 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4988 } else {
4989 Record.push_back(0);
4990 }
Richard Smith4d235792014-08-07 18:53:08 +00004991 break;
Richard Smith05a21352017-06-22 22:18:46 +00004992 }
Richard Smith4d235792014-08-07 18:53:08 +00004993
John McCall32791cc2016-01-06 22:34:54 +00004994 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004995 Record.AddStmt(const_cast<Expr *>(
4996 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004997 break;
4998
Richard Smith4b054b22016-08-24 21:25:37 +00004999 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5000 Record.AddStmt(
5001 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5002 break;
5003
Richard Smithcd45dbc2014-04-19 03:48:30 +00005004 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5005 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00005006 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00005007 Record.push_back(RD->isParamDestroyedInCallee());
Akira Hatanakae6313ac2018-04-09 22:48:22 +00005008 Record.push_back(RD->getArgPassingRestrictions());
Richard Smith69c82bf2016-04-01 22:52:03 +00005009 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00005010 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00005011 *Context, const_cast<CXXRecordDecl *>(RD)));
5012
5013 // This state is sometimes updated by template instantiation, when we
5014 // switch from the specialization referring to the template declaration
5015 // to it referring to the template definition.
5016 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5017 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005018 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005019 } else {
5020 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5021 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005022 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00005023
5024 // The instantiation might have been resolved to a partial
5025 // specialization. If so, record which one.
5026 auto From = Spec->getInstantiatedFrom();
5027 if (auto PartialSpec =
5028 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5029 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00005030 Record.AddDeclRef(PartialSpec);
5031 Record.AddTemplateArgumentList(
5032 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00005033 } else {
5034 Record.push_back(false);
5035 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005036 }
5037 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005038 Record.AddSourceLocation(RD->getLocation());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005039 Record.AddSourceLocation(RD->getBeginLoc());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00005040 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005041
5042 // Instantiation may change attributes; write them all out afresh.
5043 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00005044 if (D->hasAttrs())
5045 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005046
5047 // FIXME: Ensure we don't get here for explicit instantiations.
5048 break;
5049 }
5050
Richard Smithf8134002015-03-10 01:41:22 +00005051 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005052 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00005053 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00005054 break;
5055
John McCalld505e572019-12-13 21:54:44 -05005056 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5057 auto prototype =
5058 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5059 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
Richard Smith564417a2014-03-20 21:47:22 +00005060 break;
John McCalld505e572019-12-13 21:54:44 -05005061 }
Richard Smith564417a2014-03-20 21:47:22 +00005062
Richard Smith6ef42932014-03-20 21:02:00 +00005063 case UPD_CXX_DEDUCED_RETURN_TYPE:
5064 Record.push_back(GetOrCreateTypeID(Update.getType()));
5065 break;
5066
5067 case UPD_DECL_MARKED_USED:
5068 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00005069
5070 case UPD_MANGLING_NUMBER:
5071 case UPD_STATIC_LOCAL_NUMBER:
5072 Record.push_back(Update.getNumber());
5073 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005074
Alexey Bataev97720002014-11-11 04:05:39 +00005075 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005076 Record.AddSourceRange(
5077 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00005078 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005079
Alexey Bataev27ef9512019-03-20 20:14:22 +00005080 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5081 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5082 Record.push_back(A->getAllocatorType());
5083 Record.AddStmt(A->getAllocator());
5084 Record.AddSourceRange(A->getRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005085 break;
Alexey Bataev27ef9512019-03-20 20:14:22 +00005086 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005087
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005088 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
Alexey Bataevd01b7492018-08-15 19:45:12 +00005089 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005090 Record.AddSourceRange(
5091 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5092 break;
5093
Richard Smith65ebb4a2015-03-26 04:09:53 +00005094 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00005095 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005096 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005097
5098 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00005099 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00005100 break;
Richard Smith6ef42932014-03-20 21:02:00 +00005101 }
5102 }
5103
Richard Smithd28ac5b2014-03-22 23:33:22 +00005104 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005105 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005106 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005107 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005108 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005109 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005110 }
5111
Richard Smithcd45dbc2014-04-19 03:48:30 +00005112 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005113 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005114 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005115}
5116
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005117void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005118 uint32_t Raw = Loc.getRawEncoding();
5119 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005120}
5121
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005122void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005123 AddSourceLocation(Range.getBegin(), Record);
5124 AddSourceLocation(Range.getEnd(), Record);
5125}
5126
Richard Smithf144b542016-04-08 21:54:32 +00005127void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5128 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005129}
5130
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00005131static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5132 FixedPointSemantics FPSema) {
5133 Record.push_back(FPSema.getWidth());
5134 Record.push_back(FPSema.getScale());
5135 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5136 FPSema.hasUnsignedPadding() << 2);
5137}
5138
5139void ASTRecordWriter::AddAPValue(const APValue &Value) {
5140 APValue::ValueKind Kind = Value.getKind();
5141 push_back(static_cast<uint64_t>(Kind));
5142 switch (Kind) {
5143 case APValue::None:
5144 case APValue::Indeterminate:
5145 return;
5146 case APValue::Int:
5147 AddAPSInt(Value.getInt());
5148 return;
5149 case APValue::Float:
5150 push_back(static_cast<uint64_t>(
5151 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5152 AddAPFloat(Value.getFloat());
5153 return;
5154 case APValue::FixedPoint: {
5155 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5156 AddAPSInt(Value.getFixedPoint().getValue());
5157 return;
5158 }
5159 case APValue::ComplexInt: {
5160 AddAPSInt(Value.getComplexIntReal());
5161 AddAPSInt(Value.getComplexIntImag());
5162 return;
5163 }
5164 case APValue::ComplexFloat: {
5165 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5166 Value.getComplexFloatReal().getSemantics())));
5167 AddAPFloat(Value.getComplexFloatReal());
5168 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5169 Value.getComplexFloatImag().getSemantics())));
5170 AddAPFloat(Value.getComplexFloatImag());
5171 return;
5172 }
5173 case APValue::LValue:
5174 case APValue::Vector:
5175 case APValue::Array:
5176 case APValue::Struct:
5177 case APValue::Union:
5178 case APValue::MemberPointer:
5179 case APValue::AddrLabelDiff:
5180 // TODO : Handle all these APValue::ValueKind.
5181 return;
5182 }
5183 llvm_unreachable("Invalid APValue::ValueKind");
5184}
5185
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005186void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005187 Record.push_back(getIdentifierRef(II));
5188}
5189
Sebastian Redl539c5062010-08-18 23:57:32 +00005190IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005191 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005192 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005193
Sebastian Redl539c5062010-08-18 23:57:32 +00005194 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005195 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005196 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005197 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005198}
5199
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005200MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005201 // Don't emit builtin macros like __LINE__ to the AST file unless they
5202 // have been redefined by the header (in which case they are not
5203 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005204 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005205 return 0;
5206
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005207 MacroID &ID = MacroIDs[MI];
5208 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005209 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005210 MacroInfoToEmitData Info = { Name, MI, ID };
5211 MacroInfosToEmit.push_back(Info);
5212 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005213 return ID;
5214}
5215
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005216MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005217 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005218 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005219
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005220 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5221 return MacroIDs[MI];
5222}
5223
Dmitry Polukhina7afb212020-04-16 09:24:46 -07005224uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005225 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005226}
5227
Richard Smithe64e7452016-04-18 21:54:58 +00005228void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5229 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005230}
5231
Sebastian Redl539c5062010-08-18 23:57:32 +00005232SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005233 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005234 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005235 }
5236
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005237 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005238 if (SID == 0 && Chain) {
5239 // This might trigger a ReadSelector callback, which will set the ID for
5240 // this selector.
5241 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005242 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005243 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005244 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005245 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005246 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005247 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005248 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005249}
5250
Richard Smithe64e7452016-04-18 21:54:58 +00005251void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5252 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005253}
5254
Richard Smith290d8012016-04-06 17:06:00 +00005255void ASTRecordWriter::AddTemplateArgumentLocInfo(
5256 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005257 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005258 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005259 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005260 break;
5261 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005262 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005263 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005264 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005265 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5266 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005267 break;
5268 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005269 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5270 AddSourceLocation(Arg.getTemplateNameLoc());
5271 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005272 break;
John McCall0ad16662009-10-29 08:12:44 +00005273 case TemplateArgument::Null:
5274 case TemplateArgument::Integral:
5275 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005276 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005277 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005278 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005279 break;
5280 }
5281}
5282
Richard Smith290d8012016-04-06 17:06:00 +00005283void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5284 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005285
5286 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5287 bool InfoHasSameExpr
5288 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005289 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005290 if (InfoHasSameExpr)
5291 return; // Avoid storing the same expr twice.
5292 }
Richard Smith290d8012016-04-06 17:06:00 +00005293 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005294}
5295
Richard Smith290d8012016-04-06 17:06:00 +00005296void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005297 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005298 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005299 return;
5300 }
5301
Richard Smithc23d7342018-06-29 20:46:25 +00005302 AddTypeRef(TInfo->getType());
Richard Smith290d8012016-04-06 17:06:00 +00005303 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005304}
5305
Richard Smith290d8012016-04-06 17:06:00 +00005306void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
Richard Smith290d8012016-04-06 17:06:00 +00005307 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005308 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005309 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005310}
5311
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005312void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005313 Record.push_back(GetOrCreateTypeID(T));
5314}
5315
Richard Smith2095ffe2015-03-16 20:11:03 +00005316TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005317 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005318 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5319 if (T.isNull())
5320 return TypeIdx();
5321 assert(!T.getLocalFastQualifiers());
5322
5323 TypeIdx &Idx = TypeIdxs[T];
5324 if (Idx.getIndex() == 0) {
5325 if (DoneWritingDeclsAndTypes) {
5326 assert(0 && "New type seen after serializing all the types to emit!");
5327 return TypeIdx();
5328 }
5329
5330 // We haven't seen this type before. Assign it a new ID and put it
5331 // into the queue of types to emit.
5332 Idx = TypeIdx(NextTypeID++);
5333 DeclTypesToEmit.push(T);
5334 }
5335 return Idx;
5336 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005337}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005338
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005339TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005340 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005341 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5342 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005343 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005344 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005345
Richard Smith2095ffe2015-03-16 20:11:03 +00005346 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5347 assert(I != TypeIdxs.end() && "Type not emitted!");
5348 return I->second;
5349 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005350}
5351
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005352void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005353 Record.push_back(GetDeclRef(D));
5354}
5355
Sebastian Redl539c5062010-08-18 23:57:32 +00005356DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005357 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005358
5359 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005360 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005361 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005362
Douglas Gregorb3163e52012-01-05 22:33:30 +00005363 // If D comes from an AST file, its declaration ID is already known and
5364 // fixed.
5365 if (D->isFromASTFile())
5366 return D->getGlobalID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005367
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005368 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005369 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005370 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005371 if (DoneWritingDeclsAndTypes) {
5372 assert(0 && "New decl seen after serializing all the decls to emit!");
5373 return 0;
5374 }
5375
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005376 // We haven't seen this declaration before. Give it a new ID and
5377 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005378 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005379 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005380 }
5381
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005382 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005383}
5384
Sebastian Redl539c5062010-08-18 23:57:32 +00005385DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005386 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005387 return 0;
5388
Douglas Gregorb3163e52012-01-05 22:33:30 +00005389 // If D comes from an AST file, its declaration ID is already known and
5390 // fixed.
5391 if (D->isFromASTFile())
5392 return D->getGlobalID();
5393
Douglas Gregore84a9da2009-04-20 20:36:09 +00005394 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5395 return DeclIDs[D];
5396}
5397
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005398void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005399 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005400 assert(D);
5401
5402 SourceLocation Loc = D->getLocation();
5403 if (Loc.isInvalid())
5404 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005405
5406 // We only keep track of the file-level declarations of each file.
5407 if (!D->getLexicalDeclContext()->isFileContext())
5408 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005409 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5410 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005411 // TemplateTemplateParmDecls that are part of an alias template, should not
5412 // have TU as lexical context.
5413 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005414 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005415
5416 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005417 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005418 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005419 FileID FID;
5420 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005421 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005422 if (FID.isInvalid())
5423 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005424 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005425
David Blaikie409df392020-04-28 18:05:28 -07005426 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005427 if (!Info)
David Blaikie409df392020-04-28 18:05:28 -07005428 Info = std::make_unique<DeclIDInFileInfo>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005429
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005430 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005431 LocDeclIDsTy &Decls = Info->DeclIDs;
5432
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005433 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005434 Decls.push_back(LocDecl);
5435 return;
5436 }
5437
Benjamin Kramer45025c02013-08-24 13:22:59 +00005438 LocDeclIDsTy::iterator I =
Fangrui Song7264a472019-07-03 08:13:17 +00005439 llvm::upper_bound(Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005440
5441 Decls.insert(I, LocDecl);
5442}
5443
Richard Smithd08aeb62014-08-28 01:33:39 +00005444unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5445 assert(needsAnonymousDeclarationNumber(D) &&
5446 "expected an anonymous declaration");
5447
5448 // Number the anonymous declarations within this context, if we've not
5449 // already done so.
5450 auto It = AnonymousDeclarationNumbers.find(D);
5451 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005452 auto *DC = D->getLexicalDeclContext();
5453 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5454 AnonymousDeclarationNumbers[ND] = Number;
5455 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005456
5457 It = AnonymousDeclarationNumbers.find(D);
5458 assert(It != AnonymousDeclarationNumbers.end() &&
5459 "declaration not found within its lexical context");
5460 }
5461
5462 return It->second;
5463}
5464
Richard Smith290d8012016-04-06 17:06:00 +00005465void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5466 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005467 switch (Name.getNameKind()) {
5468 case DeclarationName::CXXConstructorName:
5469 case DeclarationName::CXXDestructorName:
5470 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005471 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005472 break;
5473
5474 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005475 AddSourceLocation(SourceLocation::getFromRawEncoding(
5476 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005477 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005478 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005479 break;
5480
5481 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005482 AddSourceLocation(SourceLocation::getFromRawEncoding(
5483 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005484 break;
5485
5486 case DeclarationName::Identifier:
5487 case DeclarationName::ObjCZeroArgSelector:
5488 case DeclarationName::ObjCOneArgSelector:
5489 case DeclarationName::ObjCMultiArgSelector:
5490 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005491 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005492 break;
5493 }
5494}
5495
Richard Smith290d8012016-04-06 17:06:00 +00005496void ASTRecordWriter::AddDeclarationNameInfo(
5497 const DeclarationNameInfo &NameInfo) {
5498 AddDeclarationName(NameInfo.getName());
5499 AddSourceLocation(NameInfo.getLoc());
5500 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005501}
5502
Richard Smith290d8012016-04-06 17:06:00 +00005503void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5504 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5505 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005506 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005507 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005508}
5509
Richard Smith290d8012016-04-06 17:06:00 +00005510void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005511 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005512 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005513 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005514
5515 // Push each of the nested-name-specifiers's onto a stack for
5516 // serialization in reverse order.
5517 while (NNS) {
5518 NestedNames.push_back(NNS);
5519 NNS = NNS.getPrefix();
5520 }
5521
Richard Smith290d8012016-04-06 17:06:00 +00005522 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005523 while(!NestedNames.empty()) {
5524 NNS = NestedNames.pop_back_val();
5525 NestedNameSpecifier::SpecifierKind Kind
5526 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005527 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005528 switch (Kind) {
5529 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005530 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5531 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005532 break;
5533
5534 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005535 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5536 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005537 break;
5538
5539 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005540 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5541 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005542 break;
5543
5544 case NestedNameSpecifier::TypeSpec:
5545 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005546 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Richard Smithc23d7342018-06-29 20:46:25 +00005547 AddTypeRef(NNS.getTypeLoc().getType());
Richard Smith290d8012016-04-06 17:06:00 +00005548 AddTypeLoc(NNS.getTypeLoc());
5549 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005550 break;
5551
5552 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005553 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005554 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005555
5556 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005557 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5558 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005559 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005560 }
5561 }
5562}
5563
Richard Smithe64e7452016-04-18 21:54:58 +00005564void ASTRecordWriter::AddTemplateParameterList(
5565 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005566 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005567 AddSourceLocation(TemplateParams->getTemplateLoc());
5568 AddSourceLocation(TemplateParams->getLAngleLoc());
5569 AddSourceLocation(TemplateParams->getRAngleLoc());
Saar Raz0330fba2019-10-15 18:44:06 +00005570
Richard Smithe64e7452016-04-18 21:54:58 +00005571 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005572 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005573 AddDeclRef(P);
Saar Raz0330fba2019-10-15 18:44:06 +00005574 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5575 Record->push_back(true);
5576 AddStmt(const_cast<Expr*>(RequiresClause));
5577 } else {
5578 Record->push_back(false);
5579 }
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005580}
5581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005582/// Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005583void ASTRecordWriter::AddTemplateArgumentList(
5584 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005585 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005586 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005587 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005588 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005589}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005590
Richard Smith290d8012016-04-06 17:06:00 +00005591void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5592 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005593 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005594 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5595 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5596 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005597 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005598 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005599 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005600}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005601
Richard Smithe64e7452016-04-18 21:54:58 +00005602void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5603 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005604 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005605 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005606 AddDeclRef(I.getDecl());
5607 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005608 }
5609}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005610
Richard Smith290d8012016-04-06 17:06:00 +00005611// FIXME: Move this out of the main ASTRecordWriter interface.
5612void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5613 Record->push_back(Base.isVirtual());
5614 Record->push_back(Base.isBaseOfClass());
5615 Record->push_back(Base.getAccessSpecifierAsWritten());
5616 Record->push_back(Base.getInheritConstructors());
5617 AddTypeSourceInfo(Base.getTypeSourceInfo());
5618 AddSourceRange(Base.getSourceRange());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005619 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005620 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005621}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005622
Richard Smith645d2cf2016-04-14 00:29:55 +00005623static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5624 ArrayRef<CXXBaseSpecifier> Bases) {
5625 ASTWriter::RecordData Record;
5626 ASTRecordWriter Writer(W, Record);
5627 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005628
Richard Smith645d2cf2016-04-14 00:29:55 +00005629 for (auto &Base : Bases)
5630 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005631
Richard Smith645d2cf2016-04-14 00:29:55 +00005632 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005633}
5634
Richard Smith290d8012016-04-06 17:06:00 +00005635// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005636void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5637 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5638}
5639
Richard Smithaa165cf2016-04-13 21:57:08 +00005640static uint64_t
5641EmitCXXCtorInitializers(ASTWriter &W,
5642 ArrayRef<CXXCtorInitializer *> CtorInits) {
5643 ASTWriter::RecordData Record;
5644 ASTRecordWriter Writer(W, Record);
5645 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005646
Richard Smithaa165cf2016-04-13 21:57:08 +00005647 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005648 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005649 Writer.push_back(CTOR_INITIALIZER_BASE);
5650 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5651 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005652 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005653 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5654 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005655 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005656 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5657 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005658 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005659 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5660 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005661 }
Francois Pichetd583da02010-12-04 09:14:42 +00005662
Richard Smithaa165cf2016-04-13 21:57:08 +00005663 Writer.AddSourceLocation(Init->getMemberLocation());
5664 Writer.AddStmt(Init->getInit());
5665 Writer.AddSourceLocation(Init->getLParenLoc());
5666 Writer.AddSourceLocation(Init->getRParenLoc());
5667 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005668 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005669 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005670 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005671
5672 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005673}
5674
Richard Smithaa165cf2016-04-13 21:57:08 +00005675// FIXME: Move this out of the main ASTRecordWriter interface.
5676void ASTRecordWriter::AddCXXCtorInitializers(
5677 ArrayRef<CXXCtorInitializer *> CtorInits) {
5678 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005679}
5680
Richard Smith290d8012016-04-06 17:06:00 +00005681void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005682 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005683 Record->push_back(Data.IsLambda);
Richard Smith91aeacc2019-10-11 00:29:04 +00005684
5685 #define FIELD(Name, Width, Merge) \
5686 Record->push_back(Data.Name);
5687 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
Richard Trieufd1acbb2017-04-11 21:31:00 +00005688
5689 // getODRHash will compute the ODRHash if it has not been previously computed.
5690 Record->push_back(D->getODRHash());
Hans Wennborg7ea9a6e2020-02-27 14:33:43 +01005691 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
5692 Writer->WritingModule && !D->isDependentType();
David Blaikief63556d2017-04-12 20:58:33 +00005693 Record->push_back(ModulesDebugInfo);
5694 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00005695 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5696
Richard Smith561fb152012-02-25 07:33:38 +00005697 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005698
Richard Smith290d8012016-04-06 17:06:00 +00005699 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005700 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005701 AddCXXBaseSpecifiers(Data.bases());
5702
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005703 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005704 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005705 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005706 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005707
Richard Smith290d8012016-04-06 17:06:00 +00005708 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
Richard Smith91aeacc2019-10-11 00:29:04 +00005709 Record->push_back(Data.ComputedVisibleConversions);
5710 if (Data.ComputedVisibleConversions)
5711 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005712 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005713 AddDeclRef(D->getFirstFriend());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005714
Douglas Gregor99ae8062012-02-14 17:54:36 +00005715 // Add lambda-specific data.
5716 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005717 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005718 Record->push_back(Lambda.Dependent);
5719 Record->push_back(Lambda.IsGenericLambda);
5720 Record->push_back(Lambda.CaptureDefault);
5721 Record->push_back(Lambda.NumCaptures);
5722 Record->push_back(Lambda.NumExplicitCaptures);
Michael Liao243ebfb2019-10-19 00:15:19 +00005723 Record->push_back(Lambda.HasKnownInternalLinkage);
Richard Smith290d8012016-04-06 17:06:00 +00005724 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00005725 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00005726 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005727 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005728 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005729 AddSourceLocation(Capture.getLocation());
5730 Record->push_back(Capture.isImplicit());
5731 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005732 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005733 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005734 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005735 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005736 break;
5737 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005738 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005739 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005740 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005741 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005742 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005743 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005744 break;
5745 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005746 }
5747 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005748}
5749
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005750void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005751 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005752 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005753 assert(FirstDeclID == NextDeclID &&
5754 FirstTypeID == NextTypeID &&
5755 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005756 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005757 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005758 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005759 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005760
Sebastian Redl07a89a82010-07-30 00:29:29 +00005761 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005762
Richard Smith7f330cd2015-03-18 01:42:29 +00005763 // Note, this will get called multiple times, once one the reader starts up
5764 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005765 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5766 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5767 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005768 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005769 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005770 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005771 NextDeclID = FirstDeclID;
5772 NextTypeID = FirstTypeID;
5773 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005774 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005775 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005776 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005777}
5778
Sebastian Redl539c5062010-08-18 23:57:32 +00005779void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005780 // Always keep the highest ID. See \p TypeRead() for more information.
5781 IdentID &StoredID = IdentifierIDs[II];
5782 if (ID > StoredID)
5783 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005784}
5785
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005786void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005787 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005788 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005789 if (ID > StoredID)
5790 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005791}
5792
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005793void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005794 // Always take the highest-numbered type index. This copes with an interesting
5795 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005796 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005797 // keep the higher-numbered entry so that we can properly write it out to
5798 // the AST file.
5799 TypeIdx &StoredIdx = TypeIdxs[T];
5800 if (Idx.getIndex() >= StoredIdx.getIndex())
5801 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005802}
5803
Sebastian Redl539c5062010-08-18 23:57:32 +00005804void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005805 // Always keep the highest ID. See \p TypeRead() for more information.
5806 SelectorID &StoredID = SelectorIDs[S];
5807 if (ID > StoredID)
5808 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005809}
Douglas Gregor91096292010-10-02 19:29:26 +00005810
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005811void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005812 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005813 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005814 MacroDefinitions[MD] = ID;
5815}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005816
Douglas Gregore37a85a2011-12-02 17:30:13 +00005817void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5818 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5819 SubmoduleIDs[Mod] = ID;
5820}
5821
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005822void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005823 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005824 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005825 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005826 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005827 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005828 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005829 // A forward reference was mutated into a definition. Rewrite it.
5830 // FIXME: This happens during template instantiation, should we
5831 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005832 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5833 "completed a tag from another module but not by instantiation?");
5834 DeclUpdates[RD].push_back(
5835 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005836 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005837 }
5838}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005839
Richard Smithf983f7f2015-10-13 00:23:25 +00005840static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5841 if (D->isFromASTFile())
5842 return true;
5843
Richard Smithf983f7f2015-10-13 00:23:25 +00005844 // The predefined __va_list_tag struct is imported if we imported any decls.
5845 // FIXME: This is a gross hack.
5846 return D == D->getASTContext().getVaListTagDecl();
5847}
5848
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005849void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005850 if (Chain && Chain->isProcessingUpdateRecords()) return;
5851 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005852 "Should not add lookup results to non-lookup contexts!");
5853
Vassil Vassilev632eac32016-03-16 11:17:04 +00005854 // TU is handled elsewhere.
5855 if (isa<TranslationUnitDecl>(DC))
5856 return;
5857
5858 // Namespaces are handled elsewhere, except for template instantiations of
5859 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5860 // local instantiations are added to an imported context. Only happens when
5861 // adding ADL lookup candidates, for example templated friends.
5862 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5863 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005864 return;
5865
Richard Smithf983f7f2015-10-13 00:23:25 +00005866 // We're only interested in cases where a local declaration is added to an
5867 // imported context.
5868 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5869 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005870
Richard Smith0f4e2c42015-08-06 04:23:48 +00005871 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005872 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005873 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005874 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5875 // We're adding a visible declaration to a predefined decl context. Ensure
5876 // that we write out all of its lookup results so we don't get a nasty
5877 // surprise when we try to emit its lookup table.
5878 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00005879 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00005880 }
Richard Smithc26d9742016-10-06 20:30:51 +00005881 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005882}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005883
5884void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005885 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005886 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005887
5888 // We're only interested in cases where a local declaration is added to an
5889 // imported context.
5890 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5891 return;
5892
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005893 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005894 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005895
5896 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005897 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005898 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005899 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005900}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005901
Richard Smith564417a2014-03-20 21:47:22 +00005902void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005903 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005904 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5905 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005906 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005907 // If we don't already know the exception specification for this redecl
5908 // chain, add an update record for it.
5909 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5910 ->getType()
5911 ->castAs<FunctionProtoType>()
5912 ->getExceptionSpecType()))
5913 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5914 });
Richard Smith564417a2014-03-20 21:47:22 +00005915}
5916
Richard Smith1fa5d642013-05-11 05:45:24 +00005917void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005918 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005919 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005920 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005921 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005922 DeclUpdates[D].push_back(
5923 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5924 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005925}
5926
Richard Smithf8134002015-03-10 01:41:22 +00005927void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00005928 const FunctionDecl *Delete,
5929 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005930 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005931 assert(!WritingAST && "Already writing the AST!");
5932 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005933 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005934 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005935 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5936 });
Richard Smithf8134002015-03-10 01:41:22 +00005937}
5938
Sebastian Redlab238a72011-04-24 16:28:06 +00005939void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005940 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005941 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005942 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005943 return; // Declaration not imported from PCH.
5944
Richard Smith4d235792014-08-07 18:53:08 +00005945 // Implicit function decl from a PCH was defined.
5946 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005947}
5948
Richard Smith891fc7f2017-12-05 01:31:47 +00005949void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5950 if (Chain && Chain->isProcessingUpdateRecords()) return;
5951 assert(!WritingAST && "Already writing the AST!");
5952 if (!D->isFromASTFile())
5953 return;
5954
5955 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5956}
5957
Richard Smithd28ac5b2014-03-22 23:33:22 +00005958void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005959 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005960 assert(!WritingAST && "Already writing the AST!");
5961 if (!D->isFromASTFile())
5962 return;
5963
Richard Smith9e2341d2015-03-23 03:25:59 +00005964 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005965}
5966
Richard Smith891fc7f2017-12-05 01:31:47 +00005967void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005968 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005969 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005970 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005971 return;
5972
5973 // Since the actual instantiation is delayed, this really means that we need
5974 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00005975 SourceLocation POI;
5976 if (auto *VD = dyn_cast<VarDecl>(D))
5977 POI = VD->getPointOfInstantiation();
5978 else
5979 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5980 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005981}
5982
John McCall32791cc2016-01-06 22:34:54 +00005983void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005984 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005985 assert(!WritingAST && "Already writing the AST!");
5986 if (!D->isFromASTFile())
5987 return;
5988
5989 DeclUpdates[D].push_back(
5990 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5991}
5992
Richard Smith4b054b22016-08-24 21:25:37 +00005993void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5994 assert(!WritingAST && "Already writing the AST!");
5995 if (!D->isFromASTFile())
5996 return;
5997
5998 DeclUpdates[D].push_back(
5999 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6000}
6001
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006002void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6003 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006004 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006005 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006006 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006007 return; // Declaration not imported from PCH.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00006008
Douglas Gregor404cdde2012-01-27 01:47:08 +00006009 assert(IFD->getDefinition() && "Category on a class without a definition?");
6010 ObjCClassesWithCategories.insert(
6011 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006012}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00006013
Eli Friedman276dd182013-09-05 00:02:25 +00006014void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006015 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00006016 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00006017
6018 // If there is *any* declaration of the entity that's not from an AST file,
6019 // we can skip writing the update record. We make sure that isUsed() triggers
6020 // completion of the redeclaration chain of the entity.
6021 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6022 if (IsLocalDecl(Prev))
6023 return;
Eli Friedman276dd182013-09-05 00:02:25 +00006024
Aaron Ballman4f45b712014-03-21 15:22:56 +00006025 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00006026}
Alexey Bataev97720002014-11-11 04:05:39 +00006027
6028void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006029 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00006030 assert(!WritingAST && "Already writing the AST!");
6031 if (!D->isFromASTFile())
6032 return;
6033
6034 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6035}
Richard Smith65ebb4a2015-03-26 04:09:53 +00006036
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006037void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6038 if (Chain && Chain->isProcessingUpdateRecords()) return;
6039 assert(!WritingAST && "Already writing the AST!");
6040 if (!D->isFromASTFile())
6041 return;
6042
6043 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6044}
6045
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006046void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6047 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006048 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006049 assert(!WritingAST && "Already writing the AST!");
6050 if (!D->isFromASTFile())
6051 return;
6052
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006053 DeclUpdates[D].push_back(
6054 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006055}
6056
Richard Smith4caa4492015-05-15 02:34:32 +00006057void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006058 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00006059 assert(!WritingAST && "Already writing the AST!");
Martin Boehme2e92b392020-06-08 15:37:44 +02006060 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00006061 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00006062}
Alex Denisovfde64952015-06-26 05:28:36 +00006063
6064void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6065 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006066 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00006067 assert(!WritingAST && "Already writing the AST!");
6068 if (!Record->isFromASTFile())
6069 return;
6070 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6071}
Richard Smithc26d9742016-10-06 20:30:51 +00006072
6073void ASTWriter::AddedCXXTemplateSpecialization(
6074 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6075 assert(!WritingAST && "Already writing the AST!");
6076
6077 if (!TD->getFirstDecl()->isFromASTFile())
6078 return;
6079 if (Chain && Chain->isProcessingUpdateRecords())
6080 return;
6081
6082 DeclsToEmitEvenIfUnreferenced.push_back(D);
6083}
6084
6085void ASTWriter::AddedCXXTemplateSpecialization(
6086 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6087 assert(!WritingAST && "Already writing the AST!");
6088
6089 if (!TD->getFirstDecl()->isFromASTFile())
6090 return;
6091 if (Chain && Chain->isProcessingUpdateRecords())
6092 return;
6093
6094 DeclsToEmitEvenIfUnreferenced.push_back(D);
6095}
6096
6097void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6098 const FunctionDecl *D) {
6099 assert(!WritingAST && "Already writing the AST!");
6100
6101 if (!TD->getFirstDecl()->isFromASTFile())
6102 return;
6103 if (Chain && Chain->isProcessingUpdateRecords())
6104 return;
6105
6106 DeclsToEmitEvenIfUnreferenced.push_back(D);
6107}
Kelvin Libe286f52018-09-15 13:54:15 +00006108
6109//===----------------------------------------------------------------------===//
6110//// OMPClause Serialization
6111////===----------------------------------------------------------------------===//
6112
John McCall2ac702a2019-12-14 03:17:03 -05006113namespace {
6114
6115class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6116 ASTRecordWriter &Record;
6117
6118public:
6119 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
Johannes Doerfert419a5592020-03-30 19:58:40 -05006120#define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6121#include "llvm/Frontend/OpenMP/OMPKinds.def"
John McCall2ac702a2019-12-14 03:17:03 -05006122 void writeClause(OMPClause *C);
6123 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6124 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6125};
6126
6127}
6128
6129void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6130 OMPClauseWriter(*this).writeClause(C);
6131}
6132
Kelvin Libe286f52018-09-15 13:54:15 +00006133void OMPClauseWriter::writeClause(OMPClause *C) {
Johannes Doerfert419a5592020-03-30 19:58:40 -05006134 Record.push_back(unsigned(C->getClauseKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006135 Visit(C);
6136 Record.AddSourceLocation(C->getBeginLoc());
6137 Record.AddSourceLocation(C->getEndLoc());
6138}
6139
6140void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006141 Record.push_back(uint64_t(C->getCaptureRegion()));
Kelvin Libe286f52018-09-15 13:54:15 +00006142 Record.AddStmt(C->getPreInitStmt());
6143}
6144
6145void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6146 VisitOMPClauseWithPreInit(C);
6147 Record.AddStmt(C->getPostUpdateExpr());
6148}
6149
6150void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6151 VisitOMPClauseWithPreInit(C);
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006152 Record.push_back(uint64_t(C->getNameModifier()));
Kelvin Libe286f52018-09-15 13:54:15 +00006153 Record.AddSourceLocation(C->getNameModifierLoc());
6154 Record.AddSourceLocation(C->getColonLoc());
6155 Record.AddStmt(C->getCondition());
6156 Record.AddSourceLocation(C->getLParenLoc());
6157}
6158
6159void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +00006160 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006161 Record.AddStmt(C->getCondition());
6162 Record.AddSourceLocation(C->getLParenLoc());
6163}
6164
6165void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6166 VisitOMPClauseWithPreInit(C);
6167 Record.AddStmt(C->getNumThreads());
6168 Record.AddSourceLocation(C->getLParenLoc());
6169}
6170
6171void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6172 Record.AddStmt(C->getSafelen());
6173 Record.AddSourceLocation(C->getLParenLoc());
6174}
6175
6176void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6177 Record.AddStmt(C->getSimdlen());
6178 Record.AddSourceLocation(C->getLParenLoc());
6179}
6180
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00006181void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6182 Record.AddStmt(C->getAllocator());
6183 Record.AddSourceLocation(C->getLParenLoc());
6184}
6185
Kelvin Libe286f52018-09-15 13:54:15 +00006186void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6187 Record.AddStmt(C->getNumForLoops());
6188 Record.AddSourceLocation(C->getLParenLoc());
6189}
6190
Alexey Bataev0f0564b2020-03-17 09:17:42 -04006191void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6192 Record.AddStmt(C->getEventHandler());
6193 Record.AddSourceLocation(C->getLParenLoc());
6194}
6195
Kelvin Libe286f52018-09-15 13:54:15 +00006196void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
Atmn Patel577c9b02020-02-14 21:45:49 -06006197 Record.push_back(unsigned(C->getDefaultKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006198 Record.AddSourceLocation(C->getLParenLoc());
6199 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6200}
6201
6202void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -06006203 Record.push_back(unsigned(C->getProcBindKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006204 Record.AddSourceLocation(C->getLParenLoc());
6205 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6206}
6207
6208void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6209 VisitOMPClauseWithPreInit(C);
6210 Record.push_back(C->getScheduleKind());
6211 Record.push_back(C->getFirstScheduleModifier());
6212 Record.push_back(C->getSecondScheduleModifier());
6213 Record.AddStmt(C->getChunkSize());
6214 Record.AddSourceLocation(C->getLParenLoc());
6215 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6216 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6217 Record.AddSourceLocation(C->getScheduleKindLoc());
6218 Record.AddSourceLocation(C->getCommaLoc());
6219}
6220
6221void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6222 Record.push_back(C->getLoopNumIterations().size());
6223 Record.AddStmt(C->getNumForLoops());
6224 for (Expr *NumIter : C->getLoopNumIterations())
6225 Record.AddStmt(NumIter);
6226 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
Mike Rice0ed46662018-09-20 17:19:41 +00006227 Record.AddStmt(C->getLoopCounter(I));
Kelvin Libe286f52018-09-15 13:54:15 +00006228 Record.AddSourceLocation(C->getLParenLoc());
6229}
6230
6231void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6232
6233void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6234
6235void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6236
6237void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6238
6239void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6240
Alexey Bataev82f7c202020-03-03 13:22:35 -05006241void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6242 Record.push_back(C->isExtended() ? 1 : 0);
6243 if (C->isExtended()) {
6244 Record.AddSourceLocation(C->getLParenLoc());
6245 Record.AddSourceLocation(C->getArgumentLoc());
6246 Record.writeEnum(C->getDependencyKind());
6247 }
6248}
Kelvin Libe286f52018-09-15 13:54:15 +00006249
6250void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6251
6252void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6253
Alexey Bataevea9166b2020-02-06 16:30:23 -05006254void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6255
Alexey Bataev04a830f2020-02-10 14:30:39 -05006256void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6257
Alexey Bataev95598342020-02-10 15:49:05 -05006258void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6259
Alexey Bataev9a8defc2020-02-11 11:10:43 -05006260void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6261
Kelvin Libe286f52018-09-15 13:54:15 +00006262void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6263
6264void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6265
6266void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6267
Alexey Bataev375437a2020-03-02 14:21:20 -05006268void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *) {}
6269
Kelvin Libe286f52018-09-15 13:54:15 +00006270void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6271 Record.push_back(C->varlist_size());
6272 Record.AddSourceLocation(C->getLParenLoc());
6273 for (auto *VE : C->varlists()) {
6274 Record.AddStmt(VE);
6275 }
6276 for (auto *VE : C->private_copies()) {
6277 Record.AddStmt(VE);
6278 }
6279}
6280
6281void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6282 Record.push_back(C->varlist_size());
6283 VisitOMPClauseWithPreInit(C);
6284 Record.AddSourceLocation(C->getLParenLoc());
6285 for (auto *VE : C->varlists()) {
6286 Record.AddStmt(VE);
6287 }
6288 for (auto *VE : C->private_copies()) {
6289 Record.AddStmt(VE);
6290 }
6291 for (auto *VE : C->inits()) {
6292 Record.AddStmt(VE);
6293 }
6294}
6295
6296void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6297 Record.push_back(C->varlist_size());
6298 VisitOMPClauseWithPostUpdate(C);
6299 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev93dc40d2019-12-20 11:04:57 -05006300 Record.writeEnum(C->getKind());
6301 Record.AddSourceLocation(C->getKindLoc());
6302 Record.AddSourceLocation(C->getColonLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006303 for (auto *VE : C->varlists())
6304 Record.AddStmt(VE);
6305 for (auto *E : C->private_copies())
6306 Record.AddStmt(E);
6307 for (auto *E : C->source_exprs())
6308 Record.AddStmt(E);
6309 for (auto *E : C->destination_exprs())
6310 Record.AddStmt(E);
6311 for (auto *E : C->assignment_ops())
6312 Record.AddStmt(E);
6313}
6314
6315void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6316 Record.push_back(C->varlist_size());
6317 Record.AddSourceLocation(C->getLParenLoc());
6318 for (auto *VE : C->varlists())
6319 Record.AddStmt(VE);
6320}
6321
6322void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6323 Record.push_back(C->varlist_size());
Alexey Bataevbd1c03d2020-05-04 16:19:31 -04006324 Record.writeEnum(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006325 VisitOMPClauseWithPostUpdate(C);
6326 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev1236eb62020-03-23 17:30:38 -04006327 Record.AddSourceLocation(C->getModifierLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006328 Record.AddSourceLocation(C->getColonLoc());
6329 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6330 Record.AddDeclarationNameInfo(C->getNameInfo());
6331 for (auto *VE : C->varlists())
6332 Record.AddStmt(VE);
6333 for (auto *VE : C->privates())
6334 Record.AddStmt(VE);
6335 for (auto *E : C->lhs_exprs())
6336 Record.AddStmt(E);
6337 for (auto *E : C->rhs_exprs())
6338 Record.AddStmt(E);
6339 for (auto *E : C->reduction_ops())
6340 Record.AddStmt(E);
Alexey Bataevbd1c03d2020-05-04 16:19:31 -04006341 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
6342 for (auto *E : C->copy_ops())
6343 Record.AddStmt(E);
6344 for (auto *E : C->copy_array_temps())
6345 Record.AddStmt(E);
6346 for (auto *E : C->copy_array_elems())
6347 Record.AddStmt(E);
6348 }
Kelvin Libe286f52018-09-15 13:54:15 +00006349}
6350
6351void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6352 Record.push_back(C->varlist_size());
6353 VisitOMPClauseWithPostUpdate(C);
6354 Record.AddSourceLocation(C->getLParenLoc());
6355 Record.AddSourceLocation(C->getColonLoc());
6356 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6357 Record.AddDeclarationNameInfo(C->getNameInfo());
6358 for (auto *VE : C->varlists())
6359 Record.AddStmt(VE);
6360 for (auto *VE : C->privates())
6361 Record.AddStmt(VE);
6362 for (auto *E : C->lhs_exprs())
6363 Record.AddStmt(E);
6364 for (auto *E : C->rhs_exprs())
6365 Record.AddStmt(E);
6366 for (auto *E : C->reduction_ops())
6367 Record.AddStmt(E);
6368}
6369
6370void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6371 Record.push_back(C->varlist_size());
6372 VisitOMPClauseWithPostUpdate(C);
6373 Record.AddSourceLocation(C->getLParenLoc());
6374 Record.AddSourceLocation(C->getColonLoc());
6375 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6376 Record.AddDeclarationNameInfo(C->getNameInfo());
6377 for (auto *VE : C->varlists())
6378 Record.AddStmt(VE);
6379 for (auto *VE : C->privates())
6380 Record.AddStmt(VE);
6381 for (auto *E : C->lhs_exprs())
6382 Record.AddStmt(E);
6383 for (auto *E : C->rhs_exprs())
6384 Record.AddStmt(E);
6385 for (auto *E : C->reduction_ops())
6386 Record.AddStmt(E);
6387 for (auto *E : C->taskgroup_descriptors())
6388 Record.AddStmt(E);
6389}
6390
6391void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6392 Record.push_back(C->varlist_size());
6393 VisitOMPClauseWithPostUpdate(C);
6394 Record.AddSourceLocation(C->getLParenLoc());
6395 Record.AddSourceLocation(C->getColonLoc());
6396 Record.push_back(C->getModifier());
6397 Record.AddSourceLocation(C->getModifierLoc());
6398 for (auto *VE : C->varlists()) {
6399 Record.AddStmt(VE);
6400 }
6401 for (auto *VE : C->privates()) {
6402 Record.AddStmt(VE);
6403 }
6404 for (auto *VE : C->inits()) {
6405 Record.AddStmt(VE);
6406 }
6407 for (auto *VE : C->updates()) {
6408 Record.AddStmt(VE);
6409 }
6410 for (auto *VE : C->finals()) {
6411 Record.AddStmt(VE);
6412 }
6413 Record.AddStmt(C->getStep());
6414 Record.AddStmt(C->getCalcStep());
Alexey Bataev195ae902019-08-08 13:42:45 +00006415 for (auto *VE : C->used_expressions())
6416 Record.AddStmt(VE);
Kelvin Libe286f52018-09-15 13:54:15 +00006417}
6418
6419void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6420 Record.push_back(C->varlist_size());
6421 Record.AddSourceLocation(C->getLParenLoc());
6422 Record.AddSourceLocation(C->getColonLoc());
6423 for (auto *VE : C->varlists())
6424 Record.AddStmt(VE);
6425 Record.AddStmt(C->getAlignment());
6426}
6427
6428void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6429 Record.push_back(C->varlist_size());
6430 Record.AddSourceLocation(C->getLParenLoc());
6431 for (auto *VE : C->varlists())
6432 Record.AddStmt(VE);
6433 for (auto *E : C->source_exprs())
6434 Record.AddStmt(E);
6435 for (auto *E : C->destination_exprs())
6436 Record.AddStmt(E);
6437 for (auto *E : C->assignment_ops())
6438 Record.AddStmt(E);
6439}
6440
6441void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6442 Record.push_back(C->varlist_size());
6443 Record.AddSourceLocation(C->getLParenLoc());
6444 for (auto *VE : C->varlists())
6445 Record.AddStmt(VE);
6446 for (auto *E : C->source_exprs())
6447 Record.AddStmt(E);
6448 for (auto *E : C->destination_exprs())
6449 Record.AddStmt(E);
6450 for (auto *E : C->assignment_ops())
6451 Record.AddStmt(E);
6452}
6453
6454void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6455 Record.push_back(C->varlist_size());
6456 Record.AddSourceLocation(C->getLParenLoc());
6457 for (auto *VE : C->varlists())
6458 Record.AddStmt(VE);
6459}
6460
Alexey Bataevc112e942020-02-28 09:52:15 -05006461void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6462 Record.AddStmt(C->getDepobj());
6463 Record.AddSourceLocation(C->getLParenLoc());
6464}
6465
Kelvin Libe286f52018-09-15 13:54:15 +00006466void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6467 Record.push_back(C->varlist_size());
6468 Record.push_back(C->getNumLoops());
6469 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev13a15042020-04-01 15:06:38 -04006470 Record.AddStmt(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006471 Record.push_back(C->getDependencyKind());
6472 Record.AddSourceLocation(C->getDependencyLoc());
6473 Record.AddSourceLocation(C->getColonLoc());
6474 for (auto *VE : C->varlists())
6475 Record.AddStmt(VE);
6476 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6477 Record.AddStmt(C->getLoopData(I));
6478}
6479
6480void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6481 VisitOMPClauseWithPreInit(C);
Alexey Bataev2f8894a2020-03-18 15:01:15 -04006482 Record.writeEnum(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006483 Record.AddStmt(C->getDevice());
Alexey Bataev2f8894a2020-03-18 15:01:15 -04006484 Record.AddSourceLocation(C->getModifierLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006485 Record.AddSourceLocation(C->getLParenLoc());
6486}
6487
6488void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6489 Record.push_back(C->varlist_size());
6490 Record.push_back(C->getUniqueDeclarationsNum());
6491 Record.push_back(C->getTotalComponentListNum());
6492 Record.push_back(C->getTotalComponentsNum());
6493 Record.AddSourceLocation(C->getLParenLoc());
Reid Klecknerba1ffd22020-04-03 12:35:30 -07006494 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
Kelvin Lief579432018-12-18 22:18:41 +00006495 Record.push_back(C->getMapTypeModifier(I));
6496 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6497 }
Michael Kruse4304e9d2019-02-19 16:38:20 +00006498 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6499 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006500 Record.push_back(C->getMapType());
6501 Record.AddSourceLocation(C->getMapLoc());
6502 Record.AddSourceLocation(C->getColonLoc());
6503 for (auto *E : C->varlists())
6504 Record.AddStmt(E);
Michael Kruse4304e9d2019-02-19 16:38:20 +00006505 for (auto *E : C->mapperlists())
6506 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006507 for (auto *D : C->all_decls())
6508 Record.AddDeclRef(D);
6509 for (auto N : C->all_num_lists())
6510 Record.push_back(N);
6511 for (auto N : C->all_lists_sizes())
6512 Record.push_back(N);
6513 for (auto &M : C->all_components()) {
6514 Record.AddStmt(M.getAssociatedExpression());
6515 Record.AddDeclRef(M.getAssociatedDeclaration());
6516 }
6517}
6518
Alexey Bataeve04483e2019-03-27 14:14:31 +00006519void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6520 Record.push_back(C->varlist_size());
6521 Record.AddSourceLocation(C->getLParenLoc());
6522 Record.AddSourceLocation(C->getColonLoc());
6523 Record.AddStmt(C->getAllocator());
6524 for (auto *VE : C->varlists())
6525 Record.AddStmt(VE);
6526}
6527
Kelvin Libe286f52018-09-15 13:54:15 +00006528void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6529 VisitOMPClauseWithPreInit(C);
6530 Record.AddStmt(C->getNumTeams());
6531 Record.AddSourceLocation(C->getLParenLoc());
6532}
6533
6534void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6535 VisitOMPClauseWithPreInit(C);
6536 Record.AddStmt(C->getThreadLimit());
6537 Record.AddSourceLocation(C->getLParenLoc());
6538}
6539
6540void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +00006541 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006542 Record.AddStmt(C->getPriority());
6543 Record.AddSourceLocation(C->getLParenLoc());
6544}
6545
6546void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +00006547 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006548 Record.AddStmt(C->getGrainsize());
6549 Record.AddSourceLocation(C->getLParenLoc());
6550}
6551
6552void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +00006553 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006554 Record.AddStmt(C->getNumTasks());
6555 Record.AddSourceLocation(C->getLParenLoc());
6556}
6557
6558void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6559 Record.AddStmt(C->getHint());
6560 Record.AddSourceLocation(C->getLParenLoc());
6561}
6562
6563void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6564 VisitOMPClauseWithPreInit(C);
6565 Record.push_back(C->getDistScheduleKind());
6566 Record.AddStmt(C->getChunkSize());
6567 Record.AddSourceLocation(C->getLParenLoc());
6568 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6569 Record.AddSourceLocation(C->getCommaLoc());
6570}
6571
6572void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6573 Record.push_back(C->getDefaultmapKind());
6574 Record.push_back(C->getDefaultmapModifier());
6575 Record.AddSourceLocation(C->getLParenLoc());
6576 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6577 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6578}
6579
6580void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6581 Record.push_back(C->varlist_size());
6582 Record.push_back(C->getUniqueDeclarationsNum());
6583 Record.push_back(C->getTotalComponentListNum());
6584 Record.push_back(C->getTotalComponentsNum());
6585 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse01f670d2019-02-22 22:29:42 +00006586 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6587 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006588 for (auto *E : C->varlists())
6589 Record.AddStmt(E);
Michael Kruse01f670d2019-02-22 22:29:42 +00006590 for (auto *E : C->mapperlists())
6591 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006592 for (auto *D : C->all_decls())
6593 Record.AddDeclRef(D);
6594 for (auto N : C->all_num_lists())
6595 Record.push_back(N);
6596 for (auto N : C->all_lists_sizes())
6597 Record.push_back(N);
6598 for (auto &M : C->all_components()) {
6599 Record.AddStmt(M.getAssociatedExpression());
6600 Record.AddDeclRef(M.getAssociatedDeclaration());
6601 }
6602}
6603
6604void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6605 Record.push_back(C->varlist_size());
6606 Record.push_back(C->getUniqueDeclarationsNum());
6607 Record.push_back(C->getTotalComponentListNum());
6608 Record.push_back(C->getTotalComponentsNum());
6609 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse0336c752019-02-25 20:34:15 +00006610 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6611 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006612 for (auto *E : C->varlists())
6613 Record.AddStmt(E);
Michael Kruse0336c752019-02-25 20:34:15 +00006614 for (auto *E : C->mapperlists())
6615 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006616 for (auto *D : C->all_decls())
6617 Record.AddDeclRef(D);
6618 for (auto N : C->all_num_lists())
6619 Record.push_back(N);
6620 for (auto N : C->all_lists_sizes())
6621 Record.push_back(N);
6622 for (auto &M : C->all_components()) {
6623 Record.AddStmt(M.getAssociatedExpression());
6624 Record.AddDeclRef(M.getAssociatedDeclaration());
6625 }
6626}
6627
6628void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6629 Record.push_back(C->varlist_size());
6630 Record.push_back(C->getUniqueDeclarationsNum());
6631 Record.push_back(C->getTotalComponentListNum());
6632 Record.push_back(C->getTotalComponentsNum());
6633 Record.AddSourceLocation(C->getLParenLoc());
6634 for (auto *E : C->varlists())
6635 Record.AddStmt(E);
6636 for (auto *VE : C->private_copies())
6637 Record.AddStmt(VE);
6638 for (auto *VE : C->inits())
6639 Record.AddStmt(VE);
6640 for (auto *D : C->all_decls())
6641 Record.AddDeclRef(D);
6642 for (auto N : C->all_num_lists())
6643 Record.push_back(N);
6644 for (auto N : C->all_lists_sizes())
6645 Record.push_back(N);
6646 for (auto &M : C->all_components()) {
6647 Record.AddStmt(M.getAssociatedExpression());
6648 Record.AddDeclRef(M.getAssociatedDeclaration());
6649 }
6650}
6651
Alexey Bataeva888fc62020-05-21 08:30:23 -04006652void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
6653 Record.push_back(C->varlist_size());
6654 Record.push_back(C->getUniqueDeclarationsNum());
6655 Record.push_back(C->getTotalComponentListNum());
6656 Record.push_back(C->getTotalComponentsNum());
6657 Record.AddSourceLocation(C->getLParenLoc());
6658 for (auto *E : C->varlists())
6659 Record.AddStmt(E);
6660 for (auto *D : C->all_decls())
6661 Record.AddDeclRef(D);
6662 for (auto N : C->all_num_lists())
6663 Record.push_back(N);
6664 for (auto N : C->all_lists_sizes())
6665 Record.push_back(N);
6666 for (auto &M : C->all_components()) {
6667 Record.AddStmt(M.getAssociatedExpression());
6668 Record.AddDeclRef(M.getAssociatedDeclaration());
6669 }
6670}
6671
Kelvin Libe286f52018-09-15 13:54:15 +00006672void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6673 Record.push_back(C->varlist_size());
6674 Record.push_back(C->getUniqueDeclarationsNum());
6675 Record.push_back(C->getTotalComponentListNum());
6676 Record.push_back(C->getTotalComponentsNum());
6677 Record.AddSourceLocation(C->getLParenLoc());
6678 for (auto *E : C->varlists())
6679 Record.AddStmt(E);
6680 for (auto *D : C->all_decls())
6681 Record.AddDeclRef(D);
6682 for (auto N : C->all_num_lists())
6683 Record.push_back(N);
6684 for (auto N : C->all_lists_sizes())
6685 Record.push_back(N);
6686 for (auto &M : C->all_components()) {
6687 Record.AddStmt(M.getAssociatedExpression());
6688 Record.AddDeclRef(M.getAssociatedDeclaration());
6689 }
6690}
Kelvin Li1408f912018-09-26 04:28:39 +00006691
6692void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
Patrick Lyster4a370b92018-10-01 13:47:43 +00006693
6694void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6695 OMPUnifiedSharedMemoryClause *) {}
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00006696
6697void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Patrick Lyster3fe9e392018-10-11 14:41:10 +00006698
6699void
6700OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6701}
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00006702
6703void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6704 OMPAtomicDefaultMemOrderClause *C) {
6705 Record.push_back(C->getAtomicDefaultMemOrderKind());
6706 Record.AddSourceLocation(C->getLParenLoc());
6707 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6708}
Alexey Bataevb6e70842019-12-16 15:54:17 -05006709
6710void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6711 Record.push_back(C->varlist_size());
6712 Record.AddSourceLocation(C->getLParenLoc());
6713 for (auto *VE : C->varlists())
6714 Record.AddStmt(VE);
Alexey Bataev0860db92019-12-19 10:01:10 -05006715 for (auto *E : C->private_refs())
6716 Record.AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05006717}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05006718
Alexey Bataev06dea732020-03-20 09:41:22 -04006719void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
6720 Record.push_back(C->varlist_size());
6721 Record.AddSourceLocation(C->getLParenLoc());
6722 for (auto *VE : C->varlists())
6723 Record.AddStmt(VE);
6724}
6725
Alexey Bataev63828a32020-03-23 10:41:08 -04006726void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
6727 Record.push_back(C->varlist_size());
6728 Record.AddSourceLocation(C->getLParenLoc());
6729 for (auto *VE : C->varlists())
6730 Record.AddStmt(VE);
6731}
6732
Alexey Bataevcb8e6912020-01-31 16:09:26 -05006733void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
6734 Record.writeEnum(C->getKind());
6735 Record.AddSourceLocation(C->getLParenLoc());
6736 Record.AddSourceLocation(C->getKindKwLoc());
6737}
6738
Alexey Bataevb5be1c52020-04-21 13:21:00 -04006739void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
6740 Record.push_back(C->getNumberOfAllocators());
6741 Record.AddSourceLocation(C->getLParenLoc());
6742 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6743 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
6744 Record.AddStmt(Data.Allocator);
6745 Record.AddStmt(Data.AllocatorTraits);
6746 Record.AddSourceLocation(Data.LParenLoc);
6747 Record.AddSourceLocation(Data.RParenLoc);
6748 }
6749}
6750
Alexey Bataev2e499ee2020-05-18 13:37:53 -04006751void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
6752 Record.push_back(C->varlist_size());
6753 Record.AddSourceLocation(C->getLParenLoc());
6754 Record.AddStmt(C->getModifier());
6755 Record.AddSourceLocation(C->getColonLoc());
6756 for (Expr *E : C->varlists())
6757 Record.AddStmt(E);
6758}
6759
Johannes Doerfert55eca282020-03-13 23:42:05 -05006760void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
6761 writeUInt32(TI->Sets.size());
6762 for (const auto &Set : TI->Sets) {
Johannes Doerfert1228d422019-12-19 20:42:12 -06006763 writeEnum(Set.Kind);
6764 writeUInt32(Set.Selectors.size());
6765 for (const auto &Selector : Set.Selectors) {
6766 writeEnum(Selector.Kind);
6767 writeBool(Selector.ScoreOrCondition);
6768 if (Selector.ScoreOrCondition)
6769 writeExprRef(Selector.ScoreOrCondition);
6770 writeUInt32(Selector.Properties.size());
6771 for (const auto &Property : Selector.Properties)
6772 writeEnum(Property.Kind);
6773 }
6774 }
6775}