-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSerializeSIL.cpp
3340 lines (3070 loc) · 137 KB
/
SerializeSIL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SerializeSIL.cpp - Read and write SIL ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-serialize"
#include "SILFormat.h"
#include "Serialization.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/SIL/CFG.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TerminatorUtils.h"
#include "swift/SILOptimizer/Utils/Generics.h"
#include "swift/Strings.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/OnDiskHashTable.h"
#include <type_traits>
using namespace swift;
using namespace swift::serialization;
using namespace swift::serialization::sil_block;
using namespace llvm::support;
using llvm::BCBlockRAII;
static unsigned toStableStringEncoding(StringLiteralInst::Encoding encoding) {
switch (encoding) {
case StringLiteralInst::Encoding::Bytes: return SIL_BYTES;
case StringLiteralInst::Encoding::UTF8: return SIL_UTF8;
case StringLiteralInst::Encoding::ObjCSelector: return SIL_OBJC_SELECTOR;
case StringLiteralInst::Encoding::UTF8_OSLOG: return SIL_UTF8_OSLOG;
}
llvm_unreachable("bad string encoding");
}
static unsigned toStableSILLinkage(SILLinkage linkage) {
switch (linkage) {
case SILLinkage::Public: return SIL_LINKAGE_PUBLIC;
case SILLinkage::PublicNonABI: return SIL_LINKAGE_PUBLIC_NON_ABI;
case SILLinkage::Package: return SIL_LINKAGE_PACKAGE;
case SILLinkage::PackageNonABI: return SIL_LINKAGE_PACKAGE_NON_ABI;
case SILLinkage::Hidden: return SIL_LINKAGE_HIDDEN;
case SILLinkage::Shared: return SIL_LINKAGE_SHARED;
case SILLinkage::Private: return SIL_LINKAGE_PRIVATE;
case SILLinkage::PublicExternal: return SIL_LINKAGE_PUBLIC_EXTERNAL;
case SILLinkage::PackageExternal: return SIL_LINKAGE_PACKAGE_EXTERNAL;
case SILLinkage::HiddenExternal: return SIL_LINKAGE_HIDDEN_EXTERNAL;
}
llvm_unreachable("bad linkage");
}
static unsigned toStableVTableEntryKind(SILVTable::Entry::Kind kind) {
switch (kind) {
case SILVTable::Entry::Kind::Normal: return SIL_VTABLE_ENTRY_NORMAL;
case SILVTable::Entry::Kind::Inherited: return SIL_VTABLE_ENTRY_INHERITED;
case SILVTable::Entry::Kind::Override: return SIL_VTABLE_ENTRY_OVERRIDE;
}
llvm_unreachable("bad vtable entry kind");
}
static unsigned toStableCastConsumptionKind(CastConsumptionKind kind) {
switch (kind) {
case CastConsumptionKind::TakeAlways:
return SIL_CAST_CONSUMPTION_TAKE_ALWAYS;
case CastConsumptionKind::TakeOnSuccess:
return SIL_CAST_CONSUMPTION_TAKE_ON_SUCCESS;
case CastConsumptionKind::CopyOnSuccess:
return SIL_CAST_CONSUMPTION_COPY_ON_SUCCESS;
case CastConsumptionKind::BorrowAlways:
return SIL_CAST_CONSUMPTION_BORROW_ALWAYS;
}
llvm_unreachable("bad cast consumption kind");
}
static unsigned
toStableDifferentiabilityKind(swift::DifferentiabilityKind kind) {
switch (kind) {
case swift::DifferentiabilityKind::NonDifferentiable:
return (unsigned)serialization::DifferentiabilityKind::NonDifferentiable;
case swift::DifferentiabilityKind::Forward:
return (unsigned)serialization::DifferentiabilityKind::Forward;
case swift::DifferentiabilityKind::Reverse:
return (unsigned)serialization::DifferentiabilityKind::Reverse;
case swift::DifferentiabilityKind::Normal:
return (unsigned)serialization::DifferentiabilityKind::Normal;
case swift::DifferentiabilityKind::Linear:
return (unsigned)serialization::DifferentiabilityKind::Linear;
}
llvm_unreachable("covered switch");
}
static unsigned encodeValueOwnership(ValueOwnershipKind ownership) {
assert(ownership.value > 0 && "invalid value ownership");
return ownership.value - 1;
}
namespace {
/// Used to serialize the on-disk func hash table.
class FuncTableInfo {
Serializer &S;
public:
using key_type = StringRef;
using key_type_ref = key_type;
using data_type = DeclID;
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
explicit FuncTableInfo(Serializer &S) : S(S) {}
hash_value_type ComputeHash(key_type_ref key) {
assert(!key.empty());
return llvm::djbHash(key, SWIFTMODULE_HASH_SEED);
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
return { sizeof(uint32_t), sizeof(uint32_t) };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
uint32_t keyID = S.addUniquedStringRef(key);
endian::write<uint32_t>(out, keyID, little);
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
endian::write<uint32_t>(out, data, little);
}
};
class SILSerializer {
using TypeID = serialization::TypeID;
Serializer &S;
llvm::BitstreamWriter &Out;
/// A reusable buffer for emitting records.
SmallVector<uint64_t, 64> ScratchRecord;
/// In case we want to encode the relative of InstID vs ValueID.
uint32_t /*ValueID*/ InstID = 0;
llvm::DenseMap<const ValueBase*, ValueID> ValueIDs;
ValueID addValueRef(const ValueBase *Val);
public:
using TableData = FuncTableInfo::data_type;
using Table = llvm::MapVector<FuncTableInfo::key_type, TableData>;
private:
/// FuncTable maps function name to an ID.
Table FuncTable;
std::vector<BitOffset> Funcs;
/// The current function ID.
uint32_t /*DeclID*/ NextFuncID = 1;
/// Maps class name to a VTable ID.
Table VTableList;
/// Holds the list of VTables.
std::vector<BitOffset> VTableOffset;
uint32_t /*DeclID*/ NextVTableID = 1;
/// Maps nominal type name to a MoveOnlyDeinit ID.
Table MoveOnlyDeinitList;
/// Holds the list of MoveOnlyDeinits.
std::vector<BitOffset> MoveOnlyDeinitOffset;
uint32_t /*DeclID*/ NextMoveOnlyDeinitOffsetID = 1;
/// Maps global variable name to an ID.
Table GlobalVarList;
/// Holds the list of SIL global variables.
std::vector<BitOffset> GlobalVarOffset;
uint32_t /*DeclID*/ NextGlobalVarID = 1;
/// Maps witness table identifier to an ID.
Table WitnessTableList;
/// Holds the list of WitnessTables.
std::vector<BitOffset> WitnessTableOffset;
uint32_t /*DeclID*/ NextWitnessTableID = 1;
/// Maps default witness table identifier to an ID.
Table DefaultWitnessTableList;
/// Holds the list of DefaultWitnessTables.
std::vector<BitOffset> DefaultWitnessTableOffset;
uint32_t /*DeclID*/ NextDefaultWitnessTableID = 1;
/// Holds the list of Properties.
std::vector<BitOffset> PropertyOffset;
/// Maps differentiability witness identifier to an ID.
Table DifferentiabilityWitnessList;
/// Holds the list of SIL differentiability witnesses.
std::vector<BitOffset> DifferentiabilityWitnessOffset;
uint32_t /*DeclID*/ NextDifferentiabilityWitnessID = 1;
/// Give each SILBasicBlock a unique ID.
llvm::DenseMap<const SILBasicBlock *, unsigned> BasicBlockMap;
/// Functions that we've emitted a reference to. If the key maps
/// to true, we want to emit a declaration only.
llvm::DenseMap<const SILFunction *, bool> FuncsToEmit;
/// Global variables that we've emitted a reference to.
llvm::DenseSet<const SILGlobalVariable *> GlobalsToEmit;
/// Referenced differentiability witnesses that need to be emitted.
llvm::DenseSet<const SILDifferentiabilityWitness *>
DifferentiabilityWitnessesToEmit;
/// Additional functions we might need to serialize.
llvm::SmallVector<const SILFunction *, 16> functionWorklist;
llvm::SmallVector<const SILGlobalVariable *, 16> globalWorklist;
/// String storage for temporarily created strings which are referenced from
/// the tables.
llvm::BumpPtrAllocator StringTable;
std::array<unsigned, 256> SILAbbrCodes;
template <typename Layout>
void registerSILAbbr() {
using AbbrArrayTy = decltype(SILAbbrCodes);
static_assert(Layout::Code <= std::tuple_size<AbbrArrayTy>::value,
"layout has invalid record code");
SILAbbrCodes[Layout::Code] = Layout::emitAbbrev(Out);
LLVM_DEBUG(llvm::dbgs() << "SIL abbre code " << SILAbbrCodes[Layout::Code]
<< " for layout " << Layout::Code << "\n");
}
bool ShouldSerializeAll;
void addMandatorySILFunction(const SILFunction *F,
bool emitDeclarationsForOnoneSupport);
void addReferencedSILFunction(const SILFunction *F,
bool DeclOnly = false);
void addReferencedGlobalVariable(const SILGlobalVariable *gl);
void processWorklists();
/// Helper function to update ListOfValues for MethodInst. Format:
/// Attr, SILDeclRef (DeclID, Kind, uncurryLevel), and an operand.
void handleMethodInst(const MethodInst *MI, SILValue operand,
SmallVectorImpl<uint64_t> &ListOfValues);
void writeSILFunction(const SILFunction &F, bool DeclOnly = false);
void writeSILBasicBlock(const SILBasicBlock &BB);
void writeSILInstruction(const SILInstruction &SI);
void writeSILVTable(const SILVTable &vt);
void writeSILMoveOnlyDeinit(const SILMoveOnlyDeinit &deinit);
void writeSILGlobalVar(const SILGlobalVariable &g);
void writeSILWitnessTable(const SILWitnessTable &wt);
void writeSILWitnessTableEntry(const SILWitnessTable::Entry &entry);
void writeSILDefaultWitnessTable(const SILDefaultWitnessTable &wt);
void
writeSILDifferentiabilityWitness(const SILDifferentiabilityWitness &dw);
void writeSILProperty(const SILProperty &prop);
void writeSILBlock(const SILModule *SILMod);
void writeIndexTables();
void writeNoOperandLayout(const SILInstruction *I) {
unsigned abbrCode = SILAbbrCodes[SILInstNoOperandLayout::Code];
SILInstNoOperandLayout::emitRecord(Out, ScratchRecord, abbrCode,
(unsigned)I->getKind());
}
void writeConversionLikeInstruction(const SingleValueInstruction *I,
unsigned attrs);
void writeOneTypeLayout(SILInstructionKind valueKind,
unsigned attrs, SILType type);
void writeOneTypeLayout(SILInstructionKind valueKind,
unsigned attrs, CanType type);
void writeOneTypeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
SILType type,
SILValue operand);
void writeOneTypeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
CanType type,
SILValue operand);
void writeOneTypeOneOperandExtraAttributeLayout(
SILInstructionKind valueKind, unsigned attrs,
SILType type, SILValue operand);
void writeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
SILValue operand);
void writeOneOperandExtraAttributeLayout(SILInstructionKind valueKind,
unsigned attrs, SILValue operand);
void writeKeyPathPatternComponent(
const KeyPathPatternComponent &component,
SmallVectorImpl<uint64_t> &ListOfValues);
/// Helper function to determine if given the current state of the
/// deserialization if the function body for F should be deserialized.
bool shouldEmitFunctionBody(const SILFunction *F, bool isReference = true);
IdentifierID addSILFunctionRef(SILFunction *F);
public:
SILSerializer(Serializer &S, llvm::BitstreamWriter &Out, bool serializeAll)
: S(S), Out(Out), ShouldSerializeAll(serializeAll) {}
void writeSILModule(const SILModule *SILMod);
};
} // end anonymous namespace
void SILSerializer::addMandatorySILFunction(const SILFunction *F,
bool emitDeclarationsForOnoneSupport) {
// If this function is not fragile, don't do anything.
if (!emitDeclarationsForOnoneSupport &&
!shouldEmitFunctionBody(F, /* isReference */ false))
return;
auto iter = FuncsToEmit.find(F);
if (iter != FuncsToEmit.end()) {
// We've already visited this function. Make sure that we decided
// to emit its body the first time around.
assert(iter->second == emitDeclarationsForOnoneSupport
&& "Already emitting declaration");
return;
}
// We haven't seen this function before. Record that we want to
// emit its body, and add it to the worklist.
FuncsToEmit[F] = emitDeclarationsForOnoneSupport;
// Function body should be serialized unless it is a KeepAsPublic function
// (which is typically a pre-specialization).
if (!emitDeclarationsForOnoneSupport)
functionWorklist.push_back(F);
}
void SILSerializer::addReferencedSILFunction(const SILFunction *F,
bool DeclOnly) {
assert(F != nullptr);
if (FuncsToEmit.count(F) > 0)
return;
// We haven't seen this function before. Let's see if we should
// serialize the body or just the declaration.
if (shouldEmitFunctionBody(F)) {
FuncsToEmit[F] = false;
functionWorklist.push_back(F);
return;
}
if (F->getLinkage() == SILLinkage::Shared) {
assert(F->isSerialized() || F->hasForeignBody());
FuncsToEmit[F] = false;
functionWorklist.push_back(F);
return;
}
// Ok, we just need to emit a declaration.
FuncsToEmit[F] = true;
}
void SILSerializer::addReferencedGlobalVariable(const SILGlobalVariable *gl) {
if (GlobalsToEmit.insert(gl).second)
globalWorklist.push_back(gl);
}
void SILSerializer::processWorklists() {
do {
while (!functionWorklist.empty()) {
const SILFunction *F = functionWorklist.pop_back_val();
assert(F != nullptr);
assert(FuncsToEmit.count(F) > 0);
writeSILFunction(*F, FuncsToEmit[F]);
}
while (!globalWorklist.empty()) {
const SILGlobalVariable *gl = globalWorklist.pop_back_val();
assert(GlobalsToEmit.count(gl) > 0);
writeSILGlobalVar(*gl);
}
} while (!functionWorklist.empty());
}
/// We enumerate all values in a SILFunction beforehand to correctly
/// handle forward references of values.
ValueID SILSerializer::addValueRef(const ValueBase *Val) {
if (!Val)
return 0;
if (auto *Undef = dyn_cast<SILUndef>(Val)) {
// The first two IDs are reserved for SILUndef.
if (Undef->getOwnershipKind() == OwnershipKind::None)
return 0;
assert(Undef->getOwnershipKind() == OwnershipKind::Owned);
return 1;
}
ValueID id = ValueIDs[Val];
assert(id != 0 && "We should have assigned a value ID to each value.");
return id;
}
void SILSerializer::writeSILFunction(const SILFunction &F, bool DeclOnly) {
PrettyStackTraceSILFunction stackTrace("Serializing", &F);
ValueIDs.clear();
InstID = 0;
FuncTable[F.getName()] = NextFuncID++;
Funcs.push_back(Out.GetCurrentBitNo());
unsigned abbrCode = SILAbbrCodes[SILFunctionLayout::Code];
TypeID FnID = S.addTypeRef(F.getLoweredType().getRawASTType());
LLVM_DEBUG(llvm::dbgs() << "SILFunction " << F.getName() << " @ BitNo "
<< Out.GetCurrentBitNo() << " abbrCode " << abbrCode
<< " FnID " << FnID << "\n");
LLVM_DEBUG(llvm::dbgs() << "Serialized SIL:\n"; F.dump());
SmallVector<IdentifierID, 1> SemanticsIDs;
for (auto SemanticAttr : F.getSemanticsAttrs()) {
SemanticsIDs.push_back(S.addUniquedStringRef(SemanticAttr));
}
SILLinkage Linkage = F.getLinkage();
// Check if we need to emit a body for this function.
bool NoBody = DeclOnly || isAvailableExternally(Linkage) ||
F.isExternalDeclaration();
// If we don't emit a function body then make sure to mark the declaration
// as available externally.
if (NoBody) {
Linkage = addExternalToLinkage(Linkage);
}
// If we have a body, we might have a generic environment.
GenericSignatureID genericSigID = 0;
if (!NoBody)
if (auto *genericEnv = F.getGenericEnvironment())
genericSigID = S.addGenericSignatureRef(genericEnv->getGenericSignature());
DeclID clangNodeOwnerID;
if (F.hasClangNode())
clangNodeOwnerID = S.addDeclRef(F.getClangNodeOwner());
ModuleID parentModuleID;
if (auto *parentModule = F.getParentModule())
parentModuleID = S.addModuleRef(parentModule);
IdentifierID replacedFunctionID = 0;
if (auto *fun = F.getDynamicallyReplacedFunction()) {
addReferencedSILFunction(fun, true);
replacedFunctionID = S.addUniquedStringRef(fun->getName());
} else if (F.hasObjCReplacement()) {
replacedFunctionID =
S.addUniquedStringRef(F.getObjCReplacement().str());
}
IdentifierID usedAdHocWitnessFunctionID = 0;
if (auto *fun = F.getReferencedAdHocRequirementWitnessFunction()) {
addReferencedSILFunction(fun, true);
usedAdHocWitnessFunctionID = S.addUniquedStringRef(fun->getName());
}
unsigned numAttrs = NoBody ? 0 : F.getSpecializeAttrs().size();
auto resilience = F.getModule().getSwiftModule()->getResilienceStrategy();
bool serializeDerivedEffects = (resilience != ResilienceStrategy::Resilient) &&
!F.hasSemanticsAttr("optimize.no.crossmodule");
F.visitArgEffects(
[&](int effectIdx, int argumentIndex, bool isDerived) {
if (isDerived && !serializeDerivedEffects)
return;
numAttrs++;
});
std::optional<llvm::VersionTuple> available;
auto availability = F.getAvailabilityForLinkage();
if (!availability.isAlwaysAvailable()) {
available = availability.getOSVersion().getLowerEndpoint();
}
ENCODE_VER_TUPLE(available, available)
SILFunctionLayout::emitRecord(
Out, ScratchRecord, abbrCode, toStableSILLinkage(Linkage),
(unsigned)F.isTransparent(), (unsigned)F.isSerialized(),
(unsigned)F.isThunk(), (unsigned)F.isWithoutActuallyEscapingThunk(),
(unsigned)F.getSpecialPurpose(), (unsigned)F.getInlineStrategy(),
(unsigned)F.getOptimizationMode(), (unsigned)F.getPerfConstraints(),
(unsigned)F.getClassSubclassScope(), (unsigned)F.hasCReferences(),
(unsigned)F.getEffectsKind(), (unsigned)numAttrs,
(unsigned)F.hasOwnership(), F.isAlwaysWeakImported(),
LIST_VER_TUPLE_PIECES(available), (unsigned)F.isDynamicallyReplaceable(),
(unsigned)F.isExactSelfClass(), (unsigned)F.isDistributed(),
(unsigned)F.isRuntimeAccessible(),
(unsigned)F.forceEnableLexicalLifetimes(), FnID, replacedFunctionID,
usedAdHocWitnessFunctionID, genericSigID, clangNodeOwnerID,
parentModuleID, SemanticsIDs);
F.visitArgEffects(
[&](int effectIdx, int argumentIndex, bool isDerived) {
if (isDerived && !serializeDerivedEffects)
return;
llvm::SmallString<64> buffer;
llvm::raw_svector_ostream OS(buffer);
F.writeEffect(OS, effectIdx);
IdentifierID effectsStrID = S.addUniquedStringRef(OS.str());
unsigned abbrCode = SILAbbrCodes[SILArgEffectsAttrLayout::Code];
bool isGlobalSideEffects = (argumentIndex < 0);
unsigned argIdx = (isGlobalSideEffects ? 0 : (unsigned)argumentIndex);
SILArgEffectsAttrLayout::emitRecord(
Out, ScratchRecord, abbrCode, effectsStrID,
argIdx, (unsigned)isGlobalSideEffects, (unsigned)isDerived);
});
if (NoBody)
return;
for (auto *SA : F.getSpecializeAttrs()) {
unsigned specAttrAbbrCode = SILAbbrCodes[SILSpecializeAttrLayout::Code];
IdentifierID targetFunctionNameID = 0;
if (auto *target = SA->getTargetFunction()) {
addReferencedSILFunction(target, true);
targetFunctionNameID = S.addUniquedStringRef(target->getName());
}
IdentifierID spiGroupID = 0;
IdentifierID spiModuleDeclID = 0;
auto ident = SA->getSPIGroup();
if (!ident.empty()) {
spiGroupID = S.addUniquedStringRef(ident.str());
spiModuleDeclID = S.addModuleRef(SA->getSPIModule());
}
auto availability = SA->getAvailability();
if (!availability.isAlwaysAvailable()) {
available = availability.getOSVersion().getLowerEndpoint();
}
ENCODE_VER_TUPLE(available, available)
llvm::SmallVector<IdentifierID, 4> typeErasedParamsIDs;
for (auto ty : SA->getTypeErasedParams()) {
typeErasedParamsIDs.push_back(S.addTypeRef(ty));
}
SILSpecializeAttrLayout::emitRecord(
Out, ScratchRecord, specAttrAbbrCode, (unsigned)SA->isExported(),
(unsigned)SA->getSpecializationKind(),
S.addGenericSignatureRef(SA->getSpecializedSignature()),
targetFunctionNameID, spiGroupID, spiModuleDeclID,
LIST_VER_TUPLE_PIECES(available), typeErasedParamsIDs
);
}
// Assign a unique ID to each basic block of the SILFunction.
unsigned BasicID = 0;
BasicBlockMap.clear();
// Assign a value ID to each SILInstruction that has value and to each basic
// block argument.
//
// FIXME: Add reverse iteration to SILSuccessor and convert this to a "stable"
// RPO order. Currently, the serializer inverts the order of successors each
// time they are processed.
//
// The first valid value ID is 2. 0 and 1 are reserved for SILUndef.
unsigned ValueID = 2;
llvm::ReversePostOrderTraversal<SILFunction *> RPOT(
const_cast<SILFunction *>(&F));
for (auto Iter = RPOT.begin(), E = RPOT.end(); Iter != E; ++Iter) {
auto &BB = **Iter;
BasicBlockMap.insert(std::make_pair(&BB, BasicID++));
for (auto I = BB.args_begin(), E = BB.args_end(); I != E; ++I)
ValueIDs[static_cast<const ValueBase*>(*I)] = ValueID++;
for (const SILInstruction &SI : BB)
for (auto result : SI.getResults())
ValueIDs[result] = ValueID++;
}
// Write SIL basic blocks in the RPOT order
// to make sure that instructions defining open archetypes
// are serialized before instructions using those opened
// archetypes.
unsigned SerializedBBNum = 0;
for (auto Iter = RPOT.begin(), E = RPOT.end(); Iter != E; ++Iter) {
auto *BB = *Iter;
writeSILBasicBlock(*BB);
SerializedBBNum++;
}
assert(BasicID == SerializedBBNum && "Wrong number of BBs was serialized");
}
void SILSerializer::writeSILBasicBlock(const SILBasicBlock &BB) {
SmallVector<DeclID, 4> Args;
for (auto I = BB.args_begin(), E = BB.args_end(); I != E; ++I) {
SILArgument *SA = *I;
DeclID tId = S.addTypeRef(SA->getType().getRawASTType());
DeclID vId = addValueRef(static_cast<const ValueBase*>(SA));
Args.push_back(tId);
// We put these static asserts here to formalize our assumption that both
// SILValueCategory and ValueOwnershipKind have uint8_t as their underlying
// pointer values.
static_assert(
std::is_same<
std::underlying_type<decltype(SA->getType().getCategory())>::type,
uint8_t>::value,
"Expected an underlying uint8_t type");
// We put these static asserts here to formalize our assumption that both
// SILValueCategory and ValueOwnershipKind have uint8_t as their underlying
// pointer values.
static_assert(std::is_same<std::underlying_type<decltype(
SA->getOwnershipKind())::innerty>::type,
uint8_t>::value,
"Expected an underlying uint8_t type");
// This is 31 bits in size.
unsigned packedMetadata = 0;
packedMetadata |= unsigned(SA->getType().getCategory()); // 8 bits
packedMetadata |= unsigned(SA->getOwnershipKind()) << 8; // 3 bits
packedMetadata |= unsigned(SA->isReborrow()) << 11; // 1 bit
packedMetadata |= unsigned(SA->hasPointerEscape()) << 12; // 1 bit
if (auto *SFA = dyn_cast<SILFunctionArgument>(SA)) {
packedMetadata |= unsigned(SFA->isNoImplicitCopy()) << 13; // 1 bit
packedMetadata |= unsigned(SFA->getLifetimeAnnotation()) << 14; // 2 bits
packedMetadata |= unsigned(SFA->isClosureCapture()) << 16; // 1 bit
packedMetadata |= unsigned(SFA->isFormalParameterPack()) << 17; // 1 bit
}
// Used: 17 bits. Free: 15.
//
// TODO: We should be able to shrink the packed metadata of the first two.
Args.push_back(packedMetadata);
Args.push_back(vId);
}
unsigned abbrCode = SILAbbrCodes[SILBasicBlockLayout::Code];
SILBasicBlockLayout::emitRecord(Out, ScratchRecord, abbrCode, Args);
for (const SILInstruction &SI : BB)
writeSILInstruction(SI);
}
/// Add SILDeclRef to ListOfValues, so we can reconstruct it at
/// deserialization.
static void handleSILDeclRef(Serializer &S, const SILDeclRef &Ref,
SmallVectorImpl<uint64_t> &ListOfValues) {
ListOfValues.push_back(S.addDeclRef(Ref.getDecl()));
ListOfValues.push_back((unsigned)Ref.kind);
ListOfValues.push_back(Ref.isForeign);
}
/// Get an identifier ref for a SILFunction and add it to the list of referenced
/// functions.
IdentifierID SILSerializer::addSILFunctionRef(SILFunction *F) {
addReferencedSILFunction(F);
return S.addUniquedStringRef(F->getName());
}
/// Helper function to update ListOfValues for MethodInst. Format:
/// Attr, SILDeclRef (DeclID, Kind, uncurryLevel), and an operand.
void SILSerializer::handleMethodInst(const MethodInst *MI,
SILValue operand,
SmallVectorImpl<uint64_t> &ListOfValues) {
handleSILDeclRef(S, MI->getMember(), ListOfValues);
ListOfValues.push_back(
S.addTypeRef(operand->getType().getRawASTType()));
ListOfValues.push_back((unsigned)operand->getType().getCategory());
ListOfValues.push_back(addValueRef(operand));
}
void SILSerializer::writeOneTypeLayout(SILInstructionKind valueKind,
unsigned attrs, SILType type) {
unsigned abbrCode = SILAbbrCodes[SILOneTypeLayout::Code];
SILOneTypeLayout::emitRecord(Out, ScratchRecord, abbrCode,
(unsigned) valueKind, attrs,
S.addTypeRef(type.getRawASTType()),
(unsigned)type.getCategory());
}
void SILSerializer::writeOneTypeLayout(SILInstructionKind valueKind,
unsigned attrs, CanType type) {
unsigned abbrCode = SILAbbrCodes[SILOneTypeLayout::Code];
SILOneTypeLayout::emitRecord(Out, ScratchRecord, abbrCode,
(unsigned) valueKind, attrs,
S.addTypeRef(type), 0);
}
void SILSerializer::writeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
SILValue operand) {
auto operandType = operand->getType();
auto operandTypeRef = S.addTypeRef(operandType.getRawASTType());
auto operandRef = addValueRef(operand);
SILOneOperandLayout::emitRecord(Out, ScratchRecord,
SILAbbrCodes[SILOneOperandLayout::Code],
unsigned(valueKind), attrs,
operandTypeRef, unsigned(operandType.getCategory()),
operandRef);
}
void SILSerializer::
writeOneOperandExtraAttributeLayout(SILInstructionKind valueKind,
unsigned attrs,
SILValue operand) {
auto operandType = operand->getType();
auto operandTypeRef = S.addTypeRef(operandType.getRawASTType());
auto operandRef = addValueRef(operand);
SILOneOperandExtraAttributeLayout::emitRecord(
Out, ScratchRecord, SILAbbrCodes[SILOneOperandExtraAttributeLayout::Code],
unsigned(valueKind), attrs, operandTypeRef,
unsigned(operandType.getCategory()), operandRef);
}
void SILSerializer::writeOneTypeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
SILType type,
SILValue operand) {
auto typeRef = S.addTypeRef(type.getRawASTType());
auto operandType = operand->getType();
auto operandTypeRef = S.addTypeRef(operandType.getRawASTType());
auto operandRef = addValueRef(operand);
SILOneTypeOneOperandLayout::emitRecord(Out, ScratchRecord,
SILAbbrCodes[SILOneTypeOneOperandLayout::Code],
unsigned(valueKind), attrs,
typeRef, unsigned(type.getCategory()),
operandTypeRef, unsigned(operandType.getCategory()),
operandRef);
}
void SILSerializer::writeOneTypeOneOperandLayout(SILInstructionKind valueKind,
unsigned attrs,
CanType type,
SILValue operand) {
auto typeRef = S.addTypeRef(type);
auto operandType = operand->getType();
auto operandTypeRef = S.addTypeRef(operandType.getRawASTType());
auto operandRef = addValueRef(operand);
SILOneTypeOneOperandLayout::emitRecord(Out, ScratchRecord,
SILAbbrCodes[SILOneTypeOneOperandLayout::Code],
unsigned(valueKind), attrs,
typeRef, 0,
operandTypeRef, unsigned(operandType.getCategory()),
operandRef);
}
void SILSerializer::
writeOneTypeOneOperandExtraAttributeLayout(SILInstructionKind valueKind,
unsigned attrs,
SILType type,
SILValue operand) {
auto typeRef = S.addTypeRef(type.getRawASTType());
auto operandType = operand->getType();
auto operandTypeRef = S.addTypeRef(operandType.getRawASTType());
auto operandRef = addValueRef(operand);
SILOneTypeOneOperandExtraAttributeLayout::emitRecord(Out, ScratchRecord,
SILAbbrCodes[SILOneTypeOneOperandExtraAttributeLayout::Code],
unsigned(valueKind), attrs,
typeRef, unsigned(type.getCategory()),
operandTypeRef, unsigned(operandType.getCategory()),
operandRef);
}
/// Write an instruction that looks exactly like a conversion: all
/// important information is encoded in the operand and the result type.
void SILSerializer::writeConversionLikeInstruction(
const SingleValueInstruction *I, unsigned attrs) {
assert(I->getNumOperands() - I->getTypeDependentOperands().size() == 1);
writeOneTypeOneOperandLayout(I->getKind(), attrs, I->getType(),
I->getOperand(0));
}
void
SILSerializer::writeKeyPathPatternComponent(
const KeyPathPatternComponent &component,
SmallVectorImpl<uint64_t> &ListOfValues) {
auto handleComponentCommon = [&](KeyPathComponentKindEncoding kind) {
ListOfValues.push_back((unsigned)kind);
ListOfValues.push_back(S.addTypeRef(component.getComponentType()));
};
auto handleComputedId = [&](KeyPathPatternComponent::ComputedPropertyId id) {
switch (id.getKind()) {
case KeyPathPatternComponent::ComputedPropertyId::Property:
ListOfValues.push_back(
(unsigned)KeyPathComputedComponentIdKindEncoding::Property);
ListOfValues.push_back(S.addDeclRef(id.getProperty()));
break;
case KeyPathPatternComponent::ComputedPropertyId::Function:
ListOfValues.push_back(
(unsigned)KeyPathComputedComponentIdKindEncoding::Function);
ListOfValues.push_back(addSILFunctionRef(id.getFunction()));
break;
case KeyPathPatternComponent::ComputedPropertyId::DeclRef:
ListOfValues.push_back(
(unsigned)KeyPathComputedComponentIdKindEncoding::DeclRef);
handleSILDeclRef(S, id.getDeclRef(), ListOfValues);
break;
}
};
auto handleComputedExternalReferenceAndIndices
= [&](const KeyPathPatternComponent &component) {
ListOfValues.push_back(S.addDeclRef(component.getExternalDecl()));
ListOfValues.push_back(
S.addSubstitutionMapRef(component.getExternalSubstitutions()));
auto indices = component.getSubscriptIndices();
ListOfValues.push_back(indices.size());
for (auto &index : indices) {
ListOfValues.push_back(index.Operand);
ListOfValues.push_back(S.addTypeRef(index.FormalType));
ListOfValues.push_back(
S.addTypeRef(index.LoweredType.getRawASTType()));
ListOfValues.push_back((unsigned)index.LoweredType.getCategory());
ListOfValues.push_back(S.addConformanceRef(index.Hashable));
}
if (!indices.empty()) {
ListOfValues.push_back(
addSILFunctionRef(component.getSubscriptIndexEquals()));
ListOfValues.push_back(
addSILFunctionRef(component.getSubscriptIndexHash()));
}
};
switch (component.getKind()) {
case KeyPathPatternComponent::Kind::StoredProperty:
handleComponentCommon(KeyPathComponentKindEncoding::StoredProperty);
ListOfValues.push_back(S.addDeclRef(component.getStoredPropertyDecl()));
break;
case KeyPathPatternComponent::Kind::GettableProperty:
handleComponentCommon(KeyPathComponentKindEncoding::GettableProperty);
handleComputedId(component.getComputedPropertyId());
ListOfValues.push_back(
addSILFunctionRef(component.getComputedPropertyGetter()));
handleComputedExternalReferenceAndIndices(component);
break;
case KeyPathPatternComponent::Kind::SettableProperty:
handleComponentCommon(KeyPathComponentKindEncoding::SettableProperty);
handleComputedId(component.getComputedPropertyId());
ListOfValues.push_back(
addSILFunctionRef(component.getComputedPropertyGetter()));
ListOfValues.push_back(
addSILFunctionRef(component.getComputedPropertySetter()));
handleComputedExternalReferenceAndIndices(component);
break;
case KeyPathPatternComponent::Kind::OptionalChain:
handleComponentCommon(KeyPathComponentKindEncoding::OptionalChain);
break;
case KeyPathPatternComponent::Kind::OptionalForce:
handleComponentCommon(KeyPathComponentKindEncoding::OptionalForce);
break;
case KeyPathPatternComponent::Kind::OptionalWrap:
handleComponentCommon(KeyPathComponentKindEncoding::OptionalWrap);
break;
case KeyPathPatternComponent::Kind::TupleElement:
handleComponentCommon(KeyPathComponentKindEncoding::TupleElement);
ListOfValues.push_back((unsigned)component.getTupleIndex());
break;
}
}
void SILSerializer::writeSILInstruction(const SILInstruction &SI) {
PrettyStackTraceSILNode stackTrace("Serializing", &SI);
switch (SI.getKind()) {
case SILInstructionKind::ObjectInst: {
const ObjectInst *OI = cast<ObjectInst>(&SI);
unsigned abbrCode = SILAbbrCodes[SILOneTypeValuesLayout::Code];
SmallVector<ValueID, 4> Args;
Args.push_back((unsigned)OI->getBaseElements().size());
for (const Operand &op : OI->getAllOperands()) {
SILValue OpVal = op.get();
Args.push_back(addValueRef(OpVal));
SILType OpType = OpVal->getType();
assert(OpType.isObject());
Args.push_back(S.addTypeRef(OpType.getRawASTType()));
}
SILOneTypeValuesLayout::emitRecord(
Out, ScratchRecord, abbrCode, (unsigned)SI.getKind(),
S.addTypeRef(OI->getType().getRawASTType()),
(unsigned)OI->getType().getCategory(), Args);
break;
}
case SILInstructionKind::VectorInst: {
auto *vi = cast<VectorInst>(&SI);
SmallVector<ValueID, 4> ListOfValues;
for (auto Elt : vi->getElements()) {
ListOfValues.push_back(addValueRef(Elt));
}
unsigned abbrCode = SILAbbrCodes[SILOneTypeValuesLayout::Code];
SILOneTypeValuesLayout::emitRecord(Out, ScratchRecord, abbrCode,
(unsigned)SI.getKind(),
S.addTypeRef(vi->getType().getRawASTType()),
(unsigned)vi->getType().getCategory(),
ListOfValues);
break;
}
case SILInstructionKind::DebugValueInst:
case SILInstructionKind::DebugStepInst:
// Currently we don't serialize debug info, so it doesn't make
// sense to write those instructions at all.
// TODO: decide if we want to serialize those instructions.
return;
case SILInstructionKind::SpecifyTestInst:
// Instruction exists only for tests. Ignore it.
return;
case SILInstructionKind::AllocPackMetadataInst:
case SILInstructionKind::DeallocPackMetadataInst:
// Shoulud never be serialized: only introduced in an IRGen pass
// (PackMetadataMarkerInserter).
return;
case SILInstructionKind::UnwindInst:
case SILInstructionKind::ThrowAddrInst:
case SILInstructionKind::UnreachableInst: {
writeNoOperandLayout(&SI);
break;
}
case SILInstructionKind::AllocExistentialBoxInst:
case SILInstructionKind::InitExistentialAddrInst:
case SILInstructionKind::InitExistentialValueInst:
case SILInstructionKind::InitExistentialMetatypeInst:
case SILInstructionKind::InitExistentialRefInst: {
SILValue operand;
SILType Ty;
CanType FormalConcreteType;
ArrayRef<ProtocolConformanceRef> conformances;
switch (SI.getKind()) {
default: llvm_unreachable("out of sync with parent");
case SILInstructionKind::InitExistentialAddrInst: {
auto &IEI = cast<InitExistentialAddrInst>(SI);
operand = IEI.getOperand();
Ty = IEI.getLoweredConcreteType();
FormalConcreteType = IEI.getFormalConcreteType();
conformances = IEI.getConformances();
break;
}
case SILInstructionKind::InitExistentialValueInst: {
auto &IEOI = cast<InitExistentialValueInst>(SI);
operand = IEOI.getOperand();
Ty = IEOI.getType();
FormalConcreteType = IEOI.getFormalConcreteType();
conformances = IEOI.getConformances();
break;
}
case SILInstructionKind::InitExistentialRefInst: {
auto &IERI = cast<InitExistentialRefInst>(SI);
operand = IERI.getOperand();
Ty = IERI.getType();
FormalConcreteType = IERI.getFormalConcreteType();
conformances = IERI.getConformances();
break;
}
case SILInstructionKind::InitExistentialMetatypeInst: {
auto &IEMI = cast<InitExistentialMetatypeInst>(SI);
operand = IEMI.getOperand();
Ty = IEMI.getType();
conformances = IEMI.getConformances();
break;
}
case SILInstructionKind::AllocExistentialBoxInst: {