blob: c216b14661d4160e302ed19dd84e81a6f5b85539 [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
Alexey Bataevb6e70842019-12-16 15:54:17 -050013#include "clang/AST/OpenMPClause.h"
John McCall2ac702a2019-12-14 03:17:03 -050014#include "clang/Serialization/ASTRecordWriter.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000015#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000016#include "ASTReaderInternals.h"
17#include "MultiOnDiskHashTable.h"
John McCalld505e572019-12-13 21:54:44 -050018#include "clang/AST/AbstractTypeWriter.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000020#include "clang/AST/ASTUnresolvedSet.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000021#include "clang/AST/Attr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/Decl.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000023#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclCXX.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000025#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000026#include "clang/AST/DeclFriend.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000027#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000029#include "clang/AST/DeclarationName.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000030#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000031#include "clang/AST/ExprCXX.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/LambdaCapture.h"
33#include "clang/AST/NestedNameSpecifier.h"
34#include "clang/AST/RawCommentList.h"
35#include "clang/AST/TemplateName.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000037#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000038#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000039#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000040#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000042#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000043#include "clang/Basic/LLVM.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000044#include "clang/Basic/Lambda.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000045#include "clang/Basic/LangOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/Module.h"
47#include "clang/Basic/ObjCRuntime.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000048#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/SourceLocation.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000050#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000051#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000052#include "clang/Basic/Specifiers.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000053#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000054#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000055#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Lex/HeaderSearch.h"
57#include "clang/Lex/HeaderSearchOptions.h"
58#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000059#include "clang/Lex/ModuleMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Lex/PreprocessingRecord.h"
61#include "clang/Lex/Preprocessor.h"
62#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000063#include "clang/Lex/Token.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000064#include "clang/Sema/IdentifierResolver.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000066#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000067#include "clang/Sema/Weak.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000068#include "clang/Serialization/ASTReader.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000069#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080070#include "clang/Serialization/ModuleFile.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000071#include "clang/Serialization/ModuleFileExtension.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000072#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000073#include "llvm/ADT/APFloat.h"
74#include "llvm/ADT/APInt.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000075#include "llvm/ADT/APSInt.h"
76#include "llvm/ADT/ArrayRef.h"
77#include "llvm/ADT/DenseMap.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000078#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000079#include "llvm/ADT/Optional.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000080#include "llvm/ADT/PointerIntPair.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000081#include "llvm/ADT/STLExtras.h"
Ilya Biryukov45643102018-07-09 11:33:23 +000082#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000083#include "llvm/ADT/SmallSet.h"
84#include "llvm/ADT/SmallString.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000085#include "llvm/ADT/SmallVector.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000086#include "llvm/ADT/StringMap.h"
87#include "llvm/ADT/StringRef.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +000088#include "llvm/Bitstream/BitCodes.h"
89#include "llvm/Bitstream/BitstreamWriter.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000090#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +000091#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000092#include "llvm/Support/DJB.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000093#include "llvm/Support/Endian.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000094#include "llvm/Support/EndianStream.h"
George Rimarc39f5492017-01-17 15:45:31 +000095#include "llvm/Support/Error.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000096#include "llvm/Support/ErrorHandling.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000097#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000098#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000099#include "llvm/Support/Path.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000100#include "llvm/Support/SHA1.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000101#include "llvm/Support/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000103#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000104#include <cassert>
105#include <cstdint>
106#include <cstdlib>
107#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000108#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000109#include <deque>
110#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000111#include <memory>
112#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000113#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000114#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000115#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000116
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000117using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000118using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000119
Sebastian Redl3df5a082010-07-30 17:03:48 +0000120template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000121static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000122 if (v.empty()) return StringRef();
123 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000124 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000125}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000126
127template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000128static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000130 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000131}
132
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000133//===----------------------------------------------------------------------===//
134// Type serialization
135//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000136
John McCalld505e572019-12-13 21:54:44 -0500137static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
138 switch (id) {
139#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
140 case Type::CLASS_ID: return TYPE_##CODE_ID;
141#include "clang/Serialization/TypeBitCodes.def"
142 case Type::Builtin:
143 llvm_unreachable("shouldn't be serializing a builtin type this way");
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000144 }
John McCalld505e572019-12-13 21:54:44 -0500145 llvm_unreachable("bad type kind");
Xiuli Pan9c14e282016-01-09 12:53:17 +0000146}
147
John McCall8f115c62009-10-16 21:56:05 +0000148namespace {
149
John McCalld505e572019-12-13 21:54:44 -0500150class ASTTypeWriter {
151 ASTWriter &Writer;
152 ASTWriter::RecordData Record;
153 ASTRecordWriter BasicWriter;
154
155public:
156 ASTTypeWriter(ASTWriter &Writer)
157 : Writer(Writer), BasicWriter(Writer, Record) {}
158
159 uint64_t write(QualType T) {
160 if (T.hasLocalNonFastQualifiers()) {
161 Qualifiers Qs = T.getLocalQualifiers();
162 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
163 BasicWriter.writeQualifiers(Qs);
164 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
165 }
166
167 const Type *typePtr = T.getTypePtr();
168 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
169 atw.write(typePtr);
170 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
171 /*abbrev*/ 0);
172 }
173};
174
John McCall8f115c62009-10-16 21:56:05 +0000175class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000176 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000177
178public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000179 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000180
John McCall17001972009-10-18 01:05:36 +0000181#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000182#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000183 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000184#include "clang/AST/TypeLocNodes.def"
185
John McCall17001972009-10-18 01:05:36 +0000186 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
187 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000188};
189
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000190} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000191
John McCall17001972009-10-18 01:05:36 +0000192void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
193 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000194}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000195
John McCall17001972009-10-18 01:05:36 +0000196void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000197 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000198 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000199 Record.push_back(TL.getWrittenTypeSpec());
200 Record.push_back(TL.getWrittenSignSpec());
201 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000202 Record.push_back(TL.hasModeAttr());
203 }
John McCall8f115c62009-10-16 21:56:05 +0000204}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000205
John McCall17001972009-10-18 01:05:36 +0000206void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000207 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000208}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000209
John McCall17001972009-10-18 01:05:36 +0000210void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000211 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000212}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000213
Reid Kleckner8a365022013-06-24 17:51:48 +0000214void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
215 // nothing to do
216}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000217
Reid Kleckner0503a872013-12-05 01:23:43 +0000218void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
219 // nothing to do
220}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000221
John McCall17001972009-10-18 01:05:36 +0000222void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000223 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000224}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000225
John McCall17001972009-10-18 01:05:36 +0000226void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000227 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000228}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000229
John McCall17001972009-10-18 01:05:36 +0000230void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000231 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000232}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000233
John McCall17001972009-10-18 01:05:36 +0000234void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000235 Record.AddSourceLocation(TL.getStarLoc());
236 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000237}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000238
John McCall17001972009-10-18 01:05:36 +0000239void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddSourceLocation(TL.getLBracketLoc());
241 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000242 Record.push_back(TL.getSizeExpr() ? 1 : 0);
243 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000244 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000245}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000246
John McCall17001972009-10-18 01:05:36 +0000247void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
248 VisitArrayTypeLoc(TL);
249}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000250
John McCall17001972009-10-18 01:05:36 +0000251void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
252 VisitArrayTypeLoc(TL);
253}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000254
John McCall17001972009-10-18 01:05:36 +0000255void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
256 VisitArrayTypeLoc(TL);
257}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000258
John McCall17001972009-10-18 01:05:36 +0000259void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
260 DependentSizedArrayTypeLoc TL) {
261 VisitArrayTypeLoc(TL);
262}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000263
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000264void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
265 DependentAddressSpaceTypeLoc TL) {
266 Record.AddSourceLocation(TL.getAttrNameLoc());
267 SourceRange range = TL.getAttrOperandParensRange();
268 Record.AddSourceLocation(range.getBegin());
269 Record.AddSourceLocation(range.getEnd());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000270 Record.AddStmt(TL.getAttrExprOperand());
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000271}
272
John McCall17001972009-10-18 01:05:36 +0000273void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
274 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000275 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000276}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000277
John McCall17001972009-10-18 01:05:36 +0000278void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000279 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000280}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000281
Erich Keanef702b022018-07-13 19:46:04 +0000282void TypeLocWriter::VisitDependentVectorTypeLoc(
283 DependentVectorTypeLoc TL) {
284 Record.AddSourceLocation(TL.getNameLoc());
285}
286
John McCall17001972009-10-18 01:05:36 +0000287void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000288 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000289}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000290
John McCall17001972009-10-18 01:05:36 +0000291void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000292 Record.AddSourceLocation(TL.getLocalRangeBegin());
293 Record.AddSourceLocation(TL.getLParenLoc());
294 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000295 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000296 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000297 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000298 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000299}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000300
John McCall17001972009-10-18 01:05:36 +0000301void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
302 VisitFunctionTypeLoc(TL);
303}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000304
John McCall17001972009-10-18 01:05:36 +0000305void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
306 VisitFunctionTypeLoc(TL);
307}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000308
John McCallb96ec562009-12-04 22:46:56 +0000309void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000310 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000311}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000312
John McCall17001972009-10-18 01:05:36 +0000313void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000314 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000315}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000316
Manman Rene6be26c2016-09-13 17:25:08 +0000317void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
318 if (TL.getNumProtocols()) {
319 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
320 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
321 }
322 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
323 Record.AddSourceLocation(TL.getProtocolLoc(i));
324}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000325
John McCall17001972009-10-18 01:05:36 +0000326void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000327 Record.AddSourceLocation(TL.getTypeofLoc());
328 Record.AddSourceLocation(TL.getLParenLoc());
329 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000330}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000331
John McCall17001972009-10-18 01:05:36 +0000332void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddSourceLocation(TL.getTypeofLoc());
334 Record.AddSourceLocation(TL.getLParenLoc());
335 Record.AddSourceLocation(TL.getRParenLoc());
336 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000337}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000338
John McCall17001972009-10-18 01:05:36 +0000339void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000340 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000341}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000342
Alexis Hunte852b102011-05-24 22:41:36 +0000343void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000344 Record.AddSourceLocation(TL.getKWLoc());
345 Record.AddSourceLocation(TL.getLParenLoc());
346 Record.AddSourceLocation(TL.getRParenLoc());
347 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000348}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000349
Richard Smith30482bc2011-02-20 03:19:35 +0000350void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000351 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000352}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000353
Richard Smith600b5262017-01-26 20:40:47 +0000354void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
355 DeducedTemplateSpecializationTypeLoc TL) {
356 Record.AddSourceLocation(TL.getTemplateNameLoc());
357}
358
John McCall17001972009-10-18 01:05:36 +0000359void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc 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
John McCall17001972009-10-18 01:05:36 +0000363void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000364 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000365}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000366
John McCall81904512011-01-06 01:58:22 +0000367void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +0000368 Record.AddAttr(TL.getAttr());
John McCall81904512011-01-06 01:58:22 +0000369}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000370
John McCall17001972009-10-18 01:05:36 +0000371void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000372 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000373}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000374
John McCallcebee162009-10-18 09:09:24 +0000375void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
376 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000377 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000378}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000379
Douglas Gregorada4b792011-01-14 02:55:32 +0000380void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
381 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000382 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000383}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000384
John McCall17001972009-10-18 01:05:36 +0000385void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
386 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000387 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
388 Record.AddSourceLocation(TL.getTemplateNameLoc());
389 Record.AddSourceLocation(TL.getLAngleLoc());
390 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000391 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000392 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
393 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000394}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000395
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000396void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000397 Record.AddSourceLocation(TL.getLParenLoc());
398 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000399}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000400
Leonard Chanc72aaf62019-05-07 03:20:17 +0000401void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
402 Record.AddSourceLocation(TL.getExpansionLoc());
403}
404
Abramo Bagnara6150c882010-05-11 21:36:43 +0000405void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000406 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
407 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000408}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000409
John McCalle78aac42010-03-10 03:28:59 +0000410void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000411 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000412}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000413
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000414void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000415 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
416 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
417 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000418}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000419
John McCallc392f372010-06-11 00:33:02 +0000420void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
421 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000422 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
423 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
424 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
425 Record.AddSourceLocation(TL.getTemplateNameLoc());
426 Record.AddSourceLocation(TL.getLAngleLoc());
427 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000428 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000429 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
430 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000431}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000432
Douglas Gregord2fa7662010-12-20 02:24:11 +0000433void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000434 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000435}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000436
John McCall17001972009-10-18 01:05:36 +0000437void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000439}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000440
John McCall8b07ec22010-05-15 11:32:37 +0000441void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
442 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
444 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000445 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000446 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
447 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
448 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000449 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000450 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000451}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000452
John McCallfc93cf92009-10-22 22:37:11 +0000453void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000454 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000455}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000456
Eli Friedman0dfb8892011-10-06 23:00:33 +0000457void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000458 Record.AddSourceLocation(TL.getKWLoc());
459 Record.AddSourceLocation(TL.getLParenLoc());
460 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000462
Xiuli Pan9c14e282016-01-09 12:53:17 +0000463void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000464 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000465}
John McCall8f115c62009-10-16 21:56:05 +0000466
Richard Smith01b2cb42014-07-26 06:37:51 +0000467void ASTWriter::WriteTypeAbbrevs() {
468 using namespace llvm;
469
David Blaikieb44f0bf2017-01-04 22:36:43 +0000470 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000471
472 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000473 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000474 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
475 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
476 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000477 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000478
479 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000480 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000481 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
482 // FunctionType
483 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
484 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
485 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
486 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
487 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
488 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000489 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000490 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
Richard Smith01b2cb42014-07-26 06:37:51 +0000491 // FunctionProtoType
492 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
493 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
494 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
495 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
496 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
497 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
498 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
499 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000500 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000501}
502
Chris Lattner19cea4e2009-04-22 05:57:30 +0000503//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000504// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000505//===----------------------------------------------------------------------===//
506
Chris Lattner28fa4e62009-04-26 22:26:21 +0000507static void EmitBlockID(unsigned ID, const char *Name,
508 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000509 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000510 Record.clear();
511 Record.push_back(ID);
512 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
513
514 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000515 if (!Name || Name[0] == 0)
516 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000517 Record.clear();
518 while (*Name)
519 Record.push_back(*Name++);
520 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
521}
522
523static void EmitRecordID(unsigned ID, const char *Name,
524 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000525 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000526 Record.clear();
527 Record.push_back(ID);
528 while (*Name)
529 Record.push_back(*Name++);
530 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000531}
532
533static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000534 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000535#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000536 RECORD(STMT_STOP);
537 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000538 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000539 RECORD(STMT_NULL);
540 RECORD(STMT_COMPOUND);
541 RECORD(STMT_CASE);
542 RECORD(STMT_DEFAULT);
543 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000544 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000545 RECORD(STMT_IF);
546 RECORD(STMT_SWITCH);
547 RECORD(STMT_WHILE);
548 RECORD(STMT_DO);
549 RECORD(STMT_FOR);
550 RECORD(STMT_GOTO);
551 RECORD(STMT_INDIRECT_GOTO);
552 RECORD(STMT_CONTINUE);
553 RECORD(STMT_BREAK);
554 RECORD(STMT_RETURN);
555 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000556 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000557 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000558 RECORD(EXPR_PREDEFINED);
559 RECORD(EXPR_DECL_REF);
560 RECORD(EXPR_INTEGER_LITERAL);
561 RECORD(EXPR_FLOATING_LITERAL);
562 RECORD(EXPR_IMAGINARY_LITERAL);
563 RECORD(EXPR_STRING_LITERAL);
564 RECORD(EXPR_CHARACTER_LITERAL);
565 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000566 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000567 RECORD(EXPR_UNARY_OPERATOR);
568 RECORD(EXPR_SIZEOF_ALIGN_OF);
569 RECORD(EXPR_ARRAY_SUBSCRIPT);
570 RECORD(EXPR_CALL);
571 RECORD(EXPR_MEMBER);
572 RECORD(EXPR_BINARY_OPERATOR);
573 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
574 RECORD(EXPR_CONDITIONAL_OPERATOR);
575 RECORD(EXPR_IMPLICIT_CAST);
576 RECORD(EXPR_CSTYLE_CAST);
577 RECORD(EXPR_COMPOUND_LITERAL);
578 RECORD(EXPR_EXT_VECTOR_ELEMENT);
579 RECORD(EXPR_INIT_LIST);
580 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000581 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000582 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000583 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000584 RECORD(EXPR_VA_ARG);
585 RECORD(EXPR_ADDR_LABEL);
586 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000587 RECORD(EXPR_CHOOSE);
588 RECORD(EXPR_GNU_NULL);
589 RECORD(EXPR_SHUFFLE_VECTOR);
590 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000591 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000592 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000593 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000594 RECORD(EXPR_OBJC_ARRAY_LITERAL);
595 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000596 RECORD(EXPR_OBJC_ENCODE);
597 RECORD(EXPR_OBJC_SELECTOR_EXPR);
598 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
599 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
600 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
601 RECORD(EXPR_OBJC_KVC_REF_EXPR);
602 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000603 RECORD(STMT_OBJC_FOR_COLLECTION);
604 RECORD(STMT_OBJC_CATCH);
605 RECORD(STMT_OBJC_FINALLY);
606 RECORD(STMT_OBJC_AT_TRY);
607 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
608 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000609 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000610 RECORD(STMT_CXX_CATCH);
611 RECORD(STMT_CXX_TRY);
612 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000613 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000614 RECORD(EXPR_CXX_MEMBER_CALL);
Richard Smith778dc0f2019-10-19 00:04:38 +0000615 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000616 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000617 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000618 RECORD(EXPR_CXX_STATIC_CAST);
619 RECORD(EXPR_CXX_DYNAMIC_CAST);
620 RECORD(EXPR_CXX_REINTERPRET_CAST);
621 RECORD(EXPR_CXX_CONST_CAST);
622 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000623 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000624 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000625 RECORD(EXPR_CXX_BOOL_LITERAL);
626 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000627 RECORD(EXPR_CXX_TYPEID_EXPR);
628 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000629 RECORD(EXPR_CXX_THIS);
630 RECORD(EXPR_CXX_THROW);
631 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000632 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000633 RECORD(EXPR_CXX_BIND_TEMPORARY);
634 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
635 RECORD(EXPR_CXX_NEW);
636 RECORD(EXPR_CXX_DELETE);
637 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
638 RECORD(EXPR_EXPR_WITH_CLEANUPS);
639 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
640 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
641 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
642 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
643 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000644 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000645 RECORD(EXPR_CXX_NOEXCEPT);
646 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000647 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
648 RECORD(EXPR_TYPE_TRAIT);
649 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000650 RECORD(EXPR_PACK_EXPANSION);
651 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000652 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000653 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000654 RECORD(EXPR_FUNCTION_PARM_PACK);
655 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000656 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000657 RECORD(EXPR_CXX_UUIDOF_EXPR);
658 RECORD(EXPR_CXX_UUIDOF_TYPE);
659 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000660#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000661}
Mike Stump11289f42009-09-09 15:08:12 +0000662
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000663void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000664 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000665 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000666
Sebastian Redl539c5062010-08-18 23:57:32 +0000667#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
668#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000669
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000670 // Control Block.
671 BLOCK(CONTROL_BLOCK);
672 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000673 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000674 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000675 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000676 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000677 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000678 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000679 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000680 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000681
682 BLOCK(OPTIONS_BLOCK);
683 RECORD(LANGUAGE_OPTIONS);
684 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000685 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000686 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000687 RECORD(PREPROCESSOR_OPTIONS);
688
Douglas Gregor108cb222012-10-19 00:45:00 +0000689 BLOCK(INPUT_FILES_BLOCK);
690 RECORD(INPUT_FILE);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +0000691 RECORD(INPUT_FILE_HASH);
Douglas Gregor108cb222012-10-19 00:45:00 +0000692
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000693 // AST Top-Level Block.
694 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000695 RECORD(TYPE_OFFSET);
696 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000697 RECORD(IDENTIFIER_OFFSET);
698 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000699 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +0000700 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000701 RECORD(SPECIAL_TYPES);
702 RECORD(STATISTICS);
703 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000704 RECORD(SELECTOR_OFFSETS);
705 RECORD(METHOD_POOL);
706 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000707 RECORD(SOURCE_LOCATION_OFFSETS);
708 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000709 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000710 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000711 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000712 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000713 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000714 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000715 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000716 RECORD(SEMA_DECL_REFS);
717 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
718 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000719 RECORD(UPDATE_VISIBLE);
720 RECORD(DECL_UPDATE_OFFSETS);
721 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000722 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000723 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000724 RECORD(FP_PRAGMA_OPTIONS);
725 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +0000726 RECORD(OPENCL_EXTENSION_TYPES);
727 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000728 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000729 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000730 RECORD(MODULE_OFFSET_MAP);
731 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000732 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000733 RECORD(FILE_SORTED_DECLS);
734 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000735 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000736 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000737 RECORD(INTERESTING_IDENTIFIERS);
738 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000739 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000740 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000741 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000742 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000743 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000744 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +0000745 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000746 RECORD(PP_CONDITIONAL_STACK);
Douglas Gregor358cd442012-01-15 16:58:34 +0000747
Chris Lattner28fa4e62009-04-26 22:26:21 +0000748 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000749 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000750 RECORD(SM_SLOC_FILE_ENTRY);
751 RECORD(SM_SLOC_BUFFER_ENTRY);
752 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000753 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000754 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner28fa4e62009-04-26 22:26:21 +0000756 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000757 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000758 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000759 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000760 RECORD(PP_MACRO_OBJECT_LIKE);
761 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000762 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000763
Richard Smithfa715652015-08-31 22:43:10 +0000764 // Submodule Block.
765 BLOCK(SUBMODULE_BLOCK);
766 RECORD(SUBMODULE_METADATA);
767 RECORD(SUBMODULE_DEFINITION);
768 RECORD(SUBMODULE_UMBRELLA_HEADER);
769 RECORD(SUBMODULE_HEADER);
770 RECORD(SUBMODULE_TOPHEADER);
771 RECORD(SUBMODULE_UMBRELLA_DIR);
772 RECORD(SUBMODULE_IMPORTS);
773 RECORD(SUBMODULE_EXPORTS);
774 RECORD(SUBMODULE_REQUIRES);
775 RECORD(SUBMODULE_EXCLUDED_HEADER);
776 RECORD(SUBMODULE_LINK_LIBRARY);
777 RECORD(SUBMODULE_CONFIG_MACRO);
778 RECORD(SUBMODULE_CONFLICT);
779 RECORD(SUBMODULE_PRIVATE_HEADER);
780 RECORD(SUBMODULE_TEXTUAL_HEADER);
781 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +0000782 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +0000783 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +0000784
785 // Comments Block.
786 BLOCK(COMMENTS_BLOCK);
787 RECORD(COMMENTS_RAW_COMMENT);
788
Douglas Gregor12bfa382009-10-17 00:13:19 +0000789 // Decls and Types block.
790 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000791 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000792 RECORD(TYPE_COMPLEX);
793 RECORD(TYPE_POINTER);
794 RECORD(TYPE_BLOCK_POINTER);
795 RECORD(TYPE_LVALUE_REFERENCE);
796 RECORD(TYPE_RVALUE_REFERENCE);
797 RECORD(TYPE_MEMBER_POINTER);
798 RECORD(TYPE_CONSTANT_ARRAY);
799 RECORD(TYPE_INCOMPLETE_ARRAY);
800 RECORD(TYPE_VARIABLE_ARRAY);
801 RECORD(TYPE_VECTOR);
802 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000803 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000804 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000805 RECORD(TYPE_TYPEDEF);
806 RECORD(TYPE_TYPEOF_EXPR);
807 RECORD(TYPE_TYPEOF);
808 RECORD(TYPE_RECORD);
809 RECORD(TYPE_ENUM);
810 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000811 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000812 RECORD(TYPE_DECLTYPE);
813 RECORD(TYPE_ELABORATED);
814 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
815 RECORD(TYPE_UNRESOLVED_USING);
816 RECORD(TYPE_INJECTED_CLASS_NAME);
817 RECORD(TYPE_OBJC_OBJECT);
818 RECORD(TYPE_TEMPLATE_TYPE_PARM);
819 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
820 RECORD(TYPE_DEPENDENT_NAME);
821 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
822 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
823 RECORD(TYPE_PAREN);
Leonard Chanc72aaf62019-05-07 03:20:17 +0000824 RECORD(TYPE_MACRO_QUALIFIED);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000825 RECORD(TYPE_PACK_EXPANSION);
826 RECORD(TYPE_ATTRIBUTED);
827 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000828 RECORD(TYPE_AUTO);
829 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000830 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000831 RECORD(TYPE_DECAYED);
832 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +0000833 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +0000834 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000835 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000836 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000837 RECORD(DECL_ENUM);
838 RECORD(DECL_RECORD);
839 RECORD(DECL_ENUM_CONSTANT);
840 RECORD(DECL_FUNCTION);
841 RECORD(DECL_OBJC_METHOD);
842 RECORD(DECL_OBJC_INTERFACE);
843 RECORD(DECL_OBJC_PROTOCOL);
844 RECORD(DECL_OBJC_IVAR);
845 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000846 RECORD(DECL_OBJC_CATEGORY);
847 RECORD(DECL_OBJC_CATEGORY_IMPL);
848 RECORD(DECL_OBJC_IMPLEMENTATION);
849 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
850 RECORD(DECL_OBJC_PROPERTY);
851 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000852 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +0000853 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000854 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000855 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000856 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000857 RECORD(DECL_FILE_SCOPE_ASM);
858 RECORD(DECL_BLOCK);
859 RECORD(DECL_CONTEXT_LEXICAL);
860 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000861 RECORD(DECL_NAMESPACE);
862 RECORD(DECL_NAMESPACE_ALIAS);
863 RECORD(DECL_USING);
864 RECORD(DECL_USING_SHADOW);
865 RECORD(DECL_USING_DIRECTIVE);
866 RECORD(DECL_UNRESOLVED_USING_VALUE);
867 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
868 RECORD(DECL_LINKAGE_SPEC);
869 RECORD(DECL_CXX_RECORD);
870 RECORD(DECL_CXX_METHOD);
871 RECORD(DECL_CXX_CONSTRUCTOR);
872 RECORD(DECL_CXX_DESTRUCTOR);
873 RECORD(DECL_CXX_CONVERSION);
874 RECORD(DECL_ACCESS_SPEC);
875 RECORD(DECL_FRIEND);
876 RECORD(DECL_FRIEND_TEMPLATE);
877 RECORD(DECL_CLASS_TEMPLATE);
878 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
879 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000880 RECORD(DECL_VAR_TEMPLATE);
881 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
882 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000883 RECORD(DECL_FUNCTION_TEMPLATE);
884 RECORD(DECL_TEMPLATE_TYPE_PARM);
885 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
886 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Saar Razd7aae332019-07-10 21:25:49 +0000887 RECORD(DECL_CONCEPT);
Saar Raza0f50d72020-01-18 09:11:43 +0200888 RECORD(DECL_REQUIRES_EXPR_BODY);
Richard Smithefc884a2016-04-13 07:41:35 +0000889 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000890 RECORD(DECL_STATIC_ASSERT);
891 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +0000892 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000893 RECORD(DECL_INDIRECTFIELD);
894 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +0000895 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
896 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
897 RECORD(DECL_IMPORT);
898 RECORD(DECL_OMP_THREADPRIVATE);
899 RECORD(DECL_EMPTY);
900 RECORD(DECL_OBJC_TYPE_PARAM);
901 RECORD(DECL_OMP_CAPTUREDEXPR);
902 RECORD(DECL_PRAGMA_COMMENT);
903 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
904 RECORD(DECL_OMP_DECLARE_REDUCTION);
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000905 RECORD(DECL_OMP_ALLOCATE);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000906
Douglas Gregor03412ba2011-06-03 02:27:19 +0000907 // Statements and Exprs can occur in the Decls and Types block.
908 AddStmtsExprs(Stream, Record);
909
Douglas Gregor92a96f52011-02-08 21:58:10 +0000910 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000911 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +0000912 RECORD(PPD_MACRO_DEFINITION);
913 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000914
915 // Decls and Types block.
916 BLOCK(EXTENSION_BLOCK);
917 RECORD(EXTENSION_METADATA);
918
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000919 BLOCK(UNHASHED_CONTROL_BLOCK);
920 RECORD(SIGNATURE);
921 RECORD(DIAGNOSTIC_OPTIONS);
922 RECORD(DIAG_PRAGMA_MAPPINGS);
923
Chris Lattner28fa4e62009-04-26 22:26:21 +0000924#undef RECORD
925#undef BLOCK
926 Stream.ExitBlock();
927}
928
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000929/// Prepares a path for being written to an AST file by converting it
Richard Smith54cc3c22014-12-11 20:50:24 +0000930/// to an absolute path and removing nested './'s.
931///
932/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000933static bool cleanPathForOutput(FileManager &FileMgr,
934 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +0000935 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000936 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +0000937}
938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000939/// Adjusts the given filename to only write out the portion of the
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000940/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000941///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000942/// \param Filename the file name to adjust.
943///
Richard Smith7ed1bc92014-12-05 22:42:13 +0000944/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
945/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000946///
947/// \returns either the original filename (if it needs no adjustment) or the
948/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000949static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +0000950adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000951 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000952
Richard Smith7ed1bc92014-12-05 22:42:13 +0000953 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000954 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000956 // Verify that the filename and the system root have the same prefix.
957 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000958 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
959 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000960 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000962 // We hit the end of the filename before we hit the end of the system root.
963 if (!Filename[Pos])
964 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000965
Richard Smith7ed1bc92014-12-05 22:42:13 +0000966 // If there's not a path separator at the end of the base directory nor
967 // immediately after it, then this isn't within the base directory.
968 if (!llvm::sys::path::is_separator(Filename[Pos])) {
969 if (!llvm::sys::path::is_separator(BaseDir.back()))
970 return Filename;
971 } else {
972 // If the file name has a '/' at the current position, skip over the '/'.
973 // We distinguish relative paths from absolute paths by the
974 // absence of '/' at the beginning of relative paths.
975 //
976 // FIXME: This is wrong. We distinguish them by asking if the path is
977 // absolute, which isn't the same thing. And there might be multiple '/'s
978 // in a row. Use a better mechanism to indicate whether we have emitted an
979 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000980 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000983 return Filename + Pos;
984}
Chris Lattner28fa4e62009-04-26 22:26:21 +0000985
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000986ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
987 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
988 llvm::SHA1 Hasher;
989 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
990 auto Hash = Hasher.result();
991
992 // Convert to an array [5*i32].
993 ASTFileSignature Signature;
994 auto LShift = [&](unsigned char Val, unsigned Shift) {
995 return (uint32_t)Val << Shift;
996 };
997 for (int I = 0; I != 5; ++I)
998 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
999 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1000
1001 return Signature;
1002}
1003
1004ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1005 ASTContext &Context) {
1006 // Flush first to prepare the PCM hash (signature).
1007 Stream.FlushToWord();
1008 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1009
1010 // Enter the block and prepare to write records.
1011 RecordData Record;
1012 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1013
1014 // For implicit modules, write the hash of the PCM as its signature.
1015 ASTFileSignature Signature;
1016 if (WritingModule &&
1017 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1018 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1019 Record.append(Signature.begin(), Signature.end());
1020 Stream.EmitRecord(SIGNATURE, Record);
1021 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001022 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001023
1024 // Diagnostic options.
1025 const auto &Diags = Context.getDiagnostics();
1026 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1027#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1028#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1029 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1030#include "clang/Basic/DiagnosticOptions.def"
1031 Record.push_back(DiagOpts.Warnings.size());
1032 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1033 AddString(DiagOpts.Warnings[I], Record);
1034 Record.push_back(DiagOpts.Remarks.size());
1035 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1036 AddString(DiagOpts.Remarks[I], Record);
1037 // Note: we don't serialize the log or serialization file names, because they
1038 // are generally transient files and will almost always be overridden.
1039 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1040
1041 // Write out the diagnostic/pragma mappings.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001042 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001043
1044 // Leave the options block.
1045 Stream.ExitBlock();
1046 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001047}
1048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001049/// Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001050void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1051 StringRef isysroot,
1052 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001053 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001054
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001055 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001056 RecordData Record;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001057
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001058 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001059 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001060 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1061 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1062 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1063 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1064 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1065 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001066 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001067 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001068 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1069 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001070 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001071 assert((!WritingModule || isysroot.empty()) &&
1072 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001073 {
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001074 RecordData::value_type Record[] = {
1075 METADATA,
1076 VERSION_MAJOR,
1077 VERSION_MINOR,
1078 CLANG_VERSION_MAJOR,
1079 CLANG_VERSION_MINOR,
1080 !isysroot.empty(),
1081 IncludeTimestamps,
1082 Context.getLangOpts().BuildingPCHWithObjectFile,
1083 ASTHasCompilerErrors};
Mehdi Amini57a41912015-09-10 01:46:39 +00001084 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1085 getClangFullRepositoryVersion());
1086 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001087
Richard Smith8b706102017-05-31 20:56:55 +00001088 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001089 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001090 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001091 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1092 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001093 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001094 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001095 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1096 }
1097
Richard Smith7ed1bc92014-12-05 22:42:13 +00001098 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001099 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001100 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001101
1102 // If the home of the module is the current working directory, then we
1103 // want to pick up the cwd of the build process loading the module, not
1104 // our cwd, when we load this module.
1105 if (!PP.getHeaderSearchInfo()
1106 .getHeaderSearchOpts()
1107 .ModuleMapFileHomeIsCwd ||
1108 WritingModule->Directory->getName() != StringRef(".")) {
1109 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001110 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001111 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001113 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001114
Mehdi Amini57a41912015-09-10 01:46:39 +00001115 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001116 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1117 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001118
1119 // Write out all other paths relative to the base directory if possible.
1120 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1121 } else if (!isysroot.empty()) {
1122 // Write out paths relative to the sysroot if possible.
1123 BaseDirectory = isysroot;
1124 }
1125
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001126 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001127 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001128 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001129
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001130 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001131 AddPath(WritingModule->PresumedModuleMapFile.empty()
1132 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1133 : StringRef(WritingModule->PresumedModuleMapFile),
1134 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001135
1136 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001137 if (auto *AdditionalModMaps =
1138 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001139 Record.push_back(AdditionalModMaps->size());
1140 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001141 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001142 } else {
1143 Record.push_back(0);
1144 }
1145
1146 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001147 }
1148
Douglas Gregor112b9072012-10-18 05:31:06 +00001149 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001150 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001151 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001152 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001153
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001154 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001155 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001156 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001157 continue;
1158
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001159 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1160 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001161
1162 // If we have calculated signature, there is no need to store
1163 // the size or timestamp.
1164 Record.push_back(M.Signature ? 0 : M.File->getSize());
1165 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1166
1167 for (auto I : M.Signature)
1168 Record.push_back(I);
1169
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001170 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001171 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001172 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001173 Stream.EmitRecord(IMPORTS, Record);
1174 }
Mike Stump11289f42009-09-09 15:08:12 +00001175
Richard Smith0516b182015-09-08 19:40:14 +00001176 // Write the options block.
1177 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1178
Douglas Gregor112b9072012-10-18 05:31:06 +00001179 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001180 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001181 const LangOptions &LangOpts = Context.getLangOpts();
1182#define LANGOPT(Name, Bits, Default, Description) \
1183 Record.push_back(LangOpts.Name);
1184#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1185 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001186#include "clang/Basic/LangOptions.def"
1187#define SANITIZER(NAME, ID) \
1188 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001189#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001190
Ben Langmuircd98cb72015-06-23 18:20:18 +00001191 Record.push_back(LangOpts.ModuleFeatures.size());
1192 for (StringRef Feature : LangOpts.ModuleFeatures)
1193 AddString(Feature, Record);
1194
Douglas Gregor112b9072012-10-18 05:31:06 +00001195 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1196 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001197
1198 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001199
1200 // Comment options.
1201 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001202 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1203 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001204 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001205 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001206
Samuel Antaoee8fb302016-01-06 13:42:12 +00001207 // OpenMP offloading options.
1208 Record.push_back(LangOpts.OMPTargetTriples.size());
1209 for (auto &T : LangOpts.OMPTargetTriples)
1210 AddString(T.getTriple(), Record);
1211
1212 AddString(LangOpts.OMPHostIRFile, Record);
1213
Douglas Gregor112b9072012-10-18 05:31:06 +00001214 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1215
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001216 // Target options.
1217 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001218 const TargetInfo &Target = Context.getTargetInfo();
1219 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001220 AddString(TargetOpts.Triple, Record);
1221 AddString(TargetOpts.CPU, Record);
1222 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001223 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1224 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1225 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1226 }
1227 Record.push_back(TargetOpts.Features.size());
1228 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1229 AddString(TargetOpts.Features[I], Record);
1230 }
1231 Stream.EmitRecord(TARGET_OPTIONS, Record);
1232
Douglas Gregorc6317db2012-10-24 15:49:58 +00001233 // File system options.
1234 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001235 const FileSystemOptions &FSOpts =
1236 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001237 AddString(FSOpts.WorkingDir, Record);
1238 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1239
Douglas Gregor2d302362012-10-24 16:50:34 +00001240 // Header search options.
1241 Record.clear();
1242 const HeaderSearchOptions &HSOpts
1243 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1244 AddString(HSOpts.Sysroot, Record);
1245
1246 // Include entries.
1247 Record.push_back(HSOpts.UserEntries.size());
1248 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1249 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1250 AddString(Entry.Path, Record);
1251 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001252 Record.push_back(Entry.IsFramework);
1253 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001254 }
1255
1256 // System header prefixes.
1257 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1258 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1259 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1260 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1261 }
1262
1263 AddString(HSOpts.ResourceDir, Record);
1264 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001265 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001266 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001267 Record.push_back(HSOpts.ImplicitModuleMaps);
1268 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001269 Record.push_back(HSOpts.UseBuiltinIncludes);
1270 Record.push_back(HSOpts.UseStandardSystemIncludes);
1271 Record.push_back(HSOpts.UseStandardCXXIncludes);
1272 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001273 // Write out the specific module cache path that contains the module files.
1274 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001275 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1276
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001277 // Preprocessor options.
1278 Record.clear();
1279 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1280
1281 // Macro definitions.
1282 Record.push_back(PPOpts.Macros.size());
1283 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1284 AddString(PPOpts.Macros[I].first, Record);
1285 Record.push_back(PPOpts.Macros[I].second);
1286 }
1287
1288 // Includes
1289 Record.push_back(PPOpts.Includes.size());
1290 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1291 AddString(PPOpts.Includes[I], Record);
1292
1293 // Macro includes
1294 Record.push_back(PPOpts.MacroIncludes.size());
1295 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1296 AddString(PPOpts.MacroIncludes[I], Record);
1297
Douglas Gregorb6368752012-10-24 23:41:50 +00001298 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001299 // Detailed record is important since it is used for the module cache hash.
1300 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001301 AddString(PPOpts.ImplicitPCHInclude, Record);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001302 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1303 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1304
Richard Smith0516b182015-09-08 19:40:14 +00001305 // Leave the options block.
1306 Stream.ExitBlock();
1307
Douglas Gregora3b20262011-05-06 21:43:30 +00001308 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001309 SourceManager &SM = Context.getSourceManager();
1310 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001311 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001312 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1313 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001314 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001315 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001316
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001317 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001318 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001319 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001320 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001321 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001322
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001323 Record.clear();
1324 Record.push_back(SM.getMainFileID().getOpaqueValue());
1325 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1326
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001327 // Original PCH directory
1328 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001329 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001330 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001332 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001333
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001334 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001335
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001336 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001337 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1338
Mehdi Amini57a41912015-09-10 01:46:39 +00001339 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001340 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1341 }
1342
Douglas Gregor49491f72013-03-15 22:15:07 +00001343 WriteInputFiles(Context.SourceMgr,
1344 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001345 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001346 Stream.ExitBlock();
1347}
1348
Douglas Gregor49491f72013-03-15 22:15:07 +00001349namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001351/// An input file.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001352struct InputFileEntry {
1353 const FileEntry *File;
1354 bool IsSystemFile;
1355 bool IsTransient;
1356 bool BufferOverridden;
1357 bool IsTopLevelModuleMap;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001358 uint32_t ContentHash[2];
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001359};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001360
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001361} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001362
1363void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1364 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001365 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001366 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001367
Douglas Gregor72be3902012-10-19 00:38:02 +00001368 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001369
Douglas Gregor72be3902012-10-19 00:38:02 +00001370 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001371 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001372 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001373 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001374 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1375 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001376 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001377 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001378 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001379 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001380 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001381
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001382 // Create input file hash abbreviation.
1383 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1384 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1385 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1386 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1387 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1388
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001389 // Get all ContentCache objects for files, sorted by whether the file is a
1390 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001391 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001392 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1393 // Get this source location entry.
1394 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001395 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001396
1397 // We only care about file entries that were not overridden.
1398 if (!SLoc->isFile())
1399 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001400 const SrcMgr::FileInfo &File = SLoc->getFile();
1401 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001402 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001403 continue;
1404
Douglas Gregor49491f72013-03-15 22:15:07 +00001405 InputFileEntry Entry;
1406 Entry.File = Cache->OrigEntry;
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001407 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
Richard Smitha8cfffa2015-11-26 02:04:16 +00001408 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001409 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001410 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1411 File.getIncludeLoc().isInvalid();
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001412
1413 auto ContentHash = hash_code(-1);
1414 if (PP->getHeaderSearchInfo()
1415 .getHeaderSearchOpts()
1416 .ValidateASTInputFilesContent) {
1417 auto *MemBuff = Cache->getRawBuffer();
1418 if (MemBuff)
1419 ContentHash = hash_value(MemBuff->getBuffer());
1420 else
1421 // FIXME: The path should be taken from the FileEntryRef.
1422 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1423 << Entry.File->getName();
1424 }
1425 auto CH = llvm::APInt(64, ContentHash);
1426 Entry.ContentHash[0] =
1427 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1428 Entry.ContentHash[1] =
1429 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1430
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001431 if (Entry.IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001432 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001433 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001434 SortedFiles.push_front(Entry);
1435 }
1436
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001437 unsigned UserFilesNum = 0;
1438 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001439 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001440 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001441 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001442 if (InputFileID != 0)
1443 continue; // already recorded this file.
1444
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001445 // Record this entry's offset.
1446 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001447
1448 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001449
Douglas Gregor49491f72013-03-15 22:15:07 +00001450 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001451 ++UserFilesNum;
1452
Douglas Gregor72be3902012-10-19 00:38:02 +00001453 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001454 // And whether this file was overridden.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001455 {
1456 RecordData::value_type Record[] = {
1457 INPUT_FILE,
1458 InputFileOffsets.size(),
1459 (uint64_t)Entry.File->getSize(),
1460 (uint64_t)getTimestampForOutput(Entry.File),
1461 Entry.BufferOverridden,
1462 Entry.IsTransient,
1463 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001464
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001465 // FIXME: The path should be taken from the FileEntryRef.
1466 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1467 }
1468
1469 // Emit content hash for this file.
1470 {
1471 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1472 Entry.ContentHash[1]};
1473 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1474 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001475 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001476
Douglas Gregor112b9072012-10-18 05:31:06 +00001477 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001478
1479 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001480 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001481 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1482 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001483 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1484 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001485 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001486 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001487
1488 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001489 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1490 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001491 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001492}
1493
Douglas Gregora7f71a92009-04-10 03:52:48 +00001494//===----------------------------------------------------------------------===//
1495// Source Manager Serialization
1496//===----------------------------------------------------------------------===//
1497
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001498/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001499/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001500static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001501 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001502
David Blaikieb44f0bf2017-01-04 22:36:43 +00001503 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001504 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1506 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001508 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001509 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001514 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001515}
1516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001517/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001518/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001519static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001520 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001521
David Blaikieb44f0bf2017-01-04 22:36:43 +00001522 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001523 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001529 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001530}
1531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001532/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001533/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001534static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1535 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001536 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001537
David Blaikieb44f0bf2017-01-04 22:36:43 +00001538 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001539 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1540 : SM_SLOC_BUFFER_BLOB));
1541 if (Compressed)
1542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001544 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001545}
1546
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001547/// Create an abbreviation for the SLocEntry that refers to a macro
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001548/// expansion.
1549static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001550 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001551
David Blaikieb44f0bf2017-01-04 22:36:43 +00001552 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001553 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Richard Smithb5f81712018-04-30 05:25:48 +00001558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
Douglas Gregor83243272009-04-15 18:05:10 +00001559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001560 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001561}
1562
Douglas Gregor09b69892011-02-10 17:09:37 +00001563namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001564
Douglas Gregor09b69892011-02-10 17:09:37 +00001565 // Trait used for the on-disk hash table of header search information.
1566 class HeaderFileInfoTrait {
1567 ASTWriter &Writer;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001568
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001569 // Keep track of the framework names we've used during serialization.
1570 SmallVector<char, 128> FrameworkStringData;
1571 llvm::StringMap<unsigned> FrameworkNameOffset;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001572
Douglas Gregor09b69892011-02-10 17:09:37 +00001573 public:
Richard Smith040e1262017-06-02 01:55:39 +00001574 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1575
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001576 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001577 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001578 off_t Size;
1579 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001580 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001581 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001582
1583 using UnresolvedModule =
1584 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001585
Richard Smith040e1262017-06-02 01:55:39 +00001586 struct data_type {
1587 const HeaderFileInfo &HFI;
1588 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1589 UnresolvedModule Unresolved;
1590 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001591 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001592
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001593 using hash_value_type = unsigned;
1594 using offset_type = unsigned;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001595
Richard Smithe75ee0f2015-08-17 07:13:32 +00001596 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001597 // The hash is based only on size/time of the file, so that the reader can
1598 // match even when symlinking or excess path elements ("foo/../", "../")
1599 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001600 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001601 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001602
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001603 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001604 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001605 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001606
Peter Collingbournee3f65292018-05-18 19:46:24 +00001607 endian::Writer LE(Out, little);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001608 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001609 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001610 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001611 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001612 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1613 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001614 if (Data.Unresolved.getPointer())
1615 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001616 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001617 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001618 }
Richard Smith040e1262017-06-02 01:55:39 +00001619
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001620 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001621 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001622
Peter Collingbournee3f65292018-05-18 19:46:24 +00001623 endian::Writer LE(Out, little);
Richard Smith040e1262017-06-02 01:55:39 +00001624 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001625 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001626 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001627 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001628 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001629 }
Richard Smith040e1262017-06-02 01:55:39 +00001630
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001631 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001632 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001633 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001634
Peter Collingbournee3f65292018-05-18 19:46:24 +00001635 endian::Writer LE(Out, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001636 uint64_t Start = Out.tell(); (void)Start;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001637
Richard Smithf3f84612017-06-29 02:19:42 +00001638 unsigned char Flags = (Data.HFI.isImport << 5)
1639 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001640 | (Data.HFI.DirInfo << 1)
1641 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001642 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001643 LE.write<uint16_t>(Data.HFI.NumIncludes);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001644
Richard Smith040e1262017-06-02 01:55:39 +00001645 if (!Data.HFI.ControllingMacro)
1646 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001647 else
Richard Smith040e1262017-06-02 01:55:39 +00001648 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1649
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001650 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001651 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001652 // If this header refers into a framework, save the framework name.
1653 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00001654 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001655 if (Pos == FrameworkNameOffset.end()) {
1656 Offset = FrameworkStringData.size() + 1;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001657 FrameworkStringData.append(Data.HFI.Framework.begin(),
Richard Smith040e1262017-06-02 01:55:39 +00001658 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001659 FrameworkStringData.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001660
Richard Smith040e1262017-06-02 01:55:39 +00001661 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001662 } else
1663 Offset = Pos->second;
1664 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001665 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001666
Richard Smith040e1262017-06-02 01:55:39 +00001667 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1668 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1669 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00001670 assert((Value >> 2) == ModID && "overflow in header module info");
1671 LE.write<uint32_t>(Value);
1672 }
Richard Smith040e1262017-06-02 01:55:39 +00001673 };
1674
1675 // FIXME: If the header is excluded, we should write out some
1676 // record of that fact.
1677 for (auto ModInfo : Data.KnownHeaders)
1678 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1679 if (Data.Unresolved.getPointer())
1680 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001681
Douglas Gregor09b69892011-02-10 17:09:37 +00001682 assert(Out.tell() - Start == DataLen && "Wrong data length");
1683 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001684
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001685 const char *strings_begin() const { return FrameworkStringData.begin(); }
1686 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001687 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001688
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001689} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00001690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001691/// Write the header search block for the list of files that
Douglas Gregor09b69892011-02-10 17:09:37 +00001692///
1693/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001694void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00001695 HeaderFileInfoTrait GeneratorTrait(*this);
1696 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1697 SmallVector<const char *, 4> SavedStrings;
1698 unsigned NumHeaderSearchEntries = 0;
1699
1700 // Find all unresolved headers for the current module. We generally will
1701 // have resolved them before we get here, but not necessarily: we might be
1702 // compiling a preprocessed module, where there is no requirement for the
1703 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00001704 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00001705 if (WritingModule) {
1706 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1707 while (!Worklist.empty()) {
1708 Module *M = Worklist.pop_back_val();
1709 if (!M->isAvailable())
1710 continue;
1711
1712 // Map to disk files where possible, to pick up any missing stat
1713 // information. This also means we don't need to check the unresolved
1714 // headers list when emitting resolved headers in the first loop below.
1715 // FIXME: It'd be preferable to avoid doing this if we were given
1716 // sufficient stat information in the module map.
1717 HS.getModuleMap().resolveHeaderDirectives(M);
1718
1719 // If the file didn't exist, we can still create a module if we were given
1720 // enough information in the module map.
1721 for (auto U : M->MissingHeaders) {
1722 // Check that we were given enough information to build a module
1723 // without this file existing on disk.
1724 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1725 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1726 << WritingModule->getFullModuleName() << U.Size.hasValue()
1727 << U.FileName;
1728 continue;
1729 }
1730
1731 // Form the effective relative pathname for the file.
1732 SmallString<128> Filename(M->Directory->getName());
1733 llvm::sys::path::append(Filename, U.FileName);
1734 PreparePathForOutput(Filename);
1735
1736 StringRef FilenameDup = strdup(Filename.c_str());
1737 SavedStrings.push_back(FilenameDup.data());
1738
1739 HeaderFileInfoTrait::key_type Key = {
1740 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1741 };
1742 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00001743 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00001744 };
1745 // FIXME: Deal with cases where there are multiple unresolved header
1746 // directives in different submodules for the same header.
1747 Generator.insert(Key, Data, GeneratorTrait);
1748 ++NumHeaderSearchEntries;
1749 }
1750
1751 Worklist.append(M->submodule_begin(), M->submodule_end());
1752 }
1753 }
1754
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001755 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001756 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001757
Douglas Gregor09b69892011-02-10 17:09:37 +00001758 if (FilesByUID.size() > HS.header_file_size())
1759 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00001760
Douglas Gregor09b69892011-02-10 17:09:37 +00001761 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1762 const FileEntry *File = FilesByUID[UID];
1763 if (!File)
1764 continue;
1765
Richard Smith386bb072015-08-18 23:42:23 +00001766 // Get the file info. This will load info from the external source if
1767 // necessary. Skip emitting this file if we have no information on it
1768 // as a header file (in which case HFI will be null) or if it hasn't
1769 // changed since it was loaded. Also skip it if it's for a modular header
1770 // from a different module; in that case, we rely on the module(s)
1771 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001772 const HeaderFileInfo *HFI =
1773 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1774 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001775 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001776
Richard Smith7ed1bc92014-12-05 22:42:13 +00001777 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001778 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001779 SmallString<128> FilenameTmp(Filename);
1780 if (PreparePathForOutput(FilenameTmp)) {
1781 // If we performed any translation on the file name at all, we need to
1782 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001783 Filename = StringRef(strdup(FilenameTmp.c_str()));
1784 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00001785 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001786
Richard Smith040e1262017-06-02 01:55:39 +00001787 HeaderFileInfoTrait::key_type Key = {
1788 Filename, File->getSize(), getTimestampForOutput(File)
1789 };
1790 HeaderFileInfoTrait::data_type Data = {
1791 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
1792 };
1793 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001794 ++NumHeaderSearchEntries;
1795 }
Richard Smith040e1262017-06-02 01:55:39 +00001796
Douglas Gregor09b69892011-02-10 17:09:37 +00001797 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001798 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001799 uint32_t BucketOffset;
1800 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001801 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001802
Douglas Gregor09b69892011-02-10 17:09:37 +00001803 llvm::raw_svector_ostream Out(TableData);
1804 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00001805 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001806 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1807 }
1808
1809 // Create a blob abbreviation
1810 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001811
David Blaikieb44f0bf2017-01-04 22:36:43 +00001812 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00001813 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001816 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00001818 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001819
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001820 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001821 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1822 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001823 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001824 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001825
Douglas Gregor09b69892011-02-10 17:09:37 +00001826 // Free all of the strings we had to duplicate.
1827 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001828 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001829}
1830
George Rimarc39f5492017-01-17 15:45:31 +00001831static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1832 unsigned SLocBufferBlobCompressedAbbrv,
1833 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001834 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00001835
1836 // Compress the buffer if possible. We expect that almost all PCM
1837 // consumers will not want its contents.
1838 SmallString<0> CompressedBuffer;
1839 if (llvm::zlib::isAvailable()) {
1840 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1841 if (!E) {
1842 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1843 Blob.size() - 1};
1844 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1845 CompressedBuffer);
1846 return;
1847 }
1848 llvm::consumeError(std::move(E));
1849 }
1850
1851 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1852 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1853}
1854
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001855/// Writes the block containing the serialized form of the
Douglas Gregora7f71a92009-04-10 03:52:48 +00001856/// source manager.
1857///
1858/// TODO: We should probably use an on-disk hash table (stored in a
1859/// blob), indexed based on the file name, so that we only create
1860/// entries for files that we actually need. In the common case (no
1861/// errors), we probably won't have to create file entries for any of
1862/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001863void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001864 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001865 RecordData Record;
1866
Chris Lattner0910e3b2009-04-10 17:16:57 +00001867 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001868 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001869
1870 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001871 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1872 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001873 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1874 unsigned SLocBufferBlobCompressedAbbrv =
1875 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001876 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001877
Douglas Gregor258ae542009-04-27 06:38:32 +00001878 // Write out the source location entry table. We skip the first
1879 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001880 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001881 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001882 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1883 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001884 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001885 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001886 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001887 FileID FID = FileID::get(I);
1888 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001889
Douglas Gregor258ae542009-04-27 06:38:32 +00001890 // Record the offset of this source-location entry.
1891 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1892
1893 // Figure out which record code to use.
1894 unsigned Code;
1895 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001896 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1897 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001898 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001899 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001900 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001901 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001902 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001903 Record.clear();
1904 Record.push_back(Code);
1905
Douglas Gregor925296b2011-07-19 16:10:42 +00001906 // Starting offset of this entry within this module, so skip the dummy.
1907 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001908 if (SLoc->isFile()) {
1909 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001910 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001911 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1912 Record.push_back(File.hasLineDirectives());
1913
1914 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001915 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001916 if (Content->OrigEntry) {
1917 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001918 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001919
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001920 // The source location entry is a file. Emit input file ID.
1921 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1922 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001924 Record.push_back(File.NumCreatedFIDs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001925
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001926 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001927 if (FDI != FileDeclIDs.end()) {
1928 Record.push_back(FDI->second->FirstDeclIndex);
1929 Record.push_back(FDI->second->DeclIDs.size());
1930 } else {
1931 Record.push_back(0);
1932 Record.push_back(0);
1933 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001934
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001935 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001936
Richard Smithaada85c2016-02-06 02:06:43 +00001937 if (Content->BufferOverridden || Content->IsTransient)
1938 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001939 } else {
1940 // The source location entry is a buffer. The blob associated
1941 // with this entry contains the contents of the buffer.
1942
1943 // We add one to the size so that we capture the trailing NULL
1944 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1945 // the reader side).
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001946 const llvm::MemoryBuffer *Buffer =
1947 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00001948 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001949 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00001950 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001951 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001952
Mehdi Amini99d1b292016-10-01 16:38:28 +00001953 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00001954 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00001955 }
Richard Smithaada85c2016-02-06 02:06:43 +00001956
1957 if (EmitBlob) {
1958 // Include the implicit terminating null character in the on-disk buffer
1959 // if we're writing it uncompressed.
1960 const llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001961 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Richard Smithaada85c2016-02-06 02:06:43 +00001962 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00001963 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
1964 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00001965 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001966 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001967 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001968 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00001969 AddSourceLocation(Expansion.getSpellingLoc(), Record);
1970 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
1971 AddSourceLocation(Expansion.isMacroArgExpansion()
1972 ? SourceLocation()
1973 : Expansion.getExpansionLocEnd(),
1974 Record);
Richard Smithb5f81712018-04-30 05:25:48 +00001975 Record.push_back(Expansion.isExpansionTokenRange());
Douglas Gregor258ae542009-04-27 06:38:32 +00001976
1977 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001978 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001979 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001980 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001981 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001982 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001983 }
1984 }
1985
Douglas Gregor8f45df52009-04-16 22:23:12 +00001986 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001987
1988 if (SLocEntryOffsets.empty())
1989 return;
1990
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001991 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00001992 // table is used for lazily loading source-location information.
1993 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001994
David Blaikieb44f0bf2017-01-04 22:36:43 +00001995 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001996 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00001997 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00001998 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00001999 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00002000 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002001 {
2002 RecordData::value_type Record[] = {
2003 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2004 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2005 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2006 bytes(SLocEntryOffsets));
2007 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002008 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002009 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002010 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002011
2012 // Write the line table. It depends on remapping working, so it must come
2013 // after the source location offsets.
2014 if (SourceMgr.hasLineTable()) {
2015 LineTableInfo &LineTable = SourceMgr.getLineTable();
2016
2017 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002018
2019 // Emit the needed file names.
2020 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002021 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002022 for (const auto &L : LineTable) {
2023 if (L.first.ID < 0)
2024 continue;
2025 for (auto &LE : L.second) {
2026 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002027 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002028 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2029 }
2030 }
2031 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002032
2033 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002034 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002035 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002036 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002037 continue;
2038
2039 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002040 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002041
2042 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002043 Record.push_back(L.second.size());
2044 for (const auto &LE : L.second) {
2045 Record.push_back(LE.FileOffset);
2046 Record.push_back(LE.LineNo);
2047 Record.push_back(FilenameMap[LE.FilenameID]);
2048 Record.push_back((unsigned)LE.FileKind);
2049 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002050 }
2051 }
Richard Smith63078492015-09-01 07:41:55 +00002052
Douglas Gregor925296b2011-07-19 16:10:42 +00002053 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2054 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002055}
2056
Douglas Gregorc5046832009-04-27 18:38:38 +00002057//===----------------------------------------------------------------------===//
2058// Preprocessor Serialization
2059//===----------------------------------------------------------------------===//
2060
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002061static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2062 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002063 if (MacroInfo *MI = MD->getMacroInfo())
2064 if (MI->isBuiltinMacro())
2065 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002066
2067 if (IsModule) {
2068 SourceLocation Loc = MD->getLocation();
2069 if (Loc.isInvalid())
2070 return true;
2071 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2072 return true;
2073 }
2074
2075 return false;
2076}
2077
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002078/// Writes the block containing the serialized form of the
Chris Lattnereeffaef2009-04-10 17:15:23 +00002079/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002080void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002081 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2082 if (PPRec)
2083 WritePreprocessorDetail(*PPRec);
2084
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002085 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002086 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002087
Chris Lattner0af3ba12009-04-13 01:29:17 +00002088 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2089 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002090 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002091 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002092 }
2093
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002094 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2095 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002096 auto SkipInfo = PP.getPreambleSkipInfo();
2097 if (SkipInfo.hasValue()) {
2098 Record.push_back(true);
2099 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2100 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2101 Record.push_back(SkipInfo->FoundNonSkipPortion);
2102 Record.push_back(SkipInfo->FoundElse);
2103 AddSourceLocation(SkipInfo->ElseLoc, Record);
2104 } else {
2105 Record.push_back(false);
2106 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002107 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2108 AddSourceLocation(Cond.IfLoc, Record);
2109 Record.push_back(Cond.WasSkipping);
2110 Record.push_back(Cond.FoundNonSkip);
2111 Record.push_back(Cond.FoundElse);
2112 }
2113 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2114 Record.clear();
2115 }
2116
Douglas Gregoreda6a892009-04-26 00:07:37 +00002117 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002118 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002119
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002120 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002121 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002122 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002123 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002124
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002125 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002126 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002127
Richard Smithee977932015-05-01 21:22:17 +00002128 // Construct the list of identifiers with macro directives that need to be
2129 // serialized.
2130 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2131 for (auto &Id : PP.getIdentifierTable())
2132 if (Id.second->hadMacroDefinition() &&
2133 (!Id.second->isFromAST() ||
2134 Id.second->hasChangedSinceDeserialization()))
2135 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002136 // Sort the set of macro definitions that need to be serialized by the
2137 // name of the macro, to provide a stable ordering.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00002138 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002139
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002140 // Emit the macro directives as a list and associate the offset with the
2141 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002142 for (const IdentifierInfo *Name : MacroIdentifiers) {
2143 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002144 auto StartOffset = Stream.GetCurrentBitNo();
2145
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002146 // Emit the macro directives in reverse source order.
2147 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002148 // Once we hit an ignored macro, we're done: the rest of the chain
2149 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002150 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002151 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002152
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002153 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002154 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002155 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002156 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002157 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002158 Record.push_back(VisMD->isPublic());
2159 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002160 }
Richard Smithd7329392015-04-21 21:46:32 +00002161
Richard Smithb8b2ed62015-04-23 18:18:26 +00002162 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002163 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002164 // We write out exported module macros for PCH as well.
2165 auto Leafs = PP.getLeafModuleMacros(Name);
2166 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2167 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2168 while (!Worklist.empty()) {
2169 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002170
Manman Ren33d80292016-05-31 18:19:32 +00002171 // Emit a record indicating this submodule exports this macro.
2172 ModuleMacroRecord.push_back(
2173 getSubmoduleID(Macro->getOwningModule()));
2174 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2175 for (auto *M : Macro->overrides())
2176 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002177
Manman Ren33d80292016-05-31 18:19:32 +00002178 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2179 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002180
Manman Ren33d80292016-05-31 18:19:32 +00002181 // Enqueue overridden macros once we've visited all their ancestors.
2182 for (auto *M : Macro->overrides())
2183 if (++Visits[M] == M->getNumOverridingMacros())
2184 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002185
Manman Ren33d80292016-05-31 18:19:32 +00002186 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002187 }
Richard Smithd7329392015-04-21 21:46:32 +00002188
Richard Smithee977932015-05-01 21:22:17 +00002189 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002190 continue;
2191
Richard Smithd7329392015-04-21 21:46:32 +00002192 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002193 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2194 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002195 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002197 /// Offsets of each of the macros into the bitstream, indexed by
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002198 /// the local macro ID
2199 ///
2200 /// For each identifier that is associated with a macro, this map
2201 /// provides the offset into the bitstream where that macro is
2202 /// defined.
2203 std::vector<uint32_t> MacroOffsets;
2204
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002205 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2206 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2207 MacroInfo *MI = MacroInfosToEmit[I].MI;
2208 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002209
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002210 if (ID < FirstMacroID) {
2211 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2212 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002213 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002214
2215 // Record the local offset of this macro.
2216 unsigned Index = ID - FirstMacroID;
2217 if (Index == MacroOffsets.size())
2218 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2219 else {
2220 if (Index > MacroOffsets.size())
2221 MacroOffsets.resize(Index + 1);
2222
2223 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2224 }
2225
2226 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002227 AddSourceLocation(MI->getDefinitionLoc(), Record);
2228 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2229 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002230 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002231 unsigned Code;
2232 if (MI->isObjectLike()) {
2233 Code = PP_MACRO_OBJECT_LIKE;
2234 } else {
2235 Code = PP_MACRO_FUNCTION_LIKE;
2236
2237 Record.push_back(MI->isC99Varargs());
2238 Record.push_back(MI->isGNUVarargs());
2239 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002240 Record.push_back(MI->getNumParams());
2241 for (const IdentifierInfo *Param : MI->params())
2242 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002243 }
2244
2245 // If we have a detailed preprocessing record, record the macro definition
2246 // ID that corresponds to this macro.
2247 if (PPRec)
2248 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2249
2250 Stream.EmitRecord(Code, Record);
2251 Record.clear();
2252
2253 // Emit the tokens array.
2254 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2255 // Note that we know that the preprocessor does not have any annotation
2256 // tokens in it because they are created by the parser, and thus can't
2257 // be in a macro definition.
2258 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002259 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002260 Stream.EmitRecord(PP_TOKEN, Record);
2261 Record.clear();
2262 }
2263 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002264 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002265
Douglas Gregor92a96f52011-02-08 21:58:10 +00002266 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002267
2268 // Write the offsets table for macro IDs.
2269 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002270
David Blaikieb44f0bf2017-01-04 22:36:43 +00002271 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002272 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2273 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2274 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2275 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2276
David Blaikieb44f0bf2017-01-04 22:36:43 +00002277 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002278 {
2279 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2280 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2281 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2282 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002283}
2284
2285void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002286 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002287 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002288
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002289 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002290
Douglas Gregor92a96f52011-02-08 21:58:10 +00002291 // Enter the preprocessor block.
2292 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002293
Douglas Gregoraae92242010-03-19 21:51:54 +00002294 // If the preprocessor has a preprocessing record, emit it.
2295 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002296 using namespace llvm;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002297
2298 // Set up the abbreviation for
Douglas Gregor92a96f52011-02-08 21:58:10 +00002299 unsigned InclusionAbbrev = 0;
2300 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002301 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002302 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002306 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002307 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002308 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002309 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002310
2311 unsigned FirstPreprocessorEntityID
2312 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002313 + NUM_PREDEF_PP_ENTITY_IDS;
2314 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002315 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002316 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2317 EEnd = PPRec.local_end();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002318 E != EEnd;
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002319 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002320 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002321
Richard Smith66a81862015-05-04 02:25:31 +00002322 PreprocessedEntityOffsets.push_back(
2323 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002324
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002325 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002326 // Record this macro definition's ID.
2327 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002328
Douglas Gregor92a96f52011-02-08 21:58:10 +00002329 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002330 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2331 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002332 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002333
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002334 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002335 Record.push_back(ME->isBuiltinMacro());
2336 if (ME->isBuiltinMacro())
2337 AddIdentifierRef(ME->getName(), Record);
2338 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002339 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002340 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002341 continue;
2342 }
2343
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002344 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002345 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002346 Record.push_back(ID->getFileName().size());
2347 Record.push_back(ID->wasInQuotes());
2348 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002349 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002350 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002351 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002352 // Check that the FileEntry is not null because it was not resolved and
2353 // we create a PCH even with compiler errors.
2354 if (ID->getFile())
2355 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002356 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002357 continue;
2358 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002359
Douglas Gregor92a96f52011-02-08 21:58:10 +00002360 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2361 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002362 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002363
Douglas Gregoraae92242010-03-19 21:51:54 +00002364 // Write the offsets table for the preprocessing record.
2365 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002366 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2367
Douglas Gregoraae92242010-03-19 21:51:54 +00002368 // Write the offsets table for identifier IDs.
2369 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002370
David Blaikieb44f0bf2017-01-04 22:36:43 +00002371 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002372 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002374 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002375 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002376
Mehdi Amini57a41912015-09-10 01:46:39 +00002377 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2378 FirstPreprocessorEntityID -
2379 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002380 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002381 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002382 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002383
2384 // Write the skipped region table for the preprocessing record.
2385 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2386 if (SkippedRanges.size() > 0) {
2387 std::vector<PPSkippedRange> SerializedSkippedRanges;
2388 SerializedSkippedRanges.reserve(SkippedRanges.size());
2389 for (auto const& Range : SkippedRanges)
2390 SerializedSkippedRanges.emplace_back(Range);
2391
2392 using namespace llvm;
2393 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2394 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2395 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2396 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2397
2398 Record.clear();
2399 Record.push_back(PPD_SKIPPED_RANGES);
2400 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2401 bytes(SerializedSkippedRanges));
2402 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002403}
2404
Richard Smith386bb072015-08-18 23:42:23 +00002405unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002406 if (!Mod)
2407 return 0;
2408
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002409 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2410 if (Known != SubmoduleIDs.end())
2411 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002412
Richard Smithdc1f0422016-07-20 19:10:16 +00002413 auto *Top = Mod->getTopLevelModule();
2414 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002415 (getLangOpts().CompilingPCH ||
2416 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002417 return 0;
2418
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002419 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2420}
2421
Richard Smith386bb072015-08-18 23:42:23 +00002422unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2423 // FIXME: This can easily happen, if we have a reference to a submodule that
2424 // did not result in us loading a module file for that submodule. For
2425 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2426 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2427 assert((ID || !Mod) &&
2428 "asked for module ID for non-local, non-imported module");
2429 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002430}
2431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002432/// Compute the number of modules within the given tree (including the
Douglas Gregor253eefe2011-12-01 00:59:36 +00002433/// given module).
2434static unsigned getNumberOfModules(Module *Mod) {
2435 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002436 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002437 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002438 ChildModules += getNumberOfModules(*Sub);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002439
Douglas Gregor253eefe2011-12-01 00:59:36 +00002440 return ChildModules + 1;
2441}
2442
Douglas Gregorde3ef502011-11-30 23:21:26 +00002443void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002444 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002445 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002446
Douglas Gregor69021972011-11-30 17:33:56 +00002447 // Write the abbreviations needed for the submodules block.
2448 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002449
David Blaikieb44f0bf2017-01-04 22:36:43 +00002450 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002451 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002454 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
Douglas Gregor69021972011-11-30 17:33:56 +00002464 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002465 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002466
David Blaikieb44f0bf2017-01-04 22:36:43 +00002467 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002468 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002470 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002471
David Blaikieb44f0bf2017-01-04 22:36:43 +00002472 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002473 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2474 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002475 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002476
David Blaikieb44f0bf2017-01-04 22:36:43 +00002477 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002478 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2479 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002480 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002481
David Blaikieb44f0bf2017-01-04 22:36:43 +00002482 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002483 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002485 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002486
David Blaikieb44f0bf2017-01-04 22:36:43 +00002487 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002488 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2490 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002491 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002492
David Blaikieb44f0bf2017-01-04 22:36:43 +00002493 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002494 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002496 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002497
David Blaikieb44f0bf2017-01-04 22:36:43 +00002498 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002499 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002501 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002502
David Blaikieb44f0bf2017-01-04 22:36:43 +00002503 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002504 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002506 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002507
David Blaikieb44f0bf2017-01-04 22:36:43 +00002508 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002509 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002511 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002512
David Blaikieb44f0bf2017-01-04 22:36:43 +00002513 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002514 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2516 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002517 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002518
David Blaikieb44f0bf2017-01-04 22:36:43 +00002519 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002520 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2521 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002522 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002523
David Blaikieb44f0bf2017-01-04 22:36:43 +00002524 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002525 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002528 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002529
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002530 Abbrev = std::make_shared<BitCodeAbbrev>();
2531 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2533 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2534
Douglas Gregor253eefe2011-12-01 00:59:36 +00002535 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002536 RecordData::value_type Record[] = {
2537 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002538 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002539 Stream.EmitRecord(SUBMODULE_METADATA, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002540
Douglas Gregor69021972011-11-30 17:33:56 +00002541 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002542 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002543 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002544 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002545 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002546 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002547 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002548
2549 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002550 if (Mod->Parent) {
2551 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002552 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002553 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002554
2555 // Emit the definition of the block.
2556 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002557 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2558 ID,
2559 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002560 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002561 Mod->IsFramework,
2562 Mod->IsExplicit,
2563 Mod->IsSystem,
2564 Mod->IsExternC,
2565 Mod->InferSubmodules,
2566 Mod->InferExplicitSubmodules,
2567 Mod->InferExportWildcard,
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002568 Mod->ConfigMacrosExhaustive,
2569 Mod->ModuleMapIsPrivate};
Mehdi Amini57a41912015-09-10 01:46:39 +00002570 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2571 }
2572
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002573 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002574 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002575 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002576 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002577 }
2578
Douglas Gregor69021972011-11-30 17:33:56 +00002579 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002580 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002581 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002582 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2583 UmbrellaHeader.NameAsWritten);
2584 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002585 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2586 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002587 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002588 }
Richard Smith306d8922014-10-22 23:50:56 +00002589
Douglas Gregor69021972011-11-30 17:33:56 +00002590 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002591 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002592 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002593 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002594 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002595 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002596 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2597 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2598 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002599 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002600 Module::HK_PrivateTextual},
2601 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002602 };
2603 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002604 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002605 for (auto &H : Mod->Headers[HL.HeaderKind])
2606 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2607 }
2608
2609 // Emit the top headers.
2610 {
2611 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002612 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002613 for (auto *H : TopHeaders)
2614 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002615 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002616
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002617 // Emit the imports.
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002618 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002619 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002620 for (auto *I : Mod->Imports)
2621 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002622 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2623 }
2624
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002625 // Emit the exports.
Douglas Gregor24bb9232011-12-02 18:58:38 +00002626 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002627 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002628 for (const auto &E : Mod->Exports) {
2629 // FIXME: This may fail; we don't require that all exported modules
2630 // are local or imported.
2631 Record.push_back(getSubmoduleID(E.getPointer()));
2632 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002633 }
2634 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2635 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002636
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002637 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2638 // Might be unnecessary as use declarations are only used to build the
2639 // module itself.
2640
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002641 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002642 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002643 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2644 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002645 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002646 }
2647
Douglas Gregorfb912652013-03-20 21:10:35 +00002648 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002649 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002650 // FIXME: This may fail; we don't require that all conflicting modules
2651 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002652 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2653 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002654 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002655 }
2656
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002657 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002658 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002659 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002660 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002661 }
2662
Richard Smithdc1f0422016-07-20 19:10:16 +00002663 // Emit the initializers, if any.
2664 RecordData Inits;
2665 for (Decl *D : Context->getModuleInitializers(Mod))
2666 Inits.push_back(GetDeclRef(D));
2667 if (!Inits.empty())
2668 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2669
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002670 // Emit the name of the re-exported module, if any.
2671 if (!Mod->ExportAsModule.empty()) {
2672 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2673 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2674 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002675
Douglas Gregor69021972011-11-30 17:33:56 +00002676 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002677 for (auto *M : Mod->submodules())
2678 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002679 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002680
Douglas Gregor69021972011-11-30 17:33:56 +00002681 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002682
Richard Smith23d8d032015-05-14 00:45:20 +00002683 assert((NextSubmoduleID - FirstSubmoduleID ==
2684 getNumberOfModules(WritingModule)) &&
2685 "Wrong # of submodules; found a reference to a non-local, "
2686 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002687}
2688
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002689void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2690 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002691 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2692 DiagStateIDMap;
2693 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002694 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002695
Richard Smithe37391c2017-05-03 00:28:49 +00002696 auto EncodeDiagStateFlags =
2697 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2698 unsigned Result = (unsigned)DS->ExtBehavior;
2699 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00002700 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2701 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2702 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00002703 Result = (Result << 1) | Val;
2704 return Result;
2705 };
2706
2707 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2708 Record.push_back(Flags);
2709
Richard Smithd230de22017-01-26 01:01:01 +00002710 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2711 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00002712 // Ensure that the diagnostic state wasn't modified since it was created.
2713 // We will not correctly round-trip this information otherwise.
2714 assert(Flags == EncodeDiagStateFlags(State) &&
2715 "diag state flags vary in single AST file");
2716
Richard Smithd230de22017-01-26 01:01:01 +00002717 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002718 Record.push_back(DiagStateID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002719
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002720 if (DiagStateID == 0) {
2721 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002722
2723 // Add a placeholder for the number of mappings.
2724 auto SizeIdx = Record.size();
2725 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00002726 for (const auto &I : *State) {
2727 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002728 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00002729 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002730 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002731 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002732 // Update the placeholder.
2733 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00002734 }
2735 };
2736
2737 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00002738
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002739 // Reserve a spot for the number of locations with state transitions.
2740 auto NumLocationsIdx = Record.size();
2741 Record.emplace_back();
2742
2743 // Emit the state transitions.
2744 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00002745 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2746 if (!FileIDAndFile.first.isValid() ||
2747 !FileIDAndFile.second.HasLocalTransitions)
2748 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002749 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00002750
2751 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2752 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2753 AddSourceLocation(Loc, Record);
2754
Richard Smithd230de22017-01-26 01:01:01 +00002755 Record.push_back(FileIDAndFile.second.StateTransitions.size());
2756 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2757 Record.push_back(StatePoint.Offset);
2758 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002759 }
2760 }
2761
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002762 // Backpatch the number of locations.
2763 Record[NumLocationsIdx] = NumLocations;
2764
2765 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00002766 //
2767 // This also protects against a hypothetical corner case with simulating
2768 // -Werror settings for implicit modules in the ASTReader, where reading
2769 // CurDiagState out of context could change whether warning pragmas are
2770 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002771 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2772 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2773
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00002774 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002775}
2776
Douglas Gregorc5046832009-04-27 18:38:38 +00002777//===----------------------------------------------------------------------===//
2778// Type Serialization
2779//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002781/// Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002782void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002783 TypeIdx &IdxRef = TypeIdxs[T];
2784 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2785 IdxRef = TypeIdx(NextTypeID++);
2786 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002788 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002789
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002790 // Emit the type's representation.
John McCalld505e572019-12-13 21:54:44 -05002791 uint64_t Offset = ASTTypeWriter(*this).write(T);
John McCall8ccfcb52009-09-24 19:53:00 +00002792
Richard Smith290d8012016-04-06 17:06:00 +00002793 // Record the offset for this type.
2794 unsigned Index = Idx.getIndex() - FirstTypeID;
2795 if (TypeOffsets.size() == Index)
2796 TypeOffsets.push_back(Offset);
2797 else if (TypeOffsets.size() < Index) {
2798 TypeOffsets.resize(Index + 1);
2799 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002800 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002801 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002802 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002803}
2804
Douglas Gregorc5046832009-04-27 18:38:38 +00002805//===----------------------------------------------------------------------===//
2806// Declaration Serialization
2807//===----------------------------------------------------------------------===//
2808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002809/// Write the block containing all of the declaration IDs
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002810/// lexically declared within the given DeclContext.
2811///
2812/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002813/// bitstream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002814uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002815 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002816 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002817 return 0;
2818
Douglas Gregor8f45df52009-04-16 22:23:12 +00002819 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002820 SmallVector<uint32_t, 128> KindDeclPairs;
2821 for (const auto *D : DC->decls()) {
2822 KindDeclPairs.push_back(D->getKind());
2823 KindDeclPairs.push_back(GetDeclRef(D));
2824 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002825
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002826 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002827 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002828 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2829 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002830 return Offset;
2831}
2832
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002833void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002834 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002835
2836 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002837 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002838 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002842 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002843 {
2844 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2845 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2846 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2847 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002848
2849 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002850 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002851 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002855 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002856 {
2857 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2858 FirstDeclID - NUM_PREDEF_DECL_IDS};
2859 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2860 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002861}
2862
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002863void ASTWriter::WriteFileDeclIDsMap() {
2864 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002865
Chandler Carruthb306d732015-03-27 00:31:20 +00002866 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2867 FileDeclIDs.begin(), FileDeclIDs.end());
Fangrui Song55fab262018-09-26 22:16:28 +00002868 llvm::sort(SortedFileDeclIDs, llvm::less_first());
Chandler Carruthb306d732015-03-27 00:31:20 +00002869
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002870 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002871 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2872 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2873 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2874 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2875 for (auto &LocDeclEntry : Info.DeclIDs)
2876 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002877 }
2878
David Blaikieb44f0bf2017-01-04 22:36:43 +00002879 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002880 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002881 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002882 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002883 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002884 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2885 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002886 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002887}
2888
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002889void ASTWriter::WriteComments() {
2890 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Ilya Biryukov45643102018-07-09 11:33:23 +00002891 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2892 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2893 return;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002894 RecordData Record;
Jan Korousf31d8df2019-08-13 18:11:44 +00002895 for (const auto &FO : Context->Comments.OrderedComments) {
2896 for (const auto &OC : FO.second) {
2897 const RawComment *I = OC.second;
2898 Record.clear();
2899 AddSourceRange(I->getSourceRange(), Record);
2900 Record.push_back(I->getKind());
2901 Record.push_back(I->isTrailingComment());
2902 Record.push_back(I->isAlmostTrailingComment());
2903 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2904 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002905 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002906}
2907
Douglas Gregorc5046832009-04-27 18:38:38 +00002908//===----------------------------------------------------------------------===//
2909// Global Method Pool and Selector Serialization
2910//===----------------------------------------------------------------------===//
2911
Douglas Gregore84a9da2009-04-20 20:36:09 +00002912namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002913
Douglas Gregorc78d3462009-04-24 21:10:55 +00002914// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002915class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002916 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002917
2918public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002919 using key_type = Selector;
2920 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00002921
Sebastian Redl834bb972010-08-04 17:20:04 +00002922 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002923 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002924 ObjCMethodList Instance, Factory;
2925 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002926 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002927
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002928 using hash_value_type = unsigned;
2929 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00002930
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002931 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00002932
Justin Bogner25463f12014-04-18 20:27:24 +00002933 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002934 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002935 }
Mike Stump11289f42009-09-09 15:08:12 +00002936
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002937 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002938 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002939 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002940 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002941
Peter Collingbournee3f65292018-05-18 19:46:24 +00002942 endian::Writer LE(Out, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002943 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002944 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002945 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2946 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002947 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002948 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002949 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002950 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002951 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002952 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002953 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002954 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002955 return std::make_pair(KeyLen, DataLen);
2956 }
Mike Stump11289f42009-09-09 15:08:12 +00002957
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002958 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002959 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002960
Peter Collingbournee3f65292018-05-18 19:46:24 +00002961 endian::Writer LE(Out, little);
Mike Stump11289f42009-09-09 15:08:12 +00002962 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002963 assert((Start >> 32) == 0 && "Selector key offset too large");
2964 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002965 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002966 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002967 if (N == 0)
2968 N = 1;
2969 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002970 LE.write<uint32_t>(
2971 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002974 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002975 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002976 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002977
Peter Collingbournee3f65292018-05-18 19:46:24 +00002978 endian::Writer LE(Out, little);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002979 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002980 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002981 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002982 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002983 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002984 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002985 ++NumInstanceMethods;
2986
2987 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002988 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002989 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002990 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002991 ++NumFactoryMethods;
2992
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002993 unsigned InstanceBits = Methods.Instance.getBits();
2994 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002995 unsigned InstanceHasMoreThanOneDeclBit =
2996 Methods.Instance.hasMoreThanOneDecl();
2997 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2998 (InstanceHasMoreThanOneDeclBit << 2) |
2999 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003000 unsigned FactoryBits = Methods.Factory.getBits();
3001 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003002 unsigned FactoryHasMoreThanOneDeclBit =
3003 Methods.Factory.hasMoreThanOneDecl();
3004 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3005 (FactoryHasMoreThanOneDeclBit << 2) |
3006 FactoryBits;
3007 LE.write<uint16_t>(FullInstanceBits);
3008 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003009 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003010 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003011 if (Method->getMethod())
3012 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003013 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003014 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003015 if (Method->getMethod())
3016 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003017
3018 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003019 }
3020};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003021
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003022} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003023
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003024/// Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003025///
3026/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003027/// in an on-disk hash table indexed by the selector. The hash table also
3028/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003029void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003030 using namespace llvm;
3031
Sebastian Redla19a67f2010-08-03 21:58:15 +00003032 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003033 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003034 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003035 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003036 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003038 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003039 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003040
Sebastian Redla19a67f2010-08-03 21:58:15 +00003041 // Create the on-disk hash table representation. We walk through every
3042 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003043 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003044 for (auto &SelectorAndID : SelectorIDs) {
3045 Selector S = SelectorAndID.first;
3046 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003047 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003048 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003049 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003050 ObjCMethodList(),
3051 ObjCMethodList()
3052 };
3053 if (F != SemaRef.MethodPool.end()) {
3054 Data.Instance = F->second.first;
3055 Data.Factory = F->second.second;
3056 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003057 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003058 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003059 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003060 // Selector already exists. Did it change?
3061 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003062 for (ObjCMethodList *M = &Data.Instance;
3063 !changed && M && M->getMethod(); M = M->getNext()) {
3064 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003065 changed = true;
3066 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003067 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003068 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003069 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003070 changed = true;
3071 }
3072 if (!changed)
3073 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003074 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003075 // A new method pool entry.
3076 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003077 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003078 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003079 }
3080
Douglas Gregorc78d3462009-04-24 21:10:55 +00003081 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003082 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003083 uint32_t BucketOffset;
3084 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003085 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003086
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003087 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003088 llvm::raw_svector_ostream Out(MethodPool);
3089 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003090 endian::write<uint32_t>(Out, 0, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003091 BucketOffset = Generator.Emit(Out, Trait);
3092 }
3093
3094 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003095 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003096 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003097 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003098 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003099 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003100 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003101
Douglas Gregor95c13f52009-04-25 17:48:32 +00003102 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003103 {
3104 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3105 NumTableEntries};
3106 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3107 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003108
3109 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003110 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003111 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003113 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003114 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003115 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003116
3117 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003118 {
3119 RecordData::value_type Record[] = {
3120 SELECTOR_OFFSETS, SelectorOffsets.size(),
3121 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3122 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3123 bytes(SelectorOffsets));
3124 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003125 }
3126}
3127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003128/// Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003129void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003130 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003131
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003132 if (SemaRef.ReferencedSelectors.empty())
3133 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003134
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003135 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003136 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003137
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003138 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003139 // very tricky to fix, and given that @selector shouldn't really appear in
3140 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003141 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3142 Selector Sel = SelectorAndLocation.first;
3143 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003144 Writer.AddSelectorRef(Sel);
3145 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003146 }
Richard Smithe64e7452016-04-18 21:54:58 +00003147 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003148}
3149
Douglas Gregorc5046832009-04-27 18:38:38 +00003150//===----------------------------------------------------------------------===//
3151// Identifier Table Serialization
3152//===----------------------------------------------------------------------===//
3153
Richard Smithb3761912015-02-05 23:08:52 +00003154/// Determine the declaration that should be put into the name lookup table to
3155/// represent the given declaration in this module. This is usually D itself,
3156/// but if D was imported and merged into a local declaration, we want the most
3157/// recent local declaration instead. The chosen declaration will be the most
3158/// recent declaration in any module that imports this one.
3159static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3160 NamedDecl *D) {
3161 if (!LangOpts.Modules || !D->isFromASTFile())
3162 return D;
3163
3164 if (Decl *Redecl = D->getPreviousDecl()) {
3165 // For Redeclarable decls, a prior declaration might be local.
3166 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003167 // If we find a local decl, we're done.
3168 if (!Redecl->isFromASTFile()) {
3169 // Exception: in very rare cases (for injected-class-names), not all
3170 // redeclarations are in the same semantic context. Skip ones in a
3171 // different context. They don't go in this lookup table at all.
3172 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3173 D->getDeclContext()->getRedeclContext()))
3174 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003175 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003176 }
3177
Richard Smithfe620d22015-03-05 23:24:12 +00003178 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003179 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003180 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003181 break;
3182 }
3183 } else if (Decl *First = D->getCanonicalDecl()) {
3184 // For Mergeable decls, the first decl might be local.
3185 if (!First->isFromASTFile())
3186 return cast<NamedDecl>(First);
3187 }
3188
3189 // All declarations are imported. Our most recent declaration will also be
3190 // the most recent one in anyone who imports us.
3191 return D;
3192}
3193
Douglas Gregorc78d3462009-04-24 21:10:55 +00003194namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003195
Richard Smithcf97cf62015-04-19 01:34:23 +00003196class ASTIdentifierTableTrait {
3197 ASTWriter &Writer;
3198 Preprocessor &PP;
3199 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003200 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003201 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003202 ASTWriter::RecordData *InterestingIdentifierOffsets;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003204 /// Determines whether this is an "interesting" identifier that needs a
Richard Smithcf97cf62015-04-19 01:34:23 +00003205 /// full IdentifierInfo structure written into the hash table. Notably, this
3206 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3207 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003208 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003209 if (MacroOffset ||
3210 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003211 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003212 II->hasRevertedTokenIDToIdentifier() ||
Bruno Ricci366ba732018-09-21 12:53:22 +00003213 (NeedDecls && II->getFETokenInfo()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003214 return true;
3215
3216 return false;
3217 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003218
Douglas Gregore84a9da2009-04-20 20:36:09 +00003219public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003220 using key_type = IdentifierInfo *;
3221 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003222
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003223 using data_type = IdentID;
3224 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003225
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003226 using hash_value_type = unsigned;
3227 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003228
Richard Smithd7329392015-04-21 21:46:32 +00003229 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003230 IdentifierResolver &IdResolver, bool IsModule,
3231 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003232 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003233 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3234 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003235
Richard Smithd79514e2016-02-05 19:03:40 +00003236 bool needDecls() const { return NeedDecls; }
3237
Justin Bogner25463f12014-04-18 20:27:24 +00003238 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003239 return llvm::djbHash(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Richard Smith33e0f7e2015-07-22 02:08:40 +00003242 bool isInterestingIdentifier(const IdentifierInfo *II) {
3243 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3244 return isInterestingIdentifier(II, MacroOffset);
3245 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003246
Richard Smith9c254182015-07-19 21:41:12 +00003247 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3248 return isInterestingIdentifier(II, 0);
3249 }
3250
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003251 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003252 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003253 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003254 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003255 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3256 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003257 DataLen += 2; // 2 bytes for builtin ID
3258 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003259 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003260 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003261
Richard Smitha534a312015-07-21 23:54:07 +00003262 if (NeedDecls) {
3263 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3264 DEnd = IdResolver.end();
3265 D != DEnd; ++D)
3266 DataLen += 4;
3267 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003268 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003269
Justin Bognere1c147c2014-03-28 22:03:19 +00003270 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003271
Peter Collingbournee3f65292018-05-18 19:46:24 +00003272 endian::Writer LE(Out, little);
Justin Bognere1c147c2014-03-28 22:03:19 +00003273
Richard Smithdf8a8312015-03-13 04:05:01 +00003274 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003275 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003276 // We emit the key length after the data length so that every
3277 // string is preceded by a 16-bit length. This matches the PTH
3278 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003279 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003280 return std::make_pair(KeyLen, DataLen);
3281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003283 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003284 unsigned KeyLen) {
3285 // Record the location of the key data. This is used when generating
3286 // the mapping from persistent IDs to strings.
3287 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003288
3289 // Emit the offset of the key/data length information to the interesting
3290 // identifiers table if necessary.
3291 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3292 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3293
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003294 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003295 }
Mike Stump11289f42009-09-09 15:08:12 +00003296
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003297 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003298 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003299 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003300
Peter Collingbournee3f65292018-05-18 19:46:24 +00003301 endian::Writer LE(Out, little);
Richard Smithcf97cf62015-04-19 01:34:23 +00003302
Richard Smithd7329392015-04-21 21:46:32 +00003303 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3304 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003305 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003306 return;
3307 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003308
Justin Bognere1c147c2014-03-28 22:03:19 +00003309 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003310 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3311 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003312 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003313 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003314 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003315 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003316 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3317 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003318 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003319 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003320 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003321 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003322
Richard Smithd7329392015-04-21 21:46:32 +00003323 if (HadMacroDefinition)
3324 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003325
Richard Smitha534a312015-07-21 23:54:07 +00003326 if (NeedDecls) {
3327 // Emit the declaration IDs in reverse order, because the
3328 // IdentifierResolver provides the declarations as they would be
3329 // visible (e.g., the function "stat" would come before the struct
3330 // "stat"), but the ASTReader adds declarations to the end of the list
3331 // (so we need to see the struct "stat" before the function "stat").
3332 // Only emit declarations that aren't from a chained PCH, though.
3333 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3334 IdResolver.end());
3335 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3336 DEnd = Decls.rend();
3337 D != DEnd; ++D)
3338 LE.write<uint32_t>(
3339 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3340 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003341 }
3342};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003343
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003344} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003345
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003346/// Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003347///
3348/// The identifier table consists of a blob containing string data
3349/// (the actual identifiers themselves) and a separate "offsets" index
3350/// that maps identifier IDs to locations within the blob.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003351void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003352 IdentifierResolver &IdResolver,
3353 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003354 using namespace llvm;
3355
Richard Smith33e0f7e2015-07-22 02:08:40 +00003356 RecordData InterestingIdents;
3357
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003358 // Create and write out the blob that contains the identifier
3359 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003360 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003361 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003362 ASTIdentifierTableTrait Trait(
3363 *this, PP, IdResolver, IsModule,
3364 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003365
Douglas Gregore6648fb2009-04-28 20:33:11 +00003366 // Look for any identifiers that were named while processing the
3367 // headers, but are otherwise not needed. We add these to the hash
3368 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003369 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003370 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003371 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003372 for (const auto &ID : PP.getIdentifierTable())
3373 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003374 // Sort the identifiers lexicographically before getting them references so
3375 // that their order is stable.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00003376 llvm::sort(IIs, llvm::deref<std::less<>>());
Chandler Carruth8440c982015-03-26 23:54:15 +00003377 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003378 if (Trait.isInterestingNonMacroIdentifier(II))
3379 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003380
Sebastian Redlff4a2952010-07-23 23:49:55 +00003381 // Create the on-disk hash table representation. We only store offsets
3382 // for identifiers that appear here for the first time.
3383 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003384 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003385 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003386 IdentID ID = IdentIDPair.second;
3387 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003388 // Write out identifiers if either the ID is local or the identifier has
3389 // changed since it was loaded.
3390 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3391 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003392 (Trait.needDecls() &&
3393 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003394 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003395 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003396
Douglas Gregore84a9da2009-04-20 20:36:09 +00003397 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003398 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003399 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003400 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003401 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003402
Douglas Gregore84a9da2009-04-20 20:36:09 +00003403 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003404 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003405 endian::write<uint32_t>(Out, 0, little);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003406 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003407 }
3408
3409 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003410 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003411 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003413 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003414 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003415
3416 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003417 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003418 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003419 }
3420
3421 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003422 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003423 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003427 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003428
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003429#ifndef NDEBUG
3430 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3431 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3432#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003433
3434 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3435 IdentifierOffsets.size(),
3436 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003437 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003438 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003439
3440 // In C++, write the list of interesting identifiers (those that are
3441 // defined as macros, poisoned, or similar unusual things).
3442 if (!InterestingIdents.empty())
3443 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003444}
3445
Douglas Gregorc5046832009-04-27 18:38:38 +00003446//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003447// DeclContext's Name Lookup Table Serialization
3448//===----------------------------------------------------------------------===//
3449
3450namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003451
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003452// Trait used for the on-disk hash table used in the method pool.
3453class ASTDeclContextNameLookupTrait {
3454 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003455 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003456
3457public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003458 using key_type = DeclarationNameKey;
3459 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003460
Richard Smithd88a7f12015-09-01 20:35:42 +00003461 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003462 using data_type = std::pair<unsigned, unsigned>;
3463 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003464
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003465 using hash_value_type = unsigned;
3466 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003467
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003468 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003469
Richard Smithd88a7f12015-09-01 20:35:42 +00003470 template<typename Coll>
3471 data_type getData(const Coll &Decls) {
3472 unsigned Start = DeclIDs.size();
3473 for (NamedDecl *D : Decls) {
3474 DeclIDs.push_back(
3475 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3476 }
3477 return std::make_pair(Start, DeclIDs.size());
3478 }
3479
3480 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3481 unsigned Start = DeclIDs.size();
3482 for (auto ID : FromReader)
3483 DeclIDs.push_back(ID);
3484 return std::make_pair(Start, DeclIDs.size());
3485 }
3486
3487 static bool EqualKey(key_type_ref a, key_type_ref b) {
3488 return a == b;
3489 }
3490
Richard Smitha06c7e62015-08-26 23:55:49 +00003491 hash_value_type ComputeHash(DeclarationNameKey Name) {
3492 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003493 }
3494
Richard Smithd88a7f12015-09-01 20:35:42 +00003495 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3496 assert(Writer.hasChain() &&
3497 "have reference to loaded module file but no chain?");
3498
3499 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003500
Peter Collingbournee3f65292018-05-18 19:46:24 +00003501 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
Richard Smithd88a7f12015-09-01 20:35:42 +00003502 }
3503
Richard Smitha06c7e62015-08-26 23:55:49 +00003504 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3505 DeclarationNameKey Name,
3506 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003507 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003508
Peter Collingbournee3f65292018-05-18 19:46:24 +00003509 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003510 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003511 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003512 case DeclarationName::Identifier:
3513 case DeclarationName::ObjCZeroArgSelector:
3514 case DeclarationName::ObjCOneArgSelector:
3515 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003516 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003517 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003518 KeyLen += 4;
3519 break;
3520 case DeclarationName::CXXOperatorName:
3521 KeyLen += 1;
3522 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003523 case DeclarationName::CXXConstructorName:
3524 case DeclarationName::CXXDestructorName:
3525 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003526 case DeclarationName::CXXUsingDirective:
3527 break;
3528 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003529 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003530
Richard Smithf02662d2015-07-30 03:17:16 +00003531 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003532 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3533 assert(uint16_t(DataLen) == DataLen &&
3534 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003535 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003536
3537 return std::make_pair(KeyLen, DataLen);
3538 }
3539
Richard Smitha06c7e62015-08-26 23:55:49 +00003540 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003541 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003542
Peter Collingbournee3f65292018-05-18 19:46:24 +00003543 endian::Writer LE(Out, little);
Richard Smitha06c7e62015-08-26 23:55:49 +00003544 LE.write<uint8_t>(Name.getKind());
3545 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003546 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003547 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003548 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003549 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003550 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003551 case DeclarationName::ObjCZeroArgSelector:
3552 case DeclarationName::ObjCOneArgSelector:
3553 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003554 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003555 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003556 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003557 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003558 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003559 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003560 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003561 case DeclarationName::CXXConstructorName:
3562 case DeclarationName::CXXDestructorName:
3563 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003564 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003565 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003566 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003567
3568 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003569 }
3570
Richard Smitha06c7e62015-08-26 23:55:49 +00003571 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3572 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003573 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003574
Peter Collingbournee3f65292018-05-18 19:46:24 +00003575 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003576 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003577 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3578 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003579 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3580 }
3581};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003582
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003583} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003584
Chandler Carruthe972c362015-03-26 03:11:40 +00003585bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3586 DeclContext *DC) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003587 return Result.hasExternalDecls() &&
3588 DC->hasNeedToReconcileExternalVisibleStorage();
Chandler Carruthe972c362015-03-26 03:11:40 +00003589}
3590
3591bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3592 DeclContext *DC) {
3593 for (auto *D : Result.getLookupResult())
3594 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3595 return false;
3596
3597 return true;
3598}
3599
Richard Smithd88a7f12015-09-01 20:35:42 +00003600void
Chandler Carruthe972c362015-03-26 03:11:40 +00003601ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003602 llvm::SmallVectorImpl<char> &LookupTable) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003603 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3604 !ConstDC->hasLazyExternalLexicalLookups() &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003605 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003606
Chandler Carruthe972c362015-03-26 03:11:40 +00003607 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003608 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003609 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3610
3611 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003612 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3613 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003614 ASTDeclContextNameLookupTrait Trait(*this);
3615
Chandler Carruthe972c362015-03-26 03:11:40 +00003616 // The first step is to collect the declaration names which we need to
3617 // serialize into the name lookup table, and to collect them in a stable
3618 // order.
3619 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003620
Chandler Carruthe972c362015-03-26 03:11:40 +00003621 // We also build up small sets of the constructor and conversion function
3622 // names which are visible.
3623 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003624
Chandler Carruthe972c362015-03-26 03:11:40 +00003625 for (auto &Lookup : *DC->buildLookup()) {
3626 auto &Name = Lookup.first;
3627 auto &Result = Lookup.second;
3628
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003629 // If there are no local declarations in our lookup result, we
3630 // don't need to write an entry for the name at all. If we can't
3631 // write out a lookup set without performing more deserialization,
3632 // just skip this entry.
3633 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003634 isLookupResultEntirelyExternal(Result, DC))
3635 continue;
3636
3637 // We also skip empty results. If any of the results could be external and
3638 // the currently available results are empty, then all of the results are
3639 // external and we skip it above. So the only way we get here with an empty
3640 // results is when no results could have been external *and* we have
3641 // external results.
3642 //
3643 // FIXME: While we might want to start emitting on-disk entries for negative
3644 // lookups into a decl context as an optimization, today we *have* to skip
3645 // them because there are names with empty lookup results in decl contexts
3646 // which we can't emit in any stable ordering: we lookup constructors and
3647 // conversion functions in the enclosing namespace scope creating empty
3648 // results for them. This in almost certainly a bug in Clang's name lookup,
3649 // but that is likely to be hard or impossible to fix and so we tolerate it
3650 // here by omitting lookups with empty results.
3651 if (Lookup.second.getLookupResult().empty())
3652 continue;
3653
3654 switch (Lookup.first.getNameKind()) {
3655 default:
3656 Names.push_back(Lookup.first);
3657 break;
3658
Richard Smithcd45dbc2014-04-19 03:48:30 +00003659 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003660 assert(isa<CXXRecordDecl>(DC) &&
3661 "Cannot have a constructor name outside of a class!");
3662 ConstructorNameSet.insert(Name);
3663 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003664
3665 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003666 assert(isa<CXXRecordDecl>(DC) &&
3667 "Cannot have a conversion function name outside of a class!");
3668 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003669 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003670 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003671 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003672
Chandler Carruthe972c362015-03-26 03:11:40 +00003673 // Sort the names into a stable order.
Fangrui Song55fab262018-09-26 22:16:28 +00003674 llvm::sort(Names);
Chandler Carruthe972c362015-03-26 03:11:40 +00003675
Chandler Carruthffbf7052015-03-26 22:27:09 +00003676 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003677 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003678 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003679
Chandler Carruthffbf7052015-03-26 22:27:09 +00003680 // First we try the easy case by forming the current context's constructor
3681 // name and adding that name first. This is a very useful optimization to
3682 // avoid walking the lexical declarations in many cases, and it also
3683 // handles the only case where a constructor name can come from some other
3684 // lexical context -- when that name is an implicit constructor merged from
3685 // another declaration in the redecl chain. Any non-implicit constructor or
3686 // conversion function which doesn't occur in all the lexical contexts
3687 // would be an ODR violation.
3688 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3689 Context->getCanonicalType(Context->getRecordType(D)));
3690 if (ConstructorNameSet.erase(ImplicitCtorName))
3691 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003692
Chandler Carruthffbf7052015-03-26 22:27:09 +00003693 // If we still have constructors or conversion functions, we walk all the
3694 // names in the decl and add the constructors and conversion functions
3695 // which are visible in the order they lexically occur within the context.
3696 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3697 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3698 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3699 auto Name = ChildND->getDeclName();
3700 switch (Name.getNameKind()) {
3701 default:
3702 continue;
3703
3704 case DeclarationName::CXXConstructorName:
3705 if (ConstructorNameSet.erase(Name))
3706 Names.push_back(Name);
3707 break;
3708
3709 case DeclarationName::CXXConversionFunctionName:
3710 if (ConversionNameSet.erase(Name))
3711 Names.push_back(Name);
3712 break;
3713 }
3714
3715 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3716 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003717 }
3718
Chandler Carruthe972c362015-03-26 03:11:40 +00003719 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3720 "constructors by walking all the "
3721 "lexical members of the context.");
3722 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3723 "conversion functions by walking all "
3724 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003725 }
3726
Chandler Carruthe972c362015-03-26 03:11:40 +00003727 // Next we need to do a lookup with each name into this decl context to fully
3728 // populate any results from external sources. We don't actually use the
3729 // results of these lookups because we only want to use the results after all
3730 // results have been loaded and the pointers into them will be stable.
3731 for (auto &Name : Names)
3732 DC->lookup(Name);
3733
3734 // Now we need to insert the results for each name into the hash table. For
3735 // constructor names and conversion function names, we actually need to merge
3736 // all of the results for them into one list of results each and insert
3737 // those.
3738 SmallVector<NamedDecl *, 8> ConstructorDecls;
3739 SmallVector<NamedDecl *, 8> ConversionDecls;
3740
3741 // Now loop over the names, either inserting them or appending for the two
3742 // special cases.
3743 for (auto &Name : Names) {
3744 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3745
3746 switch (Name.getNameKind()) {
3747 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003748 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003749 break;
3750
3751 case DeclarationName::CXXConstructorName:
3752 ConstructorDecls.append(Result.begin(), Result.end());
3753 break;
3754
3755 case DeclarationName::CXXConversionFunctionName:
3756 ConversionDecls.append(Result.begin(), Result.end());
3757 break;
3758 }
3759 }
3760
3761 // Handle our two special cases if we ended up having any. We arbitrarily use
3762 // the first declaration's name here because the name itself isn't part of
3763 // the key, only the kind of name is used.
3764 if (!ConstructorDecls.empty())
3765 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003766 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003767 if (!ConversionDecls.empty())
3768 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003769 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003770
Richard Smithd88a7f12015-09-01 20:35:42 +00003771 // Create the on-disk hash table. Also emit the existing imported and
3772 // merged table if there is one.
3773 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3774 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003775}
3776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003777/// Write the block containing all of the declaration IDs
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003778/// visible from the given DeclContext.
3779///
3780/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003781/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003782uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3783 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003784 // If we imported a key declaration of this namespace, write the visible
3785 // lookup results as an update record for it rather than including them
3786 // on this declaration. We will only look at key declarations on reload.
3787 if (isa<NamespaceDecl>(DC) && Chain &&
3788 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3789 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003790 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003791 Prev = Prev->getPreviousDecl())
3792 if (!Prev->isFromASTFile())
3793 return 0;
3794
3795 // Note that we need to emit an update record for the primary context.
3796 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3797
3798 // Make sure all visible decls are written. They will be recorded later. We
3799 // do this using a side data structure so we can sort the names into
3800 // a deterministic order.
3801 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3802 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3803 LookupResults;
3804 if (Map) {
3805 LookupResults.reserve(Map->size());
3806 for (auto &Entry : *Map)
3807 LookupResults.push_back(
3808 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3809 }
3810
Fangrui Song55fab262018-09-26 22:16:28 +00003811 llvm::sort(LookupResults, llvm::less_first());
Richard Smith5fc18a92015-07-12 23:43:21 +00003812 for (auto &NameAndResult : LookupResults) {
3813 DeclarationName Name = NameAndResult.first;
3814 DeclContext::lookup_result Result = NameAndResult.second;
3815 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3816 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3817 // We have to work around a name lookup bug here where negative lookup
3818 // results for these names get cached in namespace lookup tables (these
3819 // names should never be looked up in a namespace).
3820 assert(Result.empty() && "Cannot have a constructor or conversion "
3821 "function name in a namespace!");
3822 continue;
3823 }
3824
3825 for (NamedDecl *ND : Result)
3826 if (!ND->isFromASTFile())
3827 GetDeclRef(ND);
3828 }
3829
3830 return 0;
3831 }
3832
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003833 if (DC->getPrimaryContext() != DC)
3834 return 0;
3835
Chandler Carruthe972c362015-03-26 03:11:40 +00003836 // Skip contexts which don't support name lookup.
3837 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003838 return 0;
3839
3840 // If not in C++, we perform name lookup for the translation unit via the
3841 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003842 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003843 return 0;
3844
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003845 // Serialize the contents of the mapping used for lookup. Note that,
3846 // although we have two very different code paths, the serialized
3847 // representation is the same for both cases: a declaration name,
3848 // followed by a size, followed by references to the visible
3849 // declarations that have that name.
3850 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003851 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003852 if (!Map || Map->empty())
3853 return 0;
3854
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003855 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003856 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003857 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003858
3859 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003860 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003861 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003862 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003863 ++NumVisibleDeclContexts;
3864 return Offset;
3865}
3866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003867/// Write an UPDATE_VISIBLE block for the given context.
Sebastian Redla4071b42010-08-24 00:50:09 +00003868///
3869/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3870/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003871/// (in C++), for namespaces, and for classes with forward-declared unscoped
3872/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003873void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003874 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003875 if (!Map || Map->empty())
3876 return;
3877
Sebastian Redla4071b42010-08-24 00:50:09 +00003878 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003879 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003880 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003881
Richard Smith5fc18a92015-07-12 23:43:21 +00003882 // If we're updating a namespace, select a key declaration as the key for the
3883 // update record; those are the only ones that will be checked on reload.
3884 if (isa<NamespaceDecl>(DC))
3885 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3886
Sebastian Redla4071b42010-08-24 00:50:09 +00003887 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003888 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003889 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003890}
3891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003892/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003893void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Adam Nemet484aa452017-03-27 19:17:25 +00003894 RecordData::value_type Record[] = {Opts.getInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003895 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3896}
3897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003898/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003899void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003900 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003901 return;
3902
3903 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3904 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00003905 for (const auto &I:Opts.OptMap) {
3906 AddString(I.getKey(), Record);
3907 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00003908 Record.push_back(V.Supported ? 1 : 0);
3909 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00003910 Record.push_back(V.Avail);
3911 Record.push_back(V.Core);
3912 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003913 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3914}
3915
Yaxun Liu5b746652016-12-18 05:18:55 +00003916void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3917 if (!SemaRef.Context.getLangOpts().OpenCL)
3918 return;
3919
Bruno Ricci2751b692019-04-18 15:13:27 +00003920 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3921 // without copying them.
3922 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3923 SemaRef.OpenCLTypeExtMap;
3924 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3925 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3926 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3927
3928 for (const auto &I : OpenCLTypeExtMap)
3929 StableOpenCLTypeExtMap.emplace_back(
3930 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
3931
3932 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3933 return E1.first < E2.first;
3934 };
3935 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
3936
Yaxun Liu5b746652016-12-18 05:18:55 +00003937 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003938 for (const ElementTy &E : StableOpenCLTypeExtMap) {
3939 Record.push_back(E.first); // TypeID
3940 const std::set<std::string> *ExtSet = E.second;
3941 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3942 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003943 AddString(Ext, Record);
3944 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003945
Yaxun Liu5b746652016-12-18 05:18:55 +00003946 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3947}
3948
3949void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3950 if (!SemaRef.Context.getLangOpts().OpenCL)
3951 return;
3952
Bruno Ricci2751b692019-04-18 15:13:27 +00003953 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
3954 // without copying them.
3955 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
3956 SemaRef.OpenCLDeclExtMap;
3957 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
3958 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
3959 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
3960
3961 for (const auto &I : OpenCLDeclExtMap)
3962 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
3963
3964 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3965 return E1.first < E2.first;
3966 };
3967 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
3968
Yaxun Liu5b746652016-12-18 05:18:55 +00003969 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003970 for (const ElementTy &E : StableOpenCLDeclExtMap) {
3971 Record.push_back(E.first); // DeclID
3972 const std::set<std::string> *ExtSet = E.second;
3973 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3974 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003975 AddString(Ext, Record);
3976 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003977
Yaxun Liu5b746652016-12-18 05:18:55 +00003978 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
3979}
3980
Justin Lebar67a78a62016-10-08 22:15:58 +00003981void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3982 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3983 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3984 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
3985 }
3986}
3987
Douglas Gregor404cdde2012-01-27 01:47:08 +00003988void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003989 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003990 RecordData Categories;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003991
Douglas Gregor404cdde2012-01-27 01:47:08 +00003992 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3993 unsigned Size = 0;
3994 unsigned StartIndex = Categories.size();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003995
Douglas Gregor404cdde2012-01-27 01:47:08 +00003996 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003997
Douglas Gregor404cdde2012-01-27 01:47:08 +00003998 // Allocate space for the size.
3999 Categories.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004000
Douglas Gregor404cdde2012-01-27 01:47:08 +00004001 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004002 for (ObjCInterfaceDecl::known_categories_iterator
4003 Cat = Class->known_categories_begin(),
4004 CatEnd = Class->known_categories_end();
4005 Cat != CatEnd; ++Cat, ++Size) {
4006 assert(getDeclID(*Cat) != 0 && "Bogus category");
4007 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004008 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004009
Douglas Gregor404cdde2012-01-27 01:47:08 +00004010 // Update the size.
4011 Categories[StartIndex] = Size;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004012
Douglas Gregor404cdde2012-01-27 01:47:08 +00004013 // Record this interface -> category map.
4014 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4015 CategoriesMap.push_back(CatInfo);
4016 }
4017
4018 // Sort the categories map by the definition ID, since the reader will be
4019 // performing binary searches on this information.
4020 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4021
4022 // Emit the categories map.
4023 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004024
David Blaikieb44f0bf2017-01-04 22:36:43 +00004025 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004026 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4027 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4028 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004029 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004030
4031 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4032 Stream.EmitRecordWithBlob(AbbrevID, Record,
4033 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004034 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004035
Douglas Gregor404cdde2012-01-27 01:47:08 +00004036 // Emit the category lists.
4037 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4038}
4039
Richard Smithe40f2ba2013-08-07 21:41:30 +00004040void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4041 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4042
4043 if (LPTMap.empty())
4044 return;
4045
4046 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004047 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004048 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004049 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004050 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004051 AddDeclRef(LPT.D, Record);
4052 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004053
Justin Lebar28f09c52016-10-10 16:26:08 +00004054 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004055 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004056 }
4057 }
4058 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4059}
4060
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004061/// Write the state of 'pragma clang optimize' at the end of the module.
Dario Domizioli13a0a382014-05-23 12:13:25 +00004062void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4063 RecordData Record;
4064 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4065 AddSourceLocation(PragmaLoc, Record);
4066 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4067}
4068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004069/// Write the state of 'pragma ms_struct' at the end of the module.
Nico Weber779355f2016-03-02 23:22:00 +00004070void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4071 RecordData Record;
4072 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4073 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4074}
4075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004076/// Write the state of 'pragma pointers_to_members' at the end of the
Nico Weber42932312016-03-03 00:17:35 +00004077//module.
4078void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4079 RecordData Record;
4080 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4081 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4082 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4083}
4084
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004085/// Write the state of 'pragma pack' at the end of the module.
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004086void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004087 // Don't serialize pragma pack state for modules, since it should only take
4088 // effect on a per-submodule basis.
4089 if (WritingModule)
4090 return;
4091
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004092 RecordData Record;
4093 Record.push_back(SemaRef.PackStack.CurrentValue);
4094 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4095 Record.push_back(SemaRef.PackStack.Stack.size());
4096 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4097 Record.push_back(StackEntry.Value);
4098 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004099 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004100 AddString(StackEntry.StackSlotLabel, Record);
4101 }
4102 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4103}
4104
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004105void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4106 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004107 // Enter the extension block.
4108 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4109
4110 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004111 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004112 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4113 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4114 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4115 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4116 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4117 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004118 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004119
4120 // Emit the metadata record.
4121 RecordData Record;
4122 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4123 Record.push_back(EXTENSION_METADATA);
4124 Record.push_back(Metadata.MajorVersion);
4125 Record.push_back(Metadata.MinorVersion);
4126 Record.push_back(Metadata.BlockName.size());
4127 Record.push_back(Metadata.UserInfo.size());
4128 SmallString<64> Buffer;
4129 Buffer += Metadata.BlockName;
4130 Buffer += Metadata.UserInfo;
4131 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4132
4133 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004134 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004135
4136 // Exit the extension block.
4137 Stream.ExitBlock();
4138}
4139
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004140//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004141// General Serialization Routines
4142//===----------------------------------------------------------------------===//
4143
Richard Smithe43e2b32018-08-20 21:47:29 +00004144void ASTRecordWriter::AddAttr(const Attr *A) {
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004145 auto &Record = *this;
Richard Smithe43e2b32018-08-20 21:47:29 +00004146 if (!A)
4147 return Record.push_back(0);
4148 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
Erich Keane6a24e802019-09-13 17:39:31 +00004149
4150 Record.AddIdentifierRef(A->getAttrName());
4151 Record.AddIdentifierRef(A->getScopeName());
Richard Smithe43e2b32018-08-20 21:47:29 +00004152 Record.AddSourceRange(A->getRange());
Erich Keane6a24e802019-09-13 17:39:31 +00004153 Record.AddSourceLocation(A->getScopeLoc());
4154 Record.push_back(A->getParsedKind());
4155 Record.push_back(A->getSyntax());
4156 Record.push_back(A->getAttributeSpellingListIndexRaw());
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004157
4158#include "clang/Serialization/AttrPCHWrite.inc"
Richard Smithe43e2b32018-08-20 21:47:29 +00004159}
4160
4161/// Emit the list of attributes to the specified record.
4162void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4163 push_back(Attrs.size());
4164 for (const auto *A : Attrs)
4165 AddAttr(A);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004166}
4167
John McCallf413f5e2013-05-03 00:10:13 +00004168void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4169 AddSourceLocation(Tok.getLocation(), Record);
4170 Record.push_back(Tok.getLength());
4171
4172 // FIXME: When reading literal tokens, reconstruct the literal pointer
4173 // if it is needed.
4174 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4175 // FIXME: Should translate token kind to a stable encoding.
4176 Record.push_back(Tok.getKind());
4177 // FIXME: Should translate token flags to a stable encoding.
4178 Record.push_back(Tok.getFlags());
4179}
4180
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004181void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004182 Record.push_back(Str.size());
4183 Record.insert(Record.end(), Str.begin(), Str.end());
4184}
4185
Richard Smith7ed1bc92014-12-05 22:42:13 +00004186bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004187 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004188
Richard Smith54cc3c22014-12-11 20:50:24 +00004189 bool Changed =
4190 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004191
4192 // Remove a prefix to make the path relative, if relevant.
4193 const char *PathBegin = Path.data();
4194 const char *PathPtr =
4195 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4196 if (PathPtr != PathBegin) {
4197 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4198 Changed = true;
4199 }
4200
4201 return Changed;
4202}
4203
4204void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4205 SmallString<128> FilePath(Path);
4206 PreparePathForOutput(FilePath);
4207 AddString(FilePath, Record);
4208}
4209
Mehdi Amini57a41912015-09-10 01:46:39 +00004210void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004211 StringRef Path) {
4212 SmallString<128> FilePath(Path);
4213 PreparePathForOutput(FilePath);
4214 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4215}
4216
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004217void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4218 RecordDataImpl &Record) {
4219 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004220 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004221 Record.push_back(*Minor + 1);
4222 else
4223 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004224 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004225 Record.push_back(*Subminor + 1);
4226 else
4227 Record.push_back(0);
4228}
4229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004230/// Note that the identifier II occurs at the given offset
Douglas Gregore84a9da2009-04-20 20:36:09 +00004231/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004232void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004233 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004234 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004235 // up earlier in the chain and thus don't need an offset.
4236 if (ID >= FirstIdentID)
4237 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004238}
4239
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004240/// Note that the selector Sel occurs at the given offset
Douglas Gregor95c13f52009-04-25 17:48:32 +00004241/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004242void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004243 unsigned ID = SelectorIDs[Sel];
4244 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004245 // Don't record offsets for selectors that are also available in a different
4246 // file.
4247 if (ID < FirstSelectorID)
4248 return;
4249 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004250}
4251
David Blaikie61137e12017-01-05 18:23:18 +00004252ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004253 SmallVectorImpl<char> &Buffer,
4254 InMemoryModuleCache &ModuleCache,
David Blaikie61137e12017-01-05 18:23:18 +00004255 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4256 bool IncludeTimestamps)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004257 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004258 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004259 for (const auto &Ext : Extensions) {
4260 if (auto Writer = Ext->createExtensionWriter(*this))
4261 ModuleFileExtensionWriters.push_back(std::move(Writer));
4262 }
4263}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004264
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004265ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004266 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004267}
4268
Richard Smithb3761912015-02-05 23:08:52 +00004269const LangOptions &ASTWriter::getLangOpts() const {
4270 assert(WritingAST && "can't determine lang opts when not writing AST");
4271 return Context->getLangOpts();
4272}
4273
Richard Smithe75ee0f2015-08-17 07:13:32 +00004274time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4275 return IncludeTimestamps ? E->getModificationTime() : 0;
4276}
4277
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004278ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4279 const std::string &OutputFile,
4280 Module *WritingModule, StringRef isysroot,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004281 bool hasErrors,
4282 bool ShouldCacheASTInMemory) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004283 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004284
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004285 ASTHasCompilerErrors = hasErrors;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004286
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004287 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004288 Stream.Emit((unsigned)'C', 8);
4289 Stream.Emit((unsigned)'P', 8);
4290 Stream.Emit((unsigned)'C', 8);
4291 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004292
Chris Lattner28fa4e62009-04-26 22:26:21 +00004293 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004294
Douglas Gregoreda8e122011-08-09 15:13:55 +00004295 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004296 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004297 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004298 ASTFileSignature Signature =
4299 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004300 Context = nullptr;
4301 PP = nullptr;
4302 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004303 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004304
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004305 WritingAST = false;
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004306 if (ShouldCacheASTInMemory) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004307 // Construct MemoryBuffer and update buffer manager.
Volodymyr Sapsai83f4c3a2020-01-16 17:12:41 -08004308 ModuleCache.addFinalPCM(OutputFile,
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004309 llvm::MemoryBuffer::getMemBufferCopy(
4310 StringRef(Buffer.begin(), Buffer.size())));
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004311 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004312 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004313}
4314
Douglas Gregora94a1542011-07-27 21:45:57 +00004315template<typename Vector>
4316static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4317 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004318 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4319 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004320 Writer.AddDeclRef(*I, Record);
4321 }
4322}
4323
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004324ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4325 const std::string &OutputFile,
4326 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004327 using namespace llvm;
4328
Craig Toppera13603a2014-05-22 05:54:18 +00004329 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004330
Douglas Gregorcf68c582011-12-01 22:20:10 +00004331 // Make sure that the AST reader knows to finalize itself.
4332 if (Chain)
4333 Chain->finalizeForWriting();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004334
Sebastian Redl143413f2010-07-12 22:02:52 +00004335 ASTContext &Context = SemaRef.Context;
4336 Preprocessor &PP = SemaRef.PP;
4337
Douglas Gregordab42432011-08-12 00:15:20 +00004338 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004339 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4340 if (D) {
4341 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4342 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004343 }
4344 };
4345 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4346 PREDEF_DECL_TRANSLATION_UNIT_ID);
4347 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4348 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4349 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4350 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4351 PREDEF_DECL_OBJC_PROTOCOL_ID);
4352 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4353 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4354 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4355 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4356 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004357 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004358 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4359 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004360 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004361 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4362 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004363 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4364 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004365 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4366 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004367 RegisterPredefDecl(Context.TypePackElementDecl,
4368 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004369
Chris Lattner0c797362009-09-08 18:19:27 +00004370 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004371 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004372 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004373 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004374 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004375
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004376 // Build a record containing all of the file scoped decls in this file.
4377 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004378 if (!isModule)
4379 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4380 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004381
Douglas Gregor851443c2011-08-12 01:39:19 +00004382 // Build a record containing all of the delegating constructors we still need
4383 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004384 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004385 if (!isModule)
4386 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004387
Douglas Gregor851443c2011-08-12 01:39:19 +00004388 // Write the set of weak, undeclared identifiers. We always write the
4389 // entire table, since later PCH files in a PCH chain are only interested in
4390 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004391 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004392 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4393 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4394 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4395 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4396 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4397 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4398 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004399 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004400
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004401 // Build a record containing all of the ext_vector declarations.
4402 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004403 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004404
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004405 // Build a record containing all of the VTable uses information.
4406 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004407 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004408 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4409 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4410 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4411 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4412 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004413 }
4414
Nico Weber72889432014-09-06 01:25:55 +00004415 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4416 RecordData UnusedLocalTypedefNameCandidates;
4417 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4418 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4419
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004420 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004421 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004422 for (const auto &I : SemaRef.PendingInstantiations) {
4423 AddDeclRef(I.first, PendingInstantiations);
4424 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004425 }
4426 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4427 "There are local ones at end of translation unit!");
4428
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004429 // Build a record containing some declaration references.
4430 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004431 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004432 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4433 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004434 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004435 }
4436
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004437 RecordData CUDASpecialDeclRefs;
4438 if (Context.getcudaConfigureCallDecl()) {
4439 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4440 }
4441
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004442 // Build a record containing all of the known namespaces.
4443 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004444 for (const auto &I : SemaRef.KnownNamespaces) {
4445 if (!I.second)
4446 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004447 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004448
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004449 // Build a record of all used, undefined objects that require definitions.
4450 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004451
4452 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004453 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004454 for (const auto &I : Undefined) {
4455 AddDeclRef(I.first, UndefinedButUsed);
4456 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004457 }
4458
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004459 // Build a record containing all delete-expressions that we would like to
4460 // analyze later in AST.
4461 RecordData DeleteExprsToAnalyze;
4462
Richard Smithf5262c62018-06-28 01:57:04 +00004463 if (!isModule) {
4464 for (const auto &DeleteExprsInfo :
4465 SemaRef.getMismatchingDeleteExpressions()) {
4466 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4467 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4468 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4469 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4470 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4471 }
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004472 }
4473 }
4474
Douglas Gregor112b9072012-10-18 05:31:06 +00004475 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004476 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004477
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004478 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004479 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004480
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004481 // This is so that older clang versions, before the introduction
4482 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004483 {
4484 RecordData Record = {VERSION_MAJOR};
4485 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4486 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004487
Douglas Gregor851443c2011-08-12 01:39:19 +00004488 // Create a lexical update block containing all of the declarations in the
4489 // translation unit that do not come from other AST files.
4490 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004491 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4492 for (const auto *D : TU->noload_decls()) {
4493 if (!D->isFromASTFile()) {
4494 NewGlobalKindDeclPairs.push_back(D->getKind());
4495 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4496 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004497 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004498
David Blaikieb44f0bf2017-01-04 22:36:43 +00004499 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004500 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4501 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004502 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004503 {
4504 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4505 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4506 bytes(NewGlobalKindDeclPairs));
4507 }
4508
Douglas Gregor851443c2011-08-12 01:39:19 +00004509 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004510 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004511 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4512 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004513 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004514 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004515 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004516
4517 // If we have any extern "C" names, write out a visible update for them.
4518 if (Context.ExternCContext)
4519 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004520
Douglas Gregor851443c2011-08-12 01:39:19 +00004521 // If the translation unit has an anonymous namespace, and we don't already
4522 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004523 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004524 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4525 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004526 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004527 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004528 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004529
Richard Smith5652c0f2014-03-21 01:48:23 +00004530 // Add update records for all mangling numbers and static local numbers.
4531 // These aren't really update records, but this is a convenient way of
4532 // tagging this rare extra data onto the declarations.
4533 for (const auto &Number : Context.MangleNumbers)
4534 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004535 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4536 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004537 for (const auto &Number : Context.StaticLocalNumbers)
4538 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004539 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4540 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004541
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004542 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004543 // an AST file, are registered for serialization. Likewise for template
4544 // specializations added to imported templates.
4545 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004546 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004547 }
4548
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004549 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004550 // serialization, if we're storing decls with identifiers.
4551 if (!WritingModule || !getLangOpts().CPlusPlus) {
4552 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004553 for (const auto &ID : PP.getIdentifierTable()) {
4554 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004555 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4556 IIs.push_back(II);
4557 }
4558 // Sort the identifiers to visit based on their name.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00004559 llvm::sort(IIs, llvm::deref<std::less<>>());
Richard Smith79bf9202015-08-24 03:33:22 +00004560 for (const IdentifierInfo *II : IIs) {
4561 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4562 DEnd = SemaRef.IdResolver.end();
4563 D != DEnd; ++D) {
4564 GetDeclRef(*D);
4565 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004566 }
4567 }
4568
Manman Rena0f31a02016-04-29 19:04:05 +00004569 // For method pool in the module, if it contains an entry for a selector,
4570 // the entry should be complete, containing everything introduced by that
4571 // module and all modules it imports. It's possible that the entry is out of
4572 // date, so we need to pull in the new content here.
4573
4574 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4575 // safe, we copy all selectors out.
4576 llvm::SmallVector<Selector, 256> AllSelectors;
4577 for (auto &SelectorAndID : SelectorIDs)
4578 AllSelectors.push_back(SelectorAndID.first);
4579 for (auto &Selector : AllSelectors)
4580 SemaRef.updateOutOfDateSelector(Selector);
4581
Douglas Gregor5204bde2011-08-02 16:26:37 +00004582 // Form the record of special types.
4583 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004584 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004585 AddTypeRef(Context.getFILEType(), SpecialTypes);
4586 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4587 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4588 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4589 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004590 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004591 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004592
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004593 if (Chain) {
4594 // Write the mapping information describing our module dependencies and how
4595 // each of those modules were mapped into our own offset/ID space, so that
4596 // the reader can build the appropriate mapping to its own offset/ID space.
4597 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004598 // *(module-kind:i8
4599 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004600 // source-location-offset:i32
4601 // identifier-id:i32
4602 // preprocessed-entity-id:i32
4603 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004604 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004605 // selector-id:i32
4606 // declaration-id:i32
4607 // c++-base-specifiers-id:i32
4608 // type-id:i32)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004609 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004610 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4611 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4612 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004613 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004614 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004616 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004617 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004618 {
4619 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004620 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004621 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004622
Peter Collingbournee3f65292018-05-18 19:46:24 +00004623 endian::Writer LE(Out, little);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004624 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4625 StringRef Name =
4626 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4627 ? M.ModuleName
4628 : M.FileName;
4629 LE.write<uint16_t>(Name.size());
4630 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004631
Ben Langmuir785180e2014-10-20 16:27:30 +00004632 // Note: if a base ID was uint max, it would not be possible to load
4633 // another module after it or have more than one entity inside it.
4634 uint32_t None = std::numeric_limits<uint32_t>::max();
4635
4636 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4637 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4638 if (ShouldWrite)
4639 LE.write<uint32_t>(BaseID);
4640 else
4641 LE.write<uint32_t>(None);
4642 };
4643
Ben Langmuirfe971d92014-08-16 04:54:18 +00004644 // These values should be unique within a chain, since they will be read
4645 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004646 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4647 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4648 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4649 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4650 M.NumPreprocessedEntities);
4651 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4652 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4653 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4654 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004655 }
4656 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004657 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004658 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4659 Buffer.data(), Buffer.size());
4660 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004661
Richard Smithb9eab6d2014-03-20 19:44:17 +00004662 RecordData DeclUpdatesOffsetsRecord;
4663
Richard Smith59442b42014-03-20 20:07:19 +00004664 // Keep writing types, declarations, and declaration update records
4665 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004666 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4667 WriteTypeAbbrevs();
4668 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004669 do {
4670 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4671 while (!DeclTypesToEmit.empty()) {
4672 DeclOrType DOT = DeclTypesToEmit.front();
4673 DeclTypesToEmit.pop();
4674 if (DOT.isType())
4675 WriteType(DOT.getType());
4676 else
4677 WriteDecl(Context, DOT.getDecl());
4678 }
4679 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004680 Stream.ExitBlock();
4681
Richard Smithb9eab6d2014-03-20 19:44:17 +00004682 DoneWritingDeclsAndTypes = true;
4683
4684 // These things can only be done once we've written out decls and types.
4685 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004686 if (!DeclUpdatesOffsetsRecord.empty())
4687 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004688 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004689 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004690 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004691 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004692 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004693 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004694 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004695 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004696 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004697 WriteFPPragmaOptions(SemaRef.getFPOptions());
4698 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004699 WriteOpenCLExtensionTypes(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004700 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004701
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004702 // If we're emitting a module, write out the submodule information.
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004703 if (WritingModule)
4704 WriteSubmodules(WritingModule);
4705
Andrew Savonichev52d674d2018-10-29 11:14:01 +00004706 // We need to have information about submodules to correctly deserialize
4707 // decls from OpenCLExtensionDecls block
4708 WriteOpenCLExtensionDecls(SemaRef);
4709
Douglas Gregor5204bde2011-08-02 16:26:37 +00004710 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4711
Douglas Gregord4df8652009-04-22 22:02:47 +00004712 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004713 if (!EagerlyDeserializedDecls.empty())
4714 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004715
David Blaikief63556d2017-04-12 20:58:33 +00004716 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004717 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4718
Douglas Gregord4df8652009-04-22 22:02:47 +00004719 // Write the record containing tentative definitions.
4720 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004721 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004722
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004723 // Write the record containing unused file scoped decls.
4724 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004725 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004726
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004727 // Write the record containing weak undeclared identifiers.
4728 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004729 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004730 WeakUndeclaredIdentifiers);
4731
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004732 // Write the record containing ext_vector type names.
4733 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004734 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004735
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004736 // Write the record containing VTable uses information.
4737 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004738 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004739
Nico Weber72889432014-09-06 01:25:55 +00004740 // Write the record containing potentially unused local typedefs.
4741 if (!UnusedLocalTypedefNameCandidates.empty())
4742 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4743 UnusedLocalTypedefNameCandidates);
4744
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004745 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004746 if (!PendingInstantiations.empty())
4747 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004748
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004749 // Write the record containing declaration references of Sema.
4750 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004751 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004752
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004753 // Write the record containing CUDA-specific declaration references.
4754 if (!CUDASpecialDeclRefs.empty())
4755 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004756
Alexis Hunt27a761d2011-05-04 23:29:54 +00004757 // Write the delegating constructors.
4758 if (!DelegatingCtorDecls.empty())
4759 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004760
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004761 // Write the known namespaces.
4762 if (!KnownNamespaces.empty())
4763 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004764
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004765 // Write the undefined internal functions and variables, and inline functions.
4766 if (!UndefinedButUsed.empty())
4767 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004768
4769 if (!DeleteExprsToAnalyze.empty())
4770 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4771
Douglas Gregor851443c2011-08-12 01:39:19 +00004772 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004773 for (auto *DC : UpdatedDeclContexts)
4774 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004775
Douglas Gregor959bb062011-12-03 01:15:29 +00004776 if (!WritingModule) {
4777 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004778 struct ModuleInfo {
4779 uint64_t ID;
4780 Module *M;
4781 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4782 };
Richard Smith56be7542014-03-21 00:33:59 +00004783 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004784 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004785 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004786 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4787 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004788 }
Richard Smith56be7542014-03-21 00:33:59 +00004789
4790 if (!Imports.empty()) {
4791 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4792 return A.ID < B.ID;
4793 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004794 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4795 return A.ID == B.ID;
4796 };
Richard Smith56be7542014-03-21 00:33:59 +00004797
4798 // Sort and deduplicate module IDs.
Fangrui Song55fab262018-09-26 22:16:28 +00004799 llvm::sort(Imports, Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004800 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004801 Imports.end());
4802
4803 RecordData ImportedModules;
4804 for (const auto &Import : Imports) {
4805 ImportedModules.push_back(Import.ID);
4806 // FIXME: If the module has macros imported then later has declarations
4807 // imported, this location won't be the right one as a location for the
4808 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004809 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004810 }
4811
Douglas Gregor959bb062011-12-03 01:15:29 +00004812 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4813 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004814 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004815
Douglas Gregor404cdde2012-01-27 01:47:08 +00004816 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004817 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004818 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004819 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004820 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004821 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004822 WritePackPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004823
Douglas Gregor08f01292009-04-17 22:13:46 +00004824 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004825 RecordData::value_type Record[] = {
4826 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004827 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004828 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004829
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004830 // Write the module file extension blocks.
4831 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004832 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004833
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004834 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004835}
4836
Richard Smithb9eab6d2014-03-20 19:44:17 +00004837void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004838 if (DeclUpdates.empty())
4839 return;
4840
Richard Smith59442b42014-03-20 20:07:19 +00004841 DeclUpdateMap LocalUpdates;
4842 LocalUpdates.swap(DeclUpdates);
4843
Richard Smith6ef42932014-03-20 21:02:00 +00004844 for (auto &DeclUpdate : LocalUpdates) {
4845 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004846
Richard Smithd28ac5b2014-03-22 23:33:22 +00004847 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004848 RecordData RecordData;
4849 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004850 for (auto &Update : DeclUpdate.second) {
4851 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4852
Richard Smith69c82bf2016-04-01 22:52:03 +00004853 // An updated body is emitted last, so that the reader doesn't need
4854 // to skip over the lazy body to reach statements for other records.
4855 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4856 HasUpdatedBody = true;
4857 else
4858 Record.push_back(Kind);
4859
Richard Smith6ef42932014-03-20 21:02:00 +00004860 switch (Kind) {
4861 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4862 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4863 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004864 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004865 Record.push_back(GetDeclRef(Update.getDecl()));
4866 break;
4867
Richard Smith4d235792014-08-07 18:53:08 +00004868 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004869 break;
4870
Richard Smith891fc7f2017-12-05 01:31:47 +00004871 case UPD_CXX_POINT_OF_INSTANTIATION:
4872 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00004873 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00004874 break;
4875
4876 case UPD_CXX_ADDED_VAR_DEFINITION: {
4877 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00004878 Record.push_back(VD->isInline());
4879 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00004880 if (VD->getInit()) {
4881 Record.push_back(!VD->isInitKnownICE() ? 1
4882 : (VD->isInitICE() ? 3 : 2));
4883 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4884 } else {
4885 Record.push_back(0);
4886 }
Richard Smith4d235792014-08-07 18:53:08 +00004887 break;
Richard Smith05a21352017-06-22 22:18:46 +00004888 }
Richard Smith4d235792014-08-07 18:53:08 +00004889
John McCall32791cc2016-01-06 22:34:54 +00004890 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004891 Record.AddStmt(const_cast<Expr *>(
4892 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004893 break;
4894
Richard Smith4b054b22016-08-24 21:25:37 +00004895 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4896 Record.AddStmt(
4897 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4898 break;
4899
Richard Smithcd45dbc2014-04-19 03:48:30 +00004900 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4901 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004902 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00004903 Record.push_back(RD->isParamDestroyedInCallee());
Akira Hatanakae6313ac2018-04-09 22:48:22 +00004904 Record.push_back(RD->getArgPassingRestrictions());
Richard Smith69c82bf2016-04-01 22:52:03 +00004905 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004906 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004907 *Context, const_cast<CXXRecordDecl *>(RD)));
4908
4909 // This state is sometimes updated by template instantiation, when we
4910 // switch from the specialization referring to the template declaration
4911 // to it referring to the template definition.
4912 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4913 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004914 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004915 } else {
4916 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4917 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004918 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004919
4920 // The instantiation might have been resolved to a partial
4921 // specialization. If so, record which one.
4922 auto From = Spec->getInstantiatedFrom();
4923 if (auto PartialSpec =
4924 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4925 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004926 Record.AddDeclRef(PartialSpec);
4927 Record.AddTemplateArgumentList(
4928 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004929 } else {
4930 Record.push_back(false);
4931 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004932 }
4933 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004934 Record.AddSourceLocation(RD->getLocation());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004935 Record.AddSourceLocation(RD->getBeginLoc());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004936 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004937
4938 // Instantiation may change attributes; write them all out afresh.
4939 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004940 if (D->hasAttrs())
4941 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004942
4943 // FIXME: Ensure we don't get here for explicit instantiations.
4944 break;
4945 }
4946
Richard Smithf8134002015-03-10 01:41:22 +00004947 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004948 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00004949 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00004950 break;
4951
John McCalld505e572019-12-13 21:54:44 -05004952 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4953 auto prototype =
4954 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
4955 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
Richard Smith564417a2014-03-20 21:47:22 +00004956 break;
John McCalld505e572019-12-13 21:54:44 -05004957 }
Richard Smith564417a2014-03-20 21:47:22 +00004958
Richard Smith6ef42932014-03-20 21:02:00 +00004959 case UPD_CXX_DEDUCED_RETURN_TYPE:
4960 Record.push_back(GetOrCreateTypeID(Update.getType()));
4961 break;
4962
4963 case UPD_DECL_MARKED_USED:
4964 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004965
4966 case UPD_MANGLING_NUMBER:
4967 case UPD_STATIC_LOCAL_NUMBER:
4968 Record.push_back(Update.getNumber());
4969 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004970
Alexey Bataev97720002014-11-11 04:05:39 +00004971 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004972 Record.AddSourceRange(
4973 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004974 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004975
Alexey Bataev27ef9512019-03-20 20:14:22 +00004976 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4977 auto *A = D->getAttr<OMPAllocateDeclAttr>();
4978 Record.push_back(A->getAllocatorType());
4979 Record.AddStmt(A->getAllocator());
4980 Record.AddSourceRange(A->getRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004981 break;
Alexey Bataev27ef9512019-03-20 20:14:22 +00004982 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004983
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004984 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
Alexey Bataevd01b7492018-08-15 19:45:12 +00004985 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004986 Record.AddSourceRange(
4987 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4988 break;
4989
Richard Smith65ebb4a2015-03-26 04:09:53 +00004990 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004991 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004992 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004993
4994 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004995 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004996 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004997 }
4998 }
4999
Richard Smithd28ac5b2014-03-22 23:33:22 +00005000 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005001 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005002 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005003 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005004 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005005 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005006 }
5007
Richard Smithcd45dbc2014-04-19 03:48:30 +00005008 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005009 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005010 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005011}
5012
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005013void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005014 uint32_t Raw = Loc.getRawEncoding();
5015 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005016}
5017
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005018void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005019 AddSourceLocation(Range.getBegin(), Record);
5020 AddSourceLocation(Range.getEnd(), Record);
5021}
5022
Richard Smithf144b542016-04-08 21:54:32 +00005023void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5024 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005025}
5026
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00005027static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5028 FixedPointSemantics FPSema) {
5029 Record.push_back(FPSema.getWidth());
5030 Record.push_back(FPSema.getScale());
5031 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5032 FPSema.hasUnsignedPadding() << 2);
5033}
5034
5035void ASTRecordWriter::AddAPValue(const APValue &Value) {
5036 APValue::ValueKind Kind = Value.getKind();
5037 push_back(static_cast<uint64_t>(Kind));
5038 switch (Kind) {
5039 case APValue::None:
5040 case APValue::Indeterminate:
5041 return;
5042 case APValue::Int:
5043 AddAPSInt(Value.getInt());
5044 return;
5045 case APValue::Float:
5046 push_back(static_cast<uint64_t>(
5047 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5048 AddAPFloat(Value.getFloat());
5049 return;
5050 case APValue::FixedPoint: {
5051 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5052 AddAPSInt(Value.getFixedPoint().getValue());
5053 return;
5054 }
5055 case APValue::ComplexInt: {
5056 AddAPSInt(Value.getComplexIntReal());
5057 AddAPSInt(Value.getComplexIntImag());
5058 return;
5059 }
5060 case APValue::ComplexFloat: {
5061 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5062 Value.getComplexFloatReal().getSemantics())));
5063 AddAPFloat(Value.getComplexFloatReal());
5064 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5065 Value.getComplexFloatImag().getSemantics())));
5066 AddAPFloat(Value.getComplexFloatImag());
5067 return;
5068 }
5069 case APValue::LValue:
5070 case APValue::Vector:
5071 case APValue::Array:
5072 case APValue::Struct:
5073 case APValue::Union:
5074 case APValue::MemberPointer:
5075 case APValue::AddrLabelDiff:
5076 // TODO : Handle all these APValue::ValueKind.
5077 return;
5078 }
5079 llvm_unreachable("Invalid APValue::ValueKind");
5080}
5081
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005082void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005083 Record.push_back(getIdentifierRef(II));
5084}
5085
Sebastian Redl539c5062010-08-18 23:57:32 +00005086IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005087 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005088 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005089
Sebastian Redl539c5062010-08-18 23:57:32 +00005090 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005091 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005092 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005093 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005094}
5095
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005096MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005097 // Don't emit builtin macros like __LINE__ to the AST file unless they
5098 // have been redefined by the header (in which case they are not
5099 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005100 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005101 return 0;
5102
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005103 MacroID &ID = MacroIDs[MI];
5104 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005105 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005106 MacroInfoToEmitData Info = { Name, MI, ID };
5107 MacroInfosToEmit.push_back(Info);
5108 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005109 return ID;
5110}
5111
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005112MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005113 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005114 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005115
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005116 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5117 return MacroIDs[MI];
5118}
5119
5120uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005121 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005122}
5123
Richard Smithe64e7452016-04-18 21:54:58 +00005124void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5125 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005126}
5127
Sebastian Redl539c5062010-08-18 23:57:32 +00005128SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005129 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005130 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005131 }
5132
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005133 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005134 if (SID == 0 && Chain) {
5135 // This might trigger a ReadSelector callback, which will set the ID for
5136 // this selector.
5137 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005138 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005139 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005140 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005141 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005142 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005143 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005144 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005145}
5146
Richard Smithe64e7452016-04-18 21:54:58 +00005147void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5148 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005149}
5150
Richard Smith290d8012016-04-06 17:06:00 +00005151void ASTRecordWriter::AddTemplateArgumentLocInfo(
5152 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005153 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005154 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005155 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005156 break;
5157 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005158 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005159 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005160 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005161 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5162 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005163 break;
5164 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005165 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5166 AddSourceLocation(Arg.getTemplateNameLoc());
5167 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005168 break;
John McCall0ad16662009-10-29 08:12:44 +00005169 case TemplateArgument::Null:
5170 case TemplateArgument::Integral:
5171 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005172 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005173 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005174 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005175 break;
5176 }
5177}
5178
Richard Smith290d8012016-04-06 17:06:00 +00005179void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5180 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005181
5182 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5183 bool InfoHasSameExpr
5184 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005185 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005186 if (InfoHasSameExpr)
5187 return; // Avoid storing the same expr twice.
5188 }
Richard Smith290d8012016-04-06 17:06:00 +00005189 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005190}
5191
Richard Smith290d8012016-04-06 17:06:00 +00005192void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005193 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005194 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005195 return;
5196 }
5197
Richard Smithc23d7342018-06-29 20:46:25 +00005198 AddTypeRef(TInfo->getType());
Richard Smith290d8012016-04-06 17:06:00 +00005199 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005200}
5201
Richard Smith290d8012016-04-06 17:06:00 +00005202void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
Richard Smith290d8012016-04-06 17:06:00 +00005203 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005204 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005205 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005206}
5207
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005208void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005209 Record.push_back(GetOrCreateTypeID(T));
5210}
5211
Richard Smith2095ffe2015-03-16 20:11:03 +00005212TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005213 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005214 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5215 if (T.isNull())
5216 return TypeIdx();
5217 assert(!T.getLocalFastQualifiers());
5218
5219 TypeIdx &Idx = TypeIdxs[T];
5220 if (Idx.getIndex() == 0) {
5221 if (DoneWritingDeclsAndTypes) {
5222 assert(0 && "New type seen after serializing all the types to emit!");
5223 return TypeIdx();
5224 }
5225
5226 // We haven't seen this type before. Assign it a new ID and put it
5227 // into the queue of types to emit.
5228 Idx = TypeIdx(NextTypeID++);
5229 DeclTypesToEmit.push(T);
5230 }
5231 return Idx;
5232 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005233}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005234
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005235TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005236 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005237 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5238 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005239 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005240 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005241
Richard Smith2095ffe2015-03-16 20:11:03 +00005242 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5243 assert(I != TypeIdxs.end() && "Type not emitted!");
5244 return I->second;
5245 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005246}
5247
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005248void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005249 Record.push_back(GetDeclRef(D));
5250}
5251
Sebastian Redl539c5062010-08-18 23:57:32 +00005252DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005253 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005254
5255 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005256 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005257 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005258
Douglas Gregorb3163e52012-01-05 22:33:30 +00005259 // If D comes from an AST file, its declaration ID is already known and
5260 // fixed.
5261 if (D->isFromASTFile())
5262 return D->getGlobalID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005263
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005264 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005265 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005266 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005267 if (DoneWritingDeclsAndTypes) {
5268 assert(0 && "New decl seen after serializing all the decls to emit!");
5269 return 0;
5270 }
5271
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005272 // We haven't seen this declaration before. Give it a new ID and
5273 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005274 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005275 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005276 }
5277
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005278 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005279}
5280
Sebastian Redl539c5062010-08-18 23:57:32 +00005281DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005282 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005283 return 0;
5284
Douglas Gregorb3163e52012-01-05 22:33:30 +00005285 // If D comes from an AST file, its declaration ID is already known and
5286 // fixed.
5287 if (D->isFromASTFile())
5288 return D->getGlobalID();
5289
Douglas Gregore84a9da2009-04-20 20:36:09 +00005290 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5291 return DeclIDs[D];
5292}
5293
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005294void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005295 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005296 assert(D);
5297
5298 SourceLocation Loc = D->getLocation();
5299 if (Loc.isInvalid())
5300 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005301
5302 // We only keep track of the file-level declarations of each file.
5303 if (!D->getLexicalDeclContext()->isFileContext())
5304 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005305 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5306 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005307 // TemplateTemplateParmDecls that are part of an alias template, should not
5308 // have TU as lexical context.
5309 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005310 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005311
5312 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005313 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005314 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005315 FileID FID;
5316 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005317 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005318 if (FID.isInvalid())
5319 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005320 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005321
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005322 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005323 if (!Info)
5324 Info = new DeclIDInFileInfo();
5325
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005326 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005327 LocDeclIDsTy &Decls = Info->DeclIDs;
5328
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005329 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005330 Decls.push_back(LocDecl);
5331 return;
5332 }
5333
Benjamin Kramer45025c02013-08-24 13:22:59 +00005334 LocDeclIDsTy::iterator I =
Fangrui Song7264a472019-07-03 08:13:17 +00005335 llvm::upper_bound(Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005336
5337 Decls.insert(I, LocDecl);
5338}
5339
Richard Smithd08aeb62014-08-28 01:33:39 +00005340unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5341 assert(needsAnonymousDeclarationNumber(D) &&
5342 "expected an anonymous declaration");
5343
5344 // Number the anonymous declarations within this context, if we've not
5345 // already done so.
5346 auto It = AnonymousDeclarationNumbers.find(D);
5347 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005348 auto *DC = D->getLexicalDeclContext();
5349 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5350 AnonymousDeclarationNumbers[ND] = Number;
5351 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005352
5353 It = AnonymousDeclarationNumbers.find(D);
5354 assert(It != AnonymousDeclarationNumbers.end() &&
5355 "declaration not found within its lexical context");
5356 }
5357
5358 return It->second;
5359}
5360
Richard Smith290d8012016-04-06 17:06:00 +00005361void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5362 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005363 switch (Name.getNameKind()) {
5364 case DeclarationName::CXXConstructorName:
5365 case DeclarationName::CXXDestructorName:
5366 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005367 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005368 break;
5369
5370 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005371 AddSourceLocation(SourceLocation::getFromRawEncoding(
5372 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005373 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005374 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005375 break;
5376
5377 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005378 AddSourceLocation(SourceLocation::getFromRawEncoding(
5379 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005380 break;
5381
5382 case DeclarationName::Identifier:
5383 case DeclarationName::ObjCZeroArgSelector:
5384 case DeclarationName::ObjCOneArgSelector:
5385 case DeclarationName::ObjCMultiArgSelector:
5386 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005387 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005388 break;
5389 }
5390}
5391
Richard Smith290d8012016-04-06 17:06:00 +00005392void ASTRecordWriter::AddDeclarationNameInfo(
5393 const DeclarationNameInfo &NameInfo) {
5394 AddDeclarationName(NameInfo.getName());
5395 AddSourceLocation(NameInfo.getLoc());
5396 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005397}
5398
Richard Smith290d8012016-04-06 17:06:00 +00005399void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5400 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5401 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005402 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005403 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005404}
5405
Richard Smith290d8012016-04-06 17:06:00 +00005406void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005407 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005408 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005409 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005410
5411 // Push each of the nested-name-specifiers's onto a stack for
5412 // serialization in reverse order.
5413 while (NNS) {
5414 NestedNames.push_back(NNS);
5415 NNS = NNS.getPrefix();
5416 }
5417
Richard Smith290d8012016-04-06 17:06:00 +00005418 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005419 while(!NestedNames.empty()) {
5420 NNS = NestedNames.pop_back_val();
5421 NestedNameSpecifier::SpecifierKind Kind
5422 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005423 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005424 switch (Kind) {
5425 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005426 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5427 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005428 break;
5429
5430 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005431 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5432 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005433 break;
5434
5435 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005436 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5437 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005438 break;
5439
5440 case NestedNameSpecifier::TypeSpec:
5441 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005442 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Richard Smithc23d7342018-06-29 20:46:25 +00005443 AddTypeRef(NNS.getTypeLoc().getType());
Richard Smith290d8012016-04-06 17:06:00 +00005444 AddTypeLoc(NNS.getTypeLoc());
5445 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005446 break;
5447
5448 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005449 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005450 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005451
5452 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005453 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5454 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005455 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005456 }
5457 }
5458}
5459
Richard Smithe64e7452016-04-18 21:54:58 +00005460void ASTRecordWriter::AddTemplateParameterList(
5461 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005462 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005463 AddSourceLocation(TemplateParams->getTemplateLoc());
5464 AddSourceLocation(TemplateParams->getLAngleLoc());
5465 AddSourceLocation(TemplateParams->getRAngleLoc());
Saar Raz0330fba2019-10-15 18:44:06 +00005466
Richard Smithe64e7452016-04-18 21:54:58 +00005467 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005468 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005469 AddDeclRef(P);
Saar Raz0330fba2019-10-15 18:44:06 +00005470 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5471 Record->push_back(true);
5472 AddStmt(const_cast<Expr*>(RequiresClause));
5473 } else {
5474 Record->push_back(false);
5475 }
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005476}
5477
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005478/// Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005479void ASTRecordWriter::AddTemplateArgumentList(
5480 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005481 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005482 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005483 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005484 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005485}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005486
Richard Smith290d8012016-04-06 17:06:00 +00005487void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5488 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005489 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005490 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5491 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5492 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005493 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005494 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005495 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005496}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005497
Richard Smithe64e7452016-04-18 21:54:58 +00005498void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5499 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005500 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005501 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005502 AddDeclRef(I.getDecl());
5503 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005504 }
5505}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005506
Richard Smith290d8012016-04-06 17:06:00 +00005507// FIXME: Move this out of the main ASTRecordWriter interface.
5508void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5509 Record->push_back(Base.isVirtual());
5510 Record->push_back(Base.isBaseOfClass());
5511 Record->push_back(Base.getAccessSpecifierAsWritten());
5512 Record->push_back(Base.getInheritConstructors());
5513 AddTypeSourceInfo(Base.getTypeSourceInfo());
5514 AddSourceRange(Base.getSourceRange());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005515 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005516 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005517}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005518
Richard Smith645d2cf2016-04-14 00:29:55 +00005519static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5520 ArrayRef<CXXBaseSpecifier> Bases) {
5521 ASTWriter::RecordData Record;
5522 ASTRecordWriter Writer(W, Record);
5523 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005524
Richard Smith645d2cf2016-04-14 00:29:55 +00005525 for (auto &Base : Bases)
5526 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005527
Richard Smith645d2cf2016-04-14 00:29:55 +00005528 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005529}
5530
Richard Smith290d8012016-04-06 17:06:00 +00005531// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005532void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5533 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5534}
5535
Richard Smithaa165cf2016-04-13 21:57:08 +00005536static uint64_t
5537EmitCXXCtorInitializers(ASTWriter &W,
5538 ArrayRef<CXXCtorInitializer *> CtorInits) {
5539 ASTWriter::RecordData Record;
5540 ASTRecordWriter Writer(W, Record);
5541 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005542
Richard Smithaa165cf2016-04-13 21:57:08 +00005543 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005544 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005545 Writer.push_back(CTOR_INITIALIZER_BASE);
5546 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5547 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005548 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005549 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5550 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005551 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005552 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5553 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005554 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005555 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5556 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005557 }
Francois Pichetd583da02010-12-04 09:14:42 +00005558
Richard Smithaa165cf2016-04-13 21:57:08 +00005559 Writer.AddSourceLocation(Init->getMemberLocation());
5560 Writer.AddStmt(Init->getInit());
5561 Writer.AddSourceLocation(Init->getLParenLoc());
5562 Writer.AddSourceLocation(Init->getRParenLoc());
5563 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005564 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005565 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005566 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005567
5568 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005569}
5570
Richard Smithaa165cf2016-04-13 21:57:08 +00005571// FIXME: Move this out of the main ASTRecordWriter interface.
5572void ASTRecordWriter::AddCXXCtorInitializers(
5573 ArrayRef<CXXCtorInitializer *> CtorInits) {
5574 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005575}
5576
Richard Smith290d8012016-04-06 17:06:00 +00005577void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005578 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005579 Record->push_back(Data.IsLambda);
Richard Smith91aeacc2019-10-11 00:29:04 +00005580
5581 #define FIELD(Name, Width, Merge) \
5582 Record->push_back(Data.Name);
5583 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
Richard Trieufd1acbb2017-04-11 21:31:00 +00005584
5585 // getODRHash will compute the ODRHash if it has not been previously computed.
5586 Record->push_back(D->getODRHash());
Luboš Luňákcbc9d222019-11-03 21:15:03 +01005587 bool ModulesDebugInfo =
5588 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
David Blaikief63556d2017-04-12 20:58:33 +00005589 Record->push_back(ModulesDebugInfo);
5590 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00005591 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5592
Richard Smith561fb152012-02-25 07:33:38 +00005593 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005594
Richard Smith290d8012016-04-06 17:06:00 +00005595 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005596 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005597 AddCXXBaseSpecifiers(Data.bases());
5598
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005599 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005600 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005601 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005602 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005603
Richard Smith290d8012016-04-06 17:06:00 +00005604 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
Richard Smith91aeacc2019-10-11 00:29:04 +00005605 Record->push_back(Data.ComputedVisibleConversions);
5606 if (Data.ComputedVisibleConversions)
5607 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005608 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005609 AddDeclRef(D->getFirstFriend());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005610
Douglas Gregor99ae8062012-02-14 17:54:36 +00005611 // Add lambda-specific data.
5612 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005613 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005614 Record->push_back(Lambda.Dependent);
5615 Record->push_back(Lambda.IsGenericLambda);
5616 Record->push_back(Lambda.CaptureDefault);
5617 Record->push_back(Lambda.NumCaptures);
5618 Record->push_back(Lambda.NumExplicitCaptures);
Michael Liao243ebfb2019-10-19 00:15:19 +00005619 Record->push_back(Lambda.HasKnownInternalLinkage);
Richard Smith290d8012016-04-06 17:06:00 +00005620 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00005621 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00005622 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005623 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005624 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005625 AddSourceLocation(Capture.getLocation());
5626 Record->push_back(Capture.isImplicit());
5627 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005628 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005629 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005630 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005631 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005632 break;
5633 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005634 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005635 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005636 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005637 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005638 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005639 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005640 break;
5641 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005642 }
5643 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005644}
5645
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005646void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005647 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005648 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005649 assert(FirstDeclID == NextDeclID &&
5650 FirstTypeID == NextTypeID &&
5651 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005652 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005653 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005654 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005655 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005656
Sebastian Redl07a89a82010-07-30 00:29:29 +00005657 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005658
Richard Smith7f330cd2015-03-18 01:42:29 +00005659 // Note, this will get called multiple times, once one the reader starts up
5660 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005661 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5662 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5663 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005664 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005665 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005666 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005667 NextDeclID = FirstDeclID;
5668 NextTypeID = FirstTypeID;
5669 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005670 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005671 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005672 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005673}
5674
Sebastian Redl539c5062010-08-18 23:57:32 +00005675void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005676 // Always keep the highest ID. See \p TypeRead() for more information.
5677 IdentID &StoredID = IdentifierIDs[II];
5678 if (ID > StoredID)
5679 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005680}
5681
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005682void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005683 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005684 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005685 if (ID > StoredID)
5686 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005687}
5688
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005689void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005690 // Always take the highest-numbered type index. This copes with an interesting
5691 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005692 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005693 // keep the higher-numbered entry so that we can properly write it out to
5694 // the AST file.
5695 TypeIdx &StoredIdx = TypeIdxs[T];
5696 if (Idx.getIndex() >= StoredIdx.getIndex())
5697 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005698}
5699
Sebastian Redl539c5062010-08-18 23:57:32 +00005700void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005701 // Always keep the highest ID. See \p TypeRead() for more information.
5702 SelectorID &StoredID = SelectorIDs[S];
5703 if (ID > StoredID)
5704 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005705}
Douglas Gregor91096292010-10-02 19:29:26 +00005706
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005707void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005708 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005709 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005710 MacroDefinitions[MD] = ID;
5711}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005712
Douglas Gregore37a85a2011-12-02 17:30:13 +00005713void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5714 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5715 SubmoduleIDs[Mod] = ID;
5716}
5717
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005718void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005719 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005720 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005721 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005722 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005723 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005724 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005725 // A forward reference was mutated into a definition. Rewrite it.
5726 // FIXME: This happens during template instantiation, should we
5727 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005728 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5729 "completed a tag from another module but not by instantiation?");
5730 DeclUpdates[RD].push_back(
5731 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005732 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005733 }
5734}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005735
Richard Smithf983f7f2015-10-13 00:23:25 +00005736static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5737 if (D->isFromASTFile())
5738 return true;
5739
Richard Smithf983f7f2015-10-13 00:23:25 +00005740 // The predefined __va_list_tag struct is imported if we imported any decls.
5741 // FIXME: This is a gross hack.
5742 return D == D->getASTContext().getVaListTagDecl();
5743}
5744
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005745void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005746 if (Chain && Chain->isProcessingUpdateRecords()) return;
5747 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005748 "Should not add lookup results to non-lookup contexts!");
5749
Vassil Vassilev632eac32016-03-16 11:17:04 +00005750 // TU is handled elsewhere.
5751 if (isa<TranslationUnitDecl>(DC))
5752 return;
5753
5754 // Namespaces are handled elsewhere, except for template instantiations of
5755 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5756 // local instantiations are added to an imported context. Only happens when
5757 // adding ADL lookup candidates, for example templated friends.
5758 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5759 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005760 return;
5761
Richard Smithf983f7f2015-10-13 00:23:25 +00005762 // We're only interested in cases where a local declaration is added to an
5763 // imported context.
5764 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5765 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005766
Richard Smith0f4e2c42015-08-06 04:23:48 +00005767 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005768 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005769 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005770 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5771 // We're adding a visible declaration to a predefined decl context. Ensure
5772 // that we write out all of its lookup results so we don't get a nasty
5773 // surprise when we try to emit its lookup table.
5774 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00005775 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00005776 }
Richard Smithc26d9742016-10-06 20:30:51 +00005777 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005778}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005779
5780void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005781 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005782 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005783
5784 // We're only interested in cases where a local declaration is added to an
5785 // imported context.
5786 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5787 return;
5788
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005789 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005790 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005791
5792 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005793 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005794 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005795 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005796}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005797
Richard Smith564417a2014-03-20 21:47:22 +00005798void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005799 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005800 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5801 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005802 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005803 // If we don't already know the exception specification for this redecl
5804 // chain, add an update record for it.
5805 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5806 ->getType()
5807 ->castAs<FunctionProtoType>()
5808 ->getExceptionSpecType()))
5809 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5810 });
Richard Smith564417a2014-03-20 21:47:22 +00005811}
5812
Richard Smith1fa5d642013-05-11 05:45:24 +00005813void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005814 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005815 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005816 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005817 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005818 DeclUpdates[D].push_back(
5819 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5820 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005821}
5822
Richard Smithf8134002015-03-10 01:41:22 +00005823void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00005824 const FunctionDecl *Delete,
5825 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005826 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005827 assert(!WritingAST && "Already writing the AST!");
5828 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005829 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005830 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005831 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5832 });
Richard Smithf8134002015-03-10 01:41:22 +00005833}
5834
Sebastian Redlab238a72011-04-24 16:28:06 +00005835void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005836 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005837 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005838 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005839 return; // Declaration not imported from PCH.
5840
Richard Smith4d235792014-08-07 18:53:08 +00005841 // Implicit function decl from a PCH was defined.
5842 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005843}
5844
Richard Smith891fc7f2017-12-05 01:31:47 +00005845void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5846 if (Chain && Chain->isProcessingUpdateRecords()) return;
5847 assert(!WritingAST && "Already writing the AST!");
5848 if (!D->isFromASTFile())
5849 return;
5850
5851 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5852}
5853
Richard Smithd28ac5b2014-03-22 23:33:22 +00005854void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005855 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005856 assert(!WritingAST && "Already writing the AST!");
5857 if (!D->isFromASTFile())
5858 return;
5859
Richard Smith9e2341d2015-03-23 03:25:59 +00005860 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005861}
5862
Richard Smith891fc7f2017-12-05 01:31:47 +00005863void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005864 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005865 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005866 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005867 return;
5868
5869 // Since the actual instantiation is delayed, this really means that we need
5870 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00005871 SourceLocation POI;
5872 if (auto *VD = dyn_cast<VarDecl>(D))
5873 POI = VD->getPointOfInstantiation();
5874 else
5875 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5876 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005877}
5878
John McCall32791cc2016-01-06 22:34:54 +00005879void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005880 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005881 assert(!WritingAST && "Already writing the AST!");
5882 if (!D->isFromASTFile())
5883 return;
5884
5885 DeclUpdates[D].push_back(
5886 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5887}
5888
Richard Smith4b054b22016-08-24 21:25:37 +00005889void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5890 assert(!WritingAST && "Already writing the AST!");
5891 if (!D->isFromASTFile())
5892 return;
5893
5894 DeclUpdates[D].push_back(
5895 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5896}
5897
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005898void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5899 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005900 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005901 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005902 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005903 return; // Declaration not imported from PCH.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005904
Douglas Gregor404cdde2012-01-27 01:47:08 +00005905 assert(IFD->getDefinition() && "Category on a class without a definition?");
5906 ObjCClassesWithCategories.insert(
5907 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005908}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005909
Eli Friedman276dd182013-09-05 00:02:25 +00005910void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005911 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00005912 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00005913
5914 // If there is *any* declaration of the entity that's not from an AST file,
5915 // we can skip writing the update record. We make sure that isUsed() triggers
5916 // completion of the redeclaration chain of the entity.
5917 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5918 if (IsLocalDecl(Prev))
5919 return;
Eli Friedman276dd182013-09-05 00:02:25 +00005920
Aaron Ballman4f45b712014-03-21 15:22:56 +00005921 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005922}
Alexey Bataev97720002014-11-11 04:05:39 +00005923
5924void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005925 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00005926 assert(!WritingAST && "Already writing the AST!");
5927 if (!D->isFromASTFile())
5928 return;
5929
5930 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5931}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005932
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005933void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
5934 if (Chain && Chain->isProcessingUpdateRecords()) return;
5935 assert(!WritingAST && "Already writing the AST!");
5936 if (!D->isFromASTFile())
5937 return;
5938
5939 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
5940}
5941
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005942void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5943 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005944 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005945 assert(!WritingAST && "Already writing the AST!");
5946 if (!D->isFromASTFile())
5947 return;
5948
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005949 DeclUpdates[D].push_back(
5950 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005951}
5952
Richard Smith4caa4492015-05-15 02:34:32 +00005953void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005954 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005955 assert(!WritingAST && "Already writing the AST!");
5956 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005957 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005958}
Alex Denisovfde64952015-06-26 05:28:36 +00005959
5960void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5961 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005962 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00005963 assert(!WritingAST && "Already writing the AST!");
5964 if (!Record->isFromASTFile())
5965 return;
5966 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5967}
Richard Smithc26d9742016-10-06 20:30:51 +00005968
5969void ASTWriter::AddedCXXTemplateSpecialization(
5970 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
5971 assert(!WritingAST && "Already writing the AST!");
5972
5973 if (!TD->getFirstDecl()->isFromASTFile())
5974 return;
5975 if (Chain && Chain->isProcessingUpdateRecords())
5976 return;
5977
5978 DeclsToEmitEvenIfUnreferenced.push_back(D);
5979}
5980
5981void ASTWriter::AddedCXXTemplateSpecialization(
5982 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5983 assert(!WritingAST && "Already writing the AST!");
5984
5985 if (!TD->getFirstDecl()->isFromASTFile())
5986 return;
5987 if (Chain && Chain->isProcessingUpdateRecords())
5988 return;
5989
5990 DeclsToEmitEvenIfUnreferenced.push_back(D);
5991}
5992
5993void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5994 const FunctionDecl *D) {
5995 assert(!WritingAST && "Already writing the AST!");
5996
5997 if (!TD->getFirstDecl()->isFromASTFile())
5998 return;
5999 if (Chain && Chain->isProcessingUpdateRecords())
6000 return;
6001
6002 DeclsToEmitEvenIfUnreferenced.push_back(D);
6003}
Kelvin Libe286f52018-09-15 13:54:15 +00006004
6005//===----------------------------------------------------------------------===//
6006//// OMPClause Serialization
6007////===----------------------------------------------------------------------===//
6008
John McCall2ac702a2019-12-14 03:17:03 -05006009namespace {
6010
6011class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6012 ASTRecordWriter &Record;
6013
6014public:
6015 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6016#define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *S);
6017#include "clang/Basic/OpenMPKinds.def"
6018 void writeClause(OMPClause *C);
6019 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6020 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6021};
6022
6023}
6024
6025void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6026 OMPClauseWriter(*this).writeClause(C);
6027}
6028
Kelvin Libe286f52018-09-15 13:54:15 +00006029void OMPClauseWriter::writeClause(OMPClause *C) {
6030 Record.push_back(C->getClauseKind());
6031 Visit(C);
6032 Record.AddSourceLocation(C->getBeginLoc());
6033 Record.AddSourceLocation(C->getEndLoc());
6034}
6035
6036void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006037 Record.push_back(uint64_t(C->getCaptureRegion()));
Kelvin Libe286f52018-09-15 13:54:15 +00006038 Record.AddStmt(C->getPreInitStmt());
6039}
6040
6041void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6042 VisitOMPClauseWithPreInit(C);
6043 Record.AddStmt(C->getPostUpdateExpr());
6044}
6045
6046void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6047 VisitOMPClauseWithPreInit(C);
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006048 Record.push_back(uint64_t(C->getNameModifier()));
Kelvin Libe286f52018-09-15 13:54:15 +00006049 Record.AddSourceLocation(C->getNameModifierLoc());
6050 Record.AddSourceLocation(C->getColonLoc());
6051 Record.AddStmt(C->getCondition());
6052 Record.AddSourceLocation(C->getLParenLoc());
6053}
6054
6055void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +00006056 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006057 Record.AddStmt(C->getCondition());
6058 Record.AddSourceLocation(C->getLParenLoc());
6059}
6060
6061void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6062 VisitOMPClauseWithPreInit(C);
6063 Record.AddStmt(C->getNumThreads());
6064 Record.AddSourceLocation(C->getLParenLoc());
6065}
6066
6067void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6068 Record.AddStmt(C->getSafelen());
6069 Record.AddSourceLocation(C->getLParenLoc());
6070}
6071
6072void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6073 Record.AddStmt(C->getSimdlen());
6074 Record.AddSourceLocation(C->getLParenLoc());
6075}
6076
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00006077void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6078 Record.AddStmt(C->getAllocator());
6079 Record.AddSourceLocation(C->getLParenLoc());
6080}
6081
Kelvin Libe286f52018-09-15 13:54:15 +00006082void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6083 Record.AddStmt(C->getNumForLoops());
6084 Record.AddSourceLocation(C->getLParenLoc());
6085}
6086
6087void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6088 Record.push_back(C->getDefaultKind());
6089 Record.AddSourceLocation(C->getLParenLoc());
6090 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6091}
6092
6093void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -06006094 Record.push_back(unsigned(C->getProcBindKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006095 Record.AddSourceLocation(C->getLParenLoc());
6096 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6097}
6098
6099void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6100 VisitOMPClauseWithPreInit(C);
6101 Record.push_back(C->getScheduleKind());
6102 Record.push_back(C->getFirstScheduleModifier());
6103 Record.push_back(C->getSecondScheduleModifier());
6104 Record.AddStmt(C->getChunkSize());
6105 Record.AddSourceLocation(C->getLParenLoc());
6106 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6107 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6108 Record.AddSourceLocation(C->getScheduleKindLoc());
6109 Record.AddSourceLocation(C->getCommaLoc());
6110}
6111
6112void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6113 Record.push_back(C->getLoopNumIterations().size());
6114 Record.AddStmt(C->getNumForLoops());
6115 for (Expr *NumIter : C->getLoopNumIterations())
6116 Record.AddStmt(NumIter);
6117 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
Mike Rice0ed46662018-09-20 17:19:41 +00006118 Record.AddStmt(C->getLoopCounter(I));
Kelvin Libe286f52018-09-15 13:54:15 +00006119 Record.AddSourceLocation(C->getLParenLoc());
6120}
6121
6122void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6123
6124void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6125
6126void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6127
6128void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6129
6130void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6131
6132void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
6133
6134void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6135
6136void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6137
6138void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6139
6140void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6141
6142void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6143
6144void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6145 Record.push_back(C->varlist_size());
6146 Record.AddSourceLocation(C->getLParenLoc());
6147 for (auto *VE : C->varlists()) {
6148 Record.AddStmt(VE);
6149 }
6150 for (auto *VE : C->private_copies()) {
6151 Record.AddStmt(VE);
6152 }
6153}
6154
6155void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6156 Record.push_back(C->varlist_size());
6157 VisitOMPClauseWithPreInit(C);
6158 Record.AddSourceLocation(C->getLParenLoc());
6159 for (auto *VE : C->varlists()) {
6160 Record.AddStmt(VE);
6161 }
6162 for (auto *VE : C->private_copies()) {
6163 Record.AddStmt(VE);
6164 }
6165 for (auto *VE : C->inits()) {
6166 Record.AddStmt(VE);
6167 }
6168}
6169
6170void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6171 Record.push_back(C->varlist_size());
6172 VisitOMPClauseWithPostUpdate(C);
6173 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev93dc40d2019-12-20 11:04:57 -05006174 Record.writeEnum(C->getKind());
6175 Record.AddSourceLocation(C->getKindLoc());
6176 Record.AddSourceLocation(C->getColonLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006177 for (auto *VE : C->varlists())
6178 Record.AddStmt(VE);
6179 for (auto *E : C->private_copies())
6180 Record.AddStmt(E);
6181 for (auto *E : C->source_exprs())
6182 Record.AddStmt(E);
6183 for (auto *E : C->destination_exprs())
6184 Record.AddStmt(E);
6185 for (auto *E : C->assignment_ops())
6186 Record.AddStmt(E);
6187}
6188
6189void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6190 Record.push_back(C->varlist_size());
6191 Record.AddSourceLocation(C->getLParenLoc());
6192 for (auto *VE : C->varlists())
6193 Record.AddStmt(VE);
6194}
6195
6196void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6197 Record.push_back(C->varlist_size());
6198 VisitOMPClauseWithPostUpdate(C);
6199 Record.AddSourceLocation(C->getLParenLoc());
6200 Record.AddSourceLocation(C->getColonLoc());
6201 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6202 Record.AddDeclarationNameInfo(C->getNameInfo());
6203 for (auto *VE : C->varlists())
6204 Record.AddStmt(VE);
6205 for (auto *VE : C->privates())
6206 Record.AddStmt(VE);
6207 for (auto *E : C->lhs_exprs())
6208 Record.AddStmt(E);
6209 for (auto *E : C->rhs_exprs())
6210 Record.AddStmt(E);
6211 for (auto *E : C->reduction_ops())
6212 Record.AddStmt(E);
6213}
6214
6215void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6216 Record.push_back(C->varlist_size());
6217 VisitOMPClauseWithPostUpdate(C);
6218 Record.AddSourceLocation(C->getLParenLoc());
6219 Record.AddSourceLocation(C->getColonLoc());
6220 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6221 Record.AddDeclarationNameInfo(C->getNameInfo());
6222 for (auto *VE : C->varlists())
6223 Record.AddStmt(VE);
6224 for (auto *VE : C->privates())
6225 Record.AddStmt(VE);
6226 for (auto *E : C->lhs_exprs())
6227 Record.AddStmt(E);
6228 for (auto *E : C->rhs_exprs())
6229 Record.AddStmt(E);
6230 for (auto *E : C->reduction_ops())
6231 Record.AddStmt(E);
6232}
6233
6234void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6235 Record.push_back(C->varlist_size());
6236 VisitOMPClauseWithPostUpdate(C);
6237 Record.AddSourceLocation(C->getLParenLoc());
6238 Record.AddSourceLocation(C->getColonLoc());
6239 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6240 Record.AddDeclarationNameInfo(C->getNameInfo());
6241 for (auto *VE : C->varlists())
6242 Record.AddStmt(VE);
6243 for (auto *VE : C->privates())
6244 Record.AddStmt(VE);
6245 for (auto *E : C->lhs_exprs())
6246 Record.AddStmt(E);
6247 for (auto *E : C->rhs_exprs())
6248 Record.AddStmt(E);
6249 for (auto *E : C->reduction_ops())
6250 Record.AddStmt(E);
6251 for (auto *E : C->taskgroup_descriptors())
6252 Record.AddStmt(E);
6253}
6254
6255void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6256 Record.push_back(C->varlist_size());
6257 VisitOMPClauseWithPostUpdate(C);
6258 Record.AddSourceLocation(C->getLParenLoc());
6259 Record.AddSourceLocation(C->getColonLoc());
6260 Record.push_back(C->getModifier());
6261 Record.AddSourceLocation(C->getModifierLoc());
6262 for (auto *VE : C->varlists()) {
6263 Record.AddStmt(VE);
6264 }
6265 for (auto *VE : C->privates()) {
6266 Record.AddStmt(VE);
6267 }
6268 for (auto *VE : C->inits()) {
6269 Record.AddStmt(VE);
6270 }
6271 for (auto *VE : C->updates()) {
6272 Record.AddStmt(VE);
6273 }
6274 for (auto *VE : C->finals()) {
6275 Record.AddStmt(VE);
6276 }
6277 Record.AddStmt(C->getStep());
6278 Record.AddStmt(C->getCalcStep());
Alexey Bataev195ae902019-08-08 13:42:45 +00006279 for (auto *VE : C->used_expressions())
6280 Record.AddStmt(VE);
Kelvin Libe286f52018-09-15 13:54:15 +00006281}
6282
6283void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6284 Record.push_back(C->varlist_size());
6285 Record.AddSourceLocation(C->getLParenLoc());
6286 Record.AddSourceLocation(C->getColonLoc());
6287 for (auto *VE : C->varlists())
6288 Record.AddStmt(VE);
6289 Record.AddStmt(C->getAlignment());
6290}
6291
6292void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6293 Record.push_back(C->varlist_size());
6294 Record.AddSourceLocation(C->getLParenLoc());
6295 for (auto *VE : C->varlists())
6296 Record.AddStmt(VE);
6297 for (auto *E : C->source_exprs())
6298 Record.AddStmt(E);
6299 for (auto *E : C->destination_exprs())
6300 Record.AddStmt(E);
6301 for (auto *E : C->assignment_ops())
6302 Record.AddStmt(E);
6303}
6304
6305void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6306 Record.push_back(C->varlist_size());
6307 Record.AddSourceLocation(C->getLParenLoc());
6308 for (auto *VE : C->varlists())
6309 Record.AddStmt(VE);
6310 for (auto *E : C->source_exprs())
6311 Record.AddStmt(E);
6312 for (auto *E : C->destination_exprs())
6313 Record.AddStmt(E);
6314 for (auto *E : C->assignment_ops())
6315 Record.AddStmt(E);
6316}
6317
6318void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6319 Record.push_back(C->varlist_size());
6320 Record.AddSourceLocation(C->getLParenLoc());
6321 for (auto *VE : C->varlists())
6322 Record.AddStmt(VE);
6323}
6324
6325void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6326 Record.push_back(C->varlist_size());
6327 Record.push_back(C->getNumLoops());
6328 Record.AddSourceLocation(C->getLParenLoc());
6329 Record.push_back(C->getDependencyKind());
6330 Record.AddSourceLocation(C->getDependencyLoc());
6331 Record.AddSourceLocation(C->getColonLoc());
6332 for (auto *VE : C->varlists())
6333 Record.AddStmt(VE);
6334 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6335 Record.AddStmt(C->getLoopData(I));
6336}
6337
6338void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6339 VisitOMPClauseWithPreInit(C);
6340 Record.AddStmt(C->getDevice());
6341 Record.AddSourceLocation(C->getLParenLoc());
6342}
6343
6344void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6345 Record.push_back(C->varlist_size());
6346 Record.push_back(C->getUniqueDeclarationsNum());
6347 Record.push_back(C->getTotalComponentListNum());
6348 Record.push_back(C->getTotalComponentsNum());
6349 Record.AddSourceLocation(C->getLParenLoc());
Kelvin Lief579432018-12-18 22:18:41 +00006350 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
6351 Record.push_back(C->getMapTypeModifier(I));
6352 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6353 }
Michael Kruse4304e9d2019-02-19 16:38:20 +00006354 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6355 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006356 Record.push_back(C->getMapType());
6357 Record.AddSourceLocation(C->getMapLoc());
6358 Record.AddSourceLocation(C->getColonLoc());
6359 for (auto *E : C->varlists())
6360 Record.AddStmt(E);
Michael Kruse4304e9d2019-02-19 16:38:20 +00006361 for (auto *E : C->mapperlists())
6362 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006363 for (auto *D : C->all_decls())
6364 Record.AddDeclRef(D);
6365 for (auto N : C->all_num_lists())
6366 Record.push_back(N);
6367 for (auto N : C->all_lists_sizes())
6368 Record.push_back(N);
6369 for (auto &M : C->all_components()) {
6370 Record.AddStmt(M.getAssociatedExpression());
6371 Record.AddDeclRef(M.getAssociatedDeclaration());
6372 }
6373}
6374
Alexey Bataeve04483e2019-03-27 14:14:31 +00006375void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6376 Record.push_back(C->varlist_size());
6377 Record.AddSourceLocation(C->getLParenLoc());
6378 Record.AddSourceLocation(C->getColonLoc());
6379 Record.AddStmt(C->getAllocator());
6380 for (auto *VE : C->varlists())
6381 Record.AddStmt(VE);
6382}
6383
Kelvin Libe286f52018-09-15 13:54:15 +00006384void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6385 VisitOMPClauseWithPreInit(C);
6386 Record.AddStmt(C->getNumTeams());
6387 Record.AddSourceLocation(C->getLParenLoc());
6388}
6389
6390void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6391 VisitOMPClauseWithPreInit(C);
6392 Record.AddStmt(C->getThreadLimit());
6393 Record.AddSourceLocation(C->getLParenLoc());
6394}
6395
6396void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +00006397 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006398 Record.AddStmt(C->getPriority());
6399 Record.AddSourceLocation(C->getLParenLoc());
6400}
6401
6402void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +00006403 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006404 Record.AddStmt(C->getGrainsize());
6405 Record.AddSourceLocation(C->getLParenLoc());
6406}
6407
6408void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +00006409 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006410 Record.AddStmt(C->getNumTasks());
6411 Record.AddSourceLocation(C->getLParenLoc());
6412}
6413
6414void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6415 Record.AddStmt(C->getHint());
6416 Record.AddSourceLocation(C->getLParenLoc());
6417}
6418
6419void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6420 VisitOMPClauseWithPreInit(C);
6421 Record.push_back(C->getDistScheduleKind());
6422 Record.AddStmt(C->getChunkSize());
6423 Record.AddSourceLocation(C->getLParenLoc());
6424 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6425 Record.AddSourceLocation(C->getCommaLoc());
6426}
6427
6428void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6429 Record.push_back(C->getDefaultmapKind());
6430 Record.push_back(C->getDefaultmapModifier());
6431 Record.AddSourceLocation(C->getLParenLoc());
6432 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6433 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6434}
6435
6436void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6437 Record.push_back(C->varlist_size());
6438 Record.push_back(C->getUniqueDeclarationsNum());
6439 Record.push_back(C->getTotalComponentListNum());
6440 Record.push_back(C->getTotalComponentsNum());
6441 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse01f670d2019-02-22 22:29:42 +00006442 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6443 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006444 for (auto *E : C->varlists())
6445 Record.AddStmt(E);
Michael Kruse01f670d2019-02-22 22:29:42 +00006446 for (auto *E : C->mapperlists())
6447 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006448 for (auto *D : C->all_decls())
6449 Record.AddDeclRef(D);
6450 for (auto N : C->all_num_lists())
6451 Record.push_back(N);
6452 for (auto N : C->all_lists_sizes())
6453 Record.push_back(N);
6454 for (auto &M : C->all_components()) {
6455 Record.AddStmt(M.getAssociatedExpression());
6456 Record.AddDeclRef(M.getAssociatedDeclaration());
6457 }
6458}
6459
6460void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6461 Record.push_back(C->varlist_size());
6462 Record.push_back(C->getUniqueDeclarationsNum());
6463 Record.push_back(C->getTotalComponentListNum());
6464 Record.push_back(C->getTotalComponentsNum());
6465 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse0336c752019-02-25 20:34:15 +00006466 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6467 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006468 for (auto *E : C->varlists())
6469 Record.AddStmt(E);
Michael Kruse0336c752019-02-25 20:34:15 +00006470 for (auto *E : C->mapperlists())
6471 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006472 for (auto *D : C->all_decls())
6473 Record.AddDeclRef(D);
6474 for (auto N : C->all_num_lists())
6475 Record.push_back(N);
6476 for (auto N : C->all_lists_sizes())
6477 Record.push_back(N);
6478 for (auto &M : C->all_components()) {
6479 Record.AddStmt(M.getAssociatedExpression());
6480 Record.AddDeclRef(M.getAssociatedDeclaration());
6481 }
6482}
6483
6484void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6485 Record.push_back(C->varlist_size());
6486 Record.push_back(C->getUniqueDeclarationsNum());
6487 Record.push_back(C->getTotalComponentListNum());
6488 Record.push_back(C->getTotalComponentsNum());
6489 Record.AddSourceLocation(C->getLParenLoc());
6490 for (auto *E : C->varlists())
6491 Record.AddStmt(E);
6492 for (auto *VE : C->private_copies())
6493 Record.AddStmt(VE);
6494 for (auto *VE : C->inits())
6495 Record.AddStmt(VE);
6496 for (auto *D : C->all_decls())
6497 Record.AddDeclRef(D);
6498 for (auto N : C->all_num_lists())
6499 Record.push_back(N);
6500 for (auto N : C->all_lists_sizes())
6501 Record.push_back(N);
6502 for (auto &M : C->all_components()) {
6503 Record.AddStmt(M.getAssociatedExpression());
6504 Record.AddDeclRef(M.getAssociatedDeclaration());
6505 }
6506}
6507
6508void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6509 Record.push_back(C->varlist_size());
6510 Record.push_back(C->getUniqueDeclarationsNum());
6511 Record.push_back(C->getTotalComponentListNum());
6512 Record.push_back(C->getTotalComponentsNum());
6513 Record.AddSourceLocation(C->getLParenLoc());
6514 for (auto *E : C->varlists())
6515 Record.AddStmt(E);
6516 for (auto *D : C->all_decls())
6517 Record.AddDeclRef(D);
6518 for (auto N : C->all_num_lists())
6519 Record.push_back(N);
6520 for (auto N : C->all_lists_sizes())
6521 Record.push_back(N);
6522 for (auto &M : C->all_components()) {
6523 Record.AddStmt(M.getAssociatedExpression());
6524 Record.AddDeclRef(M.getAssociatedDeclaration());
6525 }
6526}
Kelvin Li1408f912018-09-26 04:28:39 +00006527
6528void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
Patrick Lyster4a370b92018-10-01 13:47:43 +00006529
6530void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6531 OMPUnifiedSharedMemoryClause *) {}
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00006532
6533void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Patrick Lyster3fe9e392018-10-11 14:41:10 +00006534
6535void
6536OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6537}
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00006538
6539void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6540 OMPAtomicDefaultMemOrderClause *C) {
6541 Record.push_back(C->getAtomicDefaultMemOrderKind());
6542 Record.AddSourceLocation(C->getLParenLoc());
6543 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6544}
Alexey Bataevb6e70842019-12-16 15:54:17 -05006545
6546void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6547 Record.push_back(C->varlist_size());
6548 Record.AddSourceLocation(C->getLParenLoc());
6549 for (auto *VE : C->varlists())
6550 Record.AddStmt(VE);
Alexey Bataev0860db92019-12-19 10:01:10 -05006551 for (auto *E : C->private_refs())
6552 Record.AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05006553}