-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathMoveOnlyBorrowToDestructureUtils.cpp
1696 lines (1508 loc) · 69.7 KB
/
MoveOnlyBorrowToDestructureUtils.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
//===--- MoveOnlyBorrowToDestructureTransform.cpp -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
///
/// \file This is a transform that converts the borrow + gep pattern to
/// destructures or emits an error if it cannot be done. It is assumed that it
/// runs immediately before move checking of objects runs. This ensures that the
/// move checker does not need to worry about this problem and instead can just
/// check that the newly inserted destructures do not cause move only errors.
///
/// This is written as a utility so that we can have a utility pass that tests
/// this directly but also invoke this via the move only object checker.
///
/// TODO: Move this to SILOptimizer/Utils.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-move-only-checker"
#include "MoveOnlyBorrowToDestructureUtils.h"
#include "MoveOnlyDiagnostics.h"
#include "MoveOnlyObjectCheckerUtils.h"
#include "MoveOnlyTypeUtils.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/BlotSetVector.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/SIL/FieldSensitivePrunedLiveness.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallBitVector.h"
using namespace swift;
using namespace swift::siloptimizer;
using namespace swift::siloptimizer::borrowtodestructure;
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
/// Return a loc that can be used regardless if \p inst is a terminator or not.
static SILLocation getSafeLoc(SILInstruction *inst) {
if (isa<TermInst>(inst))
return RegularLocation::getDiagnosticsOnlyLocation(inst->getLoc(),
inst->getModule());
return inst->getLoc();
}
static void addCompensatingDestroys(SSAPrunedLiveness &liveness,
PrunedLivenessBoundary &boundary,
SILValue value) {
InstructionSet consumingInsts(value->getFunction());
liveness.initializeDef(value);
for (auto *use : value->getUses()) {
if (use->isConsuming())
consumingInsts.insert(use->getUser());
liveness.updateForUse(use->getUser(), use->isConsuming());
if (auto *bbi = dyn_cast<BeginBorrowInst>(use->getUser())) {
for (auto *ebi : bbi->getEndBorrows()) {
liveness.updateForUse(ebi, false /*use is consuming*/);
}
}
}
liveness.computeBoundary(boundary);
for (auto *user : boundary.lastUsers) {
// If this is a consuming inst, just continue.
if (consumingInsts.contains(user))
continue;
// Otherwise, we need to insert a destroy_value afterwards.
auto *next = user->getNextInstruction();
SILBuilderWithScope builder(next);
builder.createDestroyValue(getSafeLoc(next), value);
}
// Insert destroy_value along all boundary edges.
for (auto *edge : boundary.boundaryEdges) {
SILBuilderWithScope builder(edge->begin());
builder.createDestroyValue(getSafeLoc(&*edge->begin()), value);
}
// If we have a dead def, insert the destroy_value immediately at the def.
for (auto *deadDef : boundary.deadDefs) {
SILInstruction *nextInst = nullptr;
if (auto *inst = dyn_cast<SILInstruction>(deadDef)) {
nextInst = inst->getNextInstruction();
} else if (auto *arg = dyn_cast<SILArgument>(deadDef)) {
nextInst = arg->getNextInstruction();
} else {
llvm_unreachable("Unhandled dead def?!");
}
SILBuilderWithScope builder(nextInst);
builder.createDestroyValue(getSafeLoc(nextInst), value);
}
}
//===----------------------------------------------------------------------===//
// MARK: Available Values
//===----------------------------------------------------------------------===//
namespace {
// We reserve more bits that we need at the beginning so that we can avoid
// reallocating and potentially breaking our internal mutable array ref
// points into the data store.
struct AvailableValues {
MutableArrayRef<SILValue> values;
SILValue operator[](unsigned index) const { return values[index]; }
SILValue &operator[](unsigned index) { return values[index]; }
unsigned size() const { return values.size(); }
AvailableValues() : values() {}
AvailableValues(MutableArrayRef<SILValue> values) : values(values) {}
void print(llvm::raw_ostream &os, const char *prefix = nullptr) const;
SWIFT_DEBUG_DUMP;
};
struct AvailableValueStore {
std::vector<SILValue> dataStore;
llvm::DenseMap<SILBasicBlock *, AvailableValues> blockToValues;
unsigned nextOffset = 0;
unsigned numBits;
AvailableValueStore(const FieldSensitivePrunedLiveness &liveness)
: dataStore(liveness.getDiscoveredBlocks().size() *
liveness.getNumSubElements()),
numBits(liveness.getNumSubElements()) {}
std::pair<AvailableValues *, bool> get(SILBasicBlock *block) {
auto iter = blockToValues.try_emplace(block, AvailableValues());
if (!iter.second) {
return {&iter.first->second, false};
}
iter.first->second.values =
MutableArrayRef<SILValue>(&dataStore[nextOffset], numBits);
nextOffset += numBits;
return {&iter.first->second, true};
}
};
} // namespace
void AvailableValues::print(llvm::raw_ostream &os, const char *prefix) const {
if (prefix)
os << prefix;
os << "Dumping AvailableValues!\n";
for (auto pair : llvm::enumerate(values)) {
if (prefix)
os << prefix;
os << " values[" << pair.index() << "] = ";
if (pair.value()) {
os << *pair.value();
} else {
os << "None\n";
}
}
}
void AvailableValues::dump() const { print(llvm::dbgs(), nullptr); }
//===----------------------------------------------------------------------===//
// MARK: Private Implementation
//===----------------------------------------------------------------------===//
struct borrowtodestructure::Implementation {
BorrowToDestructureTransform &interface;
std::optional<AvailableValueStore> blockToAvailableValues;
/// The liveness that we use for all borrows or for individual switch_enum
/// arguments.
FieldSensitiveSSAPrunedLiveRange liveness;
/// The copy_value we insert upon our mark_unresolved_non_copyable_value or
/// switch_enum argument so that we have an independent owned value.
SILValue initialValue;
using InterestingUser = FieldSensitivePrunedLiveness::InterestingUser;
SmallFrozenMultiMap<SILBasicBlock *, std::pair<Operand *, InterestingUser>, 8>
blocksToUses;
/// A frozen multi-map we use to diagnose consuming uses that are used by the
/// same instruction as another consuming use or non-consuming use.
SmallFrozenMultiMap<SILInstruction *, Operand *, 8>
instToInterestingOperandIndexMap;
SmallVector<Operand *, 8> destructureNeedingUses;
Implementation(BorrowToDestructureTransform &interface,
SmallVectorImpl<SILBasicBlock *> &discoveredBlocks)
: interface(interface),
liveness(interface.mmci->getFunction(), &discoveredBlocks) {}
void clear() {
liveness.clear();
initialValue = SILValue();
}
void init(SILValue rootValue) {
clear();
liveness.init(rootValue);
liveness.initializeDef(rootValue, TypeTreeLeafTypeRange(rootValue));
}
bool gatherUses(SILValue value);
/// Once we have gathered up all of our destructure uses and liveness
/// requiring uses, validate that all of our destructure uses are on our
/// boundary. Once we have done this, we know that it is safe to perform our
/// transform.
void checkDestructureUsesOnBoundary() const;
/// Check for cases where we have two consuming uses on the same instruction
/// or a consuming/non-consuming use on the same instruction.
void checkForErrorsOnSameInstruction();
/// Rewrite all of the uses of our borrow on our borrow operand, performing
/// destructures as appropriate.
void rewriteUses(InstructionDeleter *deleter = nullptr);
void cleanup();
AvailableValues &computeAvailableValues(SILBasicBlock *block);
/// Returns mark_unresolved_non_copyable_value if we are processing borrows or
/// the enum argument if we are processing switch_enum.
SILValue getRootValue() const { return liveness.getRootValue(); }
DiagnosticEmitter &getDiagnostics() const {
return interface.diagnosticEmitter;
}
/// Always returns the actual root mark_unresolved_non_copyable_value for both
/// switch_enum args and normal borrow user checks.
MarkUnresolvedNonCopyableValueInst *getMarkedValue() const {
return interface.mmci;
}
PostOrderFunctionInfo *getPostOrderFunctionInfo() {
return interface.getPostOrderFunctionInfo();
}
IntervalMapAllocator::Allocator &getAllocator() {
return interface.allocator.get();
}
};
bool Implementation::gatherUses(SILValue value) {
LLVM_DEBUG(llvm::dbgs() << "Gathering uses for: " << *value);
StackList<Operand *> useWorklist(value->getFunction());
for (auto *use : value->getUses()) {
useWorklist.push_back(use);
}
while (!useWorklist.empty()) {
auto *nextUse = useWorklist.pop_back_val();
LLVM_DEBUG(llvm::dbgs() << " NextUse: " << *nextUse->getUser());
LLVM_DEBUG(llvm::dbgs() << " Operand Ownership: "
<< nextUse->getOperandOwnership() << '\n');
switch (nextUse->getOperandOwnership()) {
case OperandOwnership::NonUse:
continue;
// Conservatively treat a conversion to an unowned value as a pointer
// escape. If we see this in the SIL, fail and return false so we emit a
// "compiler doesn't understand error".
case OperandOwnership::ForwardingUnowned:
case OperandOwnership::PointerEscape:
LLVM_DEBUG(llvm::dbgs()
<< " Found forwarding unowned or pointer escape!\n");
return false;
// These might be uses that we need to perform a destructure or insert
// struct_extracts for.
case OperandOwnership::TrivialUse:
case OperandOwnership::InstantaneousUse:
case OperandOwnership::UnownedInstantaneousUse:
case OperandOwnership::InteriorPointer:
case OperandOwnership::AnyInteriorPointer:
case OperandOwnership::BitwiseEscape: {
// Look through copy_value of a move only value. We treat copy_value of
// copyable values as normal uses.
if (auto *cvi = dyn_cast<CopyValueInst>(nextUse->getUser())) {
if (cvi->getOperand()->getType().isMoveOnly()) {
LLVM_DEBUG(llvm::dbgs() << " Found copy value of move only "
"field... looking through!\n");
for (auto *use : cvi->getUses())
useWorklist.push_back(use);
continue;
}
// If we don't have a copy of a move only type, we just reat this as a
// normal use, so we fall through.
}
SmallVector<TypeTreeLeafTypeRange, 2> leafRanges;
TypeTreeLeafTypeRange::get(nextUse, getRootValue(), leafRanges);
if (!leafRanges.size()) {
LLVM_DEBUG(llvm::dbgs() << " Failed to compute leaf range?!\n");
return false;
}
LLVM_DEBUG(llvm::dbgs() << " Found non lifetime ending use!\n");
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
false /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
false /*is lifetime ending*/);
}
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
case OperandOwnership::ForwardingConsume:
case OperandOwnership::DestroyingConsume: {
// Ignore destroy_value, we are going to eliminate them.
if (isa<DestroyValueInst>(nextUse->getUser())) {
LLVM_DEBUG(llvm::dbgs() << " Found destroy value!\n");
continue;
}
SmallVector<TypeTreeLeafTypeRange, 2> leafRanges;
TypeTreeLeafTypeRange::get(nextUse, getRootValue(), leafRanges);
if (!leafRanges.size()) {
LLVM_DEBUG(llvm::dbgs() << " Failed to compute leaf range?!\n");
return false;
}
// Check if our use type is trivial. In such a case, just treat this as a
// liveness use.
SILType type = nextUse->get()->getType();
if (type.isTrivial(nextUse->getUser()->getFunction())) {
LLVM_DEBUG(llvm::dbgs() << " Found non lifetime ending use!\n");
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
false /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
false /*is lifetime ending*/);
}
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
LLVM_DEBUG(llvm::dbgs() << " Found lifetime ending use!\n");
destructureNeedingUses.push_back(nextUse);
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
true /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
true /*is lifetime ending*/);
}
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
case OperandOwnership::GuaranteedForwarding: {
// Always treat switches as full liveness uses of the enum being switched
// since the control flow is significant, and we can't destructure through
// the switch dispatch. If the final pattern match ends up destructuring
// the value, then SILGen emits that as a separate access.
if (auto switchEnum = dyn_cast<SwitchEnumInst>(nextUse->getUser())) {
SmallVector<TypeTreeLeafTypeRange, 2> leafRanges;
TypeTreeLeafTypeRange::get(&switchEnum->getOperandRef(), getRootValue(),
leafRanges);
if (!leafRanges.size()) {
LLVM_DEBUG(llvm::dbgs() << " Failed to compute leaf range?!\n");
return false;
}
LLVM_DEBUG(llvm::dbgs() << " Found non lifetime ending use!\n");
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
false /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
false /*is lifetime ending*/);
}
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
// Look through guaranteed forwarding if we have at least one non-trivial
// value. If we have all non-trivial values, treat this as a liveness use.
SmallVector<SILValue, 8> forwardedValues;
auto *fn = nextUse->getUser()->getFunction();
ForwardingOperand(nextUse).visitForwardedValues([&](SILValue value) {
if (value->getType().isTrivial(fn))
return true;
forwardedValues.push_back(value);
return true;
});
if (forwardedValues.empty()) {
SmallVector<TypeTreeLeafTypeRange, 2> leafRanges;
TypeTreeLeafTypeRange::get(nextUse, getRootValue(), leafRanges);
if (!leafRanges.size()) {
LLVM_DEBUG(llvm::dbgs() << " Failed to compute leaf range?!\n");
return false;
}
LLVM_DEBUG(llvm::dbgs() << " Found non lifetime ending use!\n");
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
false /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
false /*is lifetime ending*/);
}
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
// If we had at least one forwarded value that is non-trivial, we need to
// visit those uses.
while (!forwardedValues.empty()) {
for (auto *use : forwardedValues.pop_back_val()->getUses()) {
useWorklist.push_back(use);
}
}
continue;
}
case OperandOwnership::Borrow: {
if (auto *bbi = dyn_cast<BeginBorrowInst>(nextUse->getUser());
bbi && !bbi->isFixed()) {
// Look through non-fixed borrows.
LLVM_DEBUG(llvm::dbgs() << " Found recursive borrow!\n");
for (auto *use : bbi->getUses()) {
useWorklist.push_back(use);
}
continue;
}
SmallVector<TypeTreeLeafTypeRange, 2> leafRanges;
TypeTreeLeafTypeRange::get(nextUse, getRootValue(), leafRanges);
if (!leafRanges.size()) {
LLVM_DEBUG(llvm::dbgs() << " Failed to compute leaf range?!\n");
return false;
}
// Otherwise, treat it as a normal use.
LLVM_DEBUG(llvm::dbgs() << " Treating borrow as "
"a non lifetime ending use!\n");
for (auto leafRange : leafRanges) {
blocksToUses.insert(nextUse->getParentBlock(),
{nextUse,
{liveness.getNumSubElements(), leafRange,
false /*is lifetime ending*/}});
liveness.updateForUse(nextUse->getUser(), leafRange,
false /*is lifetime ending*/);
}
// The liveness extends to the scope-ending uses of the borrow.
//
// FIXME: this ignores visitScopeEndingUses failure, which may result from
// unknown uses or dead borrows.
BorrowingOperand(nextUse).visitScopeEndingUses([&](Operand *end) -> bool {
if (end->getOperandOwnership() == OperandOwnership::Reborrow) {
return false;
}
if (PhiOperand(end)) {
assert(end->getOperandOwnership() ==
OperandOwnership::ForwardingConsume);
return false;
}
LLVM_DEBUG(llvm::dbgs() << " ++ Scope-ending use: ";
end->getUser()->print(llvm::dbgs()));
for (auto leafRange : leafRanges) {
liveness.updateForUse(end->getUser(), leafRange,
false /*is lifetime ending*/);
}
return true;
});
instToInterestingOperandIndexMap.insert(nextUse->getUser(), nextUse);
continue;
}
case OperandOwnership::EndBorrow:
LLVM_DEBUG(llvm::dbgs() << " Found end borrow!\n");
continue;
case OperandOwnership::Reborrow:
llvm_unreachable("Unsupported for now?!");
}
}
return true;
}
void Implementation::checkForErrorsOnSameInstruction() {
// At this point, we have emitted all boundary checks. We also now need to
// check if any of our consuming uses that are on the boundary are used by the
// same instruction as a different consuming or non-consuming use.
instToInterestingOperandIndexMap.setFrozen();
SmallBitVector usedBits(liveness.getNumSubElements());
for (auto instRangePair : instToInterestingOperandIndexMap.getRange()) {
SWIFT_DEFER { usedBits.reset(); };
// First loop through our uses and handle any consuming twice errors. We
// also setup usedBits to check for non-consuming uses that may overlap.
Operand *badOperand = nullptr;
std::optional<TypeTreeLeafTypeRange> badRange;
for (auto *use : instRangePair.second) {
if (!use->isConsuming())
continue;
SmallVector<TypeTreeLeafTypeRange, 2> destructureUseSpans;
TypeTreeLeafTypeRange::get(use, getRootValue(), destructureUseSpans);
assert(destructureUseSpans.size() == 1);
auto destructureUseSpan = destructureUseSpans[0];
for (unsigned index : destructureUseSpan.getRange()) {
if (usedBits[index]) {
// If we get that we used the same bit twice, we have an error. We set
// the badIndex error and break early.
badOperand = use;
badRange = destructureUseSpan;
break;
}
usedBits[index] = true;
}
// If we set badOperand, break so we can emit an error for this
// instruction.
if (badOperand)
break;
}
// If we did not set badIndex for consuming uses, we did not have any
// conflicts among consuming uses. see if we have any conflicts with
// non-consuming uses. Otherwise, we continue.
if (!badOperand) {
for (auto *use : instRangePair.second) {
if (use->isConsuming())
continue;
SmallVector<TypeTreeLeafTypeRange, 2> destructureUseSpans;
TypeTreeLeafTypeRange::get(use, getRootValue(), destructureUseSpans);
assert(destructureUseSpans.size() == 1);
auto destructureUseSpan = destructureUseSpans[0];
for (unsigned index : destructureUseSpan.getRange()) {
if (!usedBits[index])
continue;
// If we get that we used the same bit twice, we have an error. We set
// the badIndex error and break early.
badOperand = use;
badRange = destructureUseSpan;
break;
}
// If we set badOperand, break so we can emit an error for this
// instruction.
if (badOperand)
break;
}
// If we even did not find a non-consuming use that conflicts, then
// continue.
if (!badOperand)
continue;
}
// If badIndex is set, we broke out of the inner loop and need to emit an
// error. Use a little more compile time to identify the other operand that
// caused the failure. NOTE: badOperand /could/ be a non-consuming use, but
// the use we are identifying here will always be consuming.
usedBits.reset();
// Reinitialize use bits with the bad bits.
for (unsigned index : badRange->getRange())
usedBits[index] = true;
// Now loop back through looking for the original operand that set the used
// bits. This will always be a consuming use.
for (auto *use : instRangePair.second) {
if (!use->isConsuming())
continue;
SmallVector<TypeTreeLeafTypeRange, 2> destructureUseSpans;
TypeTreeLeafTypeRange::get(use, getRootValue(), destructureUseSpans);
assert(destructureUseSpans.size() == 1);
auto destructureUseSpan = destructureUseSpans[0];
bool emittedError = false;
for (unsigned index : destructureUseSpan.getRange()) {
if (!usedBits[index])
continue;
if (badOperand->isConsuming())
getDiagnostics().emitObjectInstConsumesValueTwice(getMarkedValue(),
use, badOperand);
else
getDiagnostics().emitObjectInstConsumesAndUsesValue(getMarkedValue(),
use, badOperand);
emittedError = true;
}
// Once we have emitted the error, just break out of the loop.
if (emittedError)
break;
}
}
}
void Implementation::checkDestructureUsesOnBoundary() const {
LLVM_DEBUG(llvm::dbgs() << "Checking destructure uses on boundary!\n");
// Now that we have found all of our destructure needing uses and liveness
// needing uses, make sure that none of our destructure needing uses are
// within our boundary. If so, we have an automatic error since we have a
// use-after-free.
for (auto *use : destructureNeedingUses) {
LLVM_DEBUG(llvm::dbgs()
<< " DestructureNeedingUse: " << *use->getUser());
SmallVector<TypeTreeLeafTypeRange, 2> destructureUseSpans;
TypeTreeLeafTypeRange::get(use, getRootValue(), destructureUseSpans);
assert(destructureUseSpans.size() == 1);
auto destructureUseSpan = destructureUseSpans[0];
SmallBitVector destructureUseBits(liveness.getNumSubElements());
destructureUseSpan.setBits(destructureUseBits);
if (!liveness.isWithinBoundary(use->getUser(), destructureUseBits)) {
LLVM_DEBUG(llvm::dbgs()
<< " On boundary or within boundary! No error!\n");
continue;
}
// Emit an error. We have a use after free.
//
// NOTE: Since we are going to emit an error here, we do the boundary
// computation to ensure that we only do the boundary computation once:
// when we emit an error or once we know we need to do rewriting.
//
// TODO: Fix diagnostic to use destructure needing use and boundary
// uses.
LLVM_DEBUG(llvm::dbgs() << " Within boundary! Emitting error!\n");
FieldSensitivePrunedLivenessBoundary boundary(liveness.getNumSubElements());
liveness.computeBoundary(boundary);
getDiagnostics().emitObjectDestructureNeededWithinBorrowBoundary(
getMarkedValue(), use->getUser(), destructureUseSpan, boundary);
}
}
#ifndef NDEBUG
static void dumpSmallestTypeAvailable(
SmallVectorImpl<std::optional<std::pair<TypeOffsetSizePair, SILType>>>
&smallestTypeAvailable) {
LLVM_DEBUG(llvm::dbgs() << " Dumping smallest type available!\n");
for (auto pair : llvm::enumerate(smallestTypeAvailable)) {
LLVM_DEBUG(llvm::dbgs() << " value[" << pair.index() << "] = ");
if (!pair.value()) {
LLVM_DEBUG(llvm::dbgs() << "None\n");
continue;
}
auto value = *pair.value();
LLVM_DEBUG(llvm::dbgs() << "Span: " << value.first
<< ". Type: " << value.second << '\n');
}
}
#endif
/// When we compute available values, we have a few constraints:
///
/// 1. We want to be sure that we destructure as /late/ as possible. This
/// ensures that we match at the source level the assumption by users that they
/// can use entire valid parts as late as possible. If we were to do it earlier
/// we would emit errors too early.
AvailableValues &Implementation::computeAvailableValues(SILBasicBlock *block) {
LLVM_DEBUG(llvm::dbgs() << " Computing Available Values For bb"
<< block->getDebugID() << '\n');
// First grab our block. If we already have state for the block, just return
// its available values. We already computed the available values and
// potentially updated it with new destructured values for our block.
auto pair = blockToAvailableValues->get(block);
if (!pair.second) {
LLVM_DEBUG(llvm::dbgs()
<< " Already have values! Returning them!\n");
LLVM_DEBUG(pair.first->print(llvm::dbgs(), " "));
return *pair.first;
}
LLVM_DEBUG(llvm::dbgs() << " No values computed! Initializing!\n");
auto &newValues = *pair.first;
// Otherwise, we need to initialize our available values with predecessor
// information.
// First check if the block is the one associated with our mark must check
// inst. If we are in this block, set all available value bits to our initial
// value which is a copy_value of \p initial value. We add the copy_value to
// ensure that from an OSSA perspective any any destructures we insert are
// independent of any other copies. We assume that OSSA canonicalization will
// remove the extra copy later after we run or emit an error if it can't.
if (block == getRootValue()->getParentBlock()) {
LLVM_DEBUG(llvm::dbgs()
<< " In initial block, setting to initial value!\n");
for (unsigned i : indices(newValues))
newValues[i] = initialValue;
LLVM_DEBUG(newValues.print(llvm::dbgs(), " "));
return newValues;
}
// Otherwise, we need to handle predecessors. Our strategy is to loop over all
// predecessors and:
//
// 1. If we have the same value along all predecessors, for a specific bit, we
// just let it through.
//
// 2. If we find values that describe the same set of set bits and they only
// describe those bits, we phi them together.
//
// 3. If we find a value that is unavailable along one of the other paths but
// /could/ be destructured such that we could phi the destructured value, we
// destructure the value in the predecessor and use that for our phi.
//
// 4. We assume optimistically that loop back-edge predecessors always contain
// all available values that come into the loop. The reason why this is true
// is that we know that either:
//
// a. Our value either begins within a loop meaning that we either never
// seen the back edge or the back edge block is where our mark must check
// inst is so we won't visit the back edge.
//
// b. Our mark must check block is further up the loop nest than the loop
// back edge implying if we were to destructure in the loop, we would
// destructure multiple times. This would have then resulted in a liveness
// error in the liveness check we ran earlier, resulting in us not running
// this transformation.
struct SkipBackEdgeFilter {
unsigned targetBlockRPO;
SILBasicBlock::pred_iterator pe;
PostOrderFunctionInfo *pofi;
SkipBackEdgeFilter(SILBasicBlock *block, PostOrderFunctionInfo *pofi)
: targetBlockRPO(*pofi->getRPONumber(block)), pe(block->pred_end()),
pofi(pofi) {}
std::optional<SILBasicBlock *> operator()(SILBasicBlock *predBlock) const {
// If our predecessor block has a larger RPO number than our target block,
// then their edge must be a backedge.
if (targetBlockRPO < *pofi->getRPONumber(predBlock))
return std::nullopt;
return predBlock;
}
};
auto predsSkippingBackEdges = makeOptionalTransformRange(
llvm::make_range(block->pred_begin(), block->pred_end()),
SkipBackEdgeFilter(block, getPostOrderFunctionInfo()));
// Loop over all available values for all predecessors and determine for each
// sub-element number the smallest type over all available values if we have
// an available value for each predecessor. This is implemented by storing an
// Optional<TypeOffsetSizePair> in an array for each available value. If we
// find any predecessor without an available value at all for that entry, we
// set the Optional to be none. Otherwise, we intersect each
// TypeOffsetSizePair derived from each available value by always taking the
// smaller TypeOffsetSizePair. We know by construction that we always will
// move down the type tree, not up the type tree (see NOTE 2 below).
//
// NOTE: Given a parent type and a child type which is the only child of the
// parent type, we always mathematically take the top type. If we have to
// later destructure an additional time to wire up a use, we do it at the
// use site when we wire it up. When phi-ing/destructuring, we hide it from
// the algorithm. This allows us to keep the invariant that our type in size
// is always absolutely decreasing in size.
//
// NOTE 2: We can only move up the type tree by calling a constructor which is
// always a +1 operation that is treated as a consuming operation end
// point. In Swift at the source level, we never construct aggregates in a
// forwarding guaranteed manner for move only types.
LLVM_DEBUG(llvm::dbgs() << " Computing smallest type available for "
"available values for block bb"
<< block->getDebugID() << '\n');
SmallVector<std::optional<std::pair<TypeOffsetSizePair, SILType>>, 8>
smallestTypeAvailable;
{
auto pi = predsSkippingBackEdges.begin();
auto pe = predsSkippingBackEdges.end();
assert(pi != pe && "If initial block then should have been the mark must "
"check inst block?!");
{
auto *bb = *pi;
LLVM_DEBUG(llvm::dbgs() << " Visiting first block bb"
<< bb->getDebugID() << '\n');
LLVM_DEBUG(llvm::dbgs()
<< " Recursively loading its available values to "
"compute initial smallest type available for block bb"
<< block->getDebugID() << '\n');
auto &predAvailableValues = computeAvailableValues(bb);
LLVM_DEBUG(
llvm::dbgs()
<< " Computing initial smallest type available for block bb"
<< block->getDebugID() << '\n');
for (unsigned i : range(predAvailableValues.size())) {
if (predAvailableValues[i])
smallestTypeAvailable.push_back(
{{TypeOffsetSizePair(predAvailableValues[i], getRootValue()),
predAvailableValues[i]->getType()}});
else
smallestTypeAvailable.emplace_back(std::nullopt);
}
LLVM_DEBUG(llvm::dbgs() << " Finished computing initial smallest "
"type available for block bb"
<< block->getDebugID() << '\n';
dumpSmallestTypeAvailable(smallestTypeAvailable));
}
LLVM_DEBUG(llvm::dbgs()
<< " Visiting rest of preds and intersecting for block bb"
<< block->getDebugID() << '\n');
for (auto ppi = std::next(pi); ppi != pe; ++ppi) {
auto *bb = *ppi;
LLVM_DEBUG(llvm::dbgs() << " Computing smallest type for bb"
<< bb->getDebugID() << '\n');
LLVM_DEBUG(llvm::dbgs()
<< " Recursively loading its available values!\n");
auto &predAvailableValues = computeAvailableValues(bb);
for (unsigned i : range(predAvailableValues.size())) {
if (!smallestTypeAvailable[i].has_value())
continue;
if (!predAvailableValues[i]) {
smallestTypeAvailable[i] = std::nullopt;
continue;
}
// Since we assume all types in the type tree for our purposes are
// absolutely monotonically decreasing in size from their parent (noting
// the NOTE above), we know that if subElt has a smaller size than our
// accumulator, then it must be further down the type tree from our
// accumulator.
auto offsetSize =
TypeOffsetSizePair(predAvailableValues[i], getRootValue());
if (smallestTypeAvailable[i]->first.size > offsetSize.size)
smallestTypeAvailable[i] = {offsetSize,
predAvailableValues[i]->getType()};
}
LLVM_DEBUG(llvm::dbgs() << " Smallest type available after "
"intersecting with block!\n");
LLVM_DEBUG(dumpSmallestTypeAvailable(smallestTypeAvailable));
}
}
// At this point, in smallestValueAvailable, we have for each phi slot the
// smallest size element needed. Now we go through our predecessors again,
// destructuring available values to match the smallest value needed. If we
// destructure a larger value, we always update any other available values we
// are propagating for it using an interval map over the type offsets.
LLVM_DEBUG(
llvm::dbgs()
<< " Destructuring available values in preds to smallest size for bb"
<< block->getDebugID() << '\n');
auto *fn = block->getFunction();
IntervalMapAllocator::Map typeSpanToValue(getAllocator());
for (auto *predBlock : predsSkippingBackEdges) {
SWIFT_DEFER { typeSpanToValue.clear(); };
auto &predAvailableValues = computeAvailableValues(predBlock);
// First go through our available values and initialize our interval map. We
// should never fail to insert. We want to insert /all/ available values so
// we can update values that may not be available along other paths if we
// destructure.
for (unsigned i : range(predAvailableValues.size())) {
if (auto value = predAvailableValues[i]) {
// We check later that we store entire values.
typeSpanToValue.insert(i, i + 1, value);
}
}
// Now walk through our available values and chop up the contents of our
// interval map to fit our smallest offset size.
for (unsigned i : range(predAvailableValues.size())) {
// If we do not have an offset size for this available value, just
// continue, we do not need to perform any destructuring.
//
// NOTE: If we do not have an available value for this element, then we
// will already not have a smallest type available due to our earlier
// work.
auto smallestOffsetSize = smallestTypeAvailable[i];
if (!smallestOffsetSize)
continue;
// Otherwise, compute the offsetSize for the value associated with this
// offset in the interval map. If the value is already the correct size,
// just continue, we do not need to perform any destructuring.
auto iter = typeSpanToValue.find(i);
assert(iter != typeSpanToValue.end());
auto iterValue = iter.value();
auto iterOffsetSize = TypeOffsetSizePair(iterValue, getRootValue());
if (smallestOffsetSize->first.size == iterOffsetSize.size) {
// Our value should already be in the interval map.
assert(iter.start() == iterOffsetSize.startOffset &&
iter.stop() == iterOffsetSize.getEndOffset() &&
"We should always store entire values");
continue;
}
// Otherwise, we need to destructure the value. Our overall plan is that
// we walk down the type tree, destructuring as we go.
//
// NOTE: We do not actually update our available values here since a later
// smallest offset size could result in further destructuring that an
// earlier value required. Instead, we do a final loop afterwards using
// the interval map to update each available value.
auto iterType = iterValue->getType();
auto loc = getSafeLoc(predBlock->getTerminator());
SILBuilderWithScope builder(predBlock->getTerminator());
while (smallestOffsetSize->first.size < iterOffsetSize.size) {
TypeOffsetSizePair childOffsetSize;
SILType childType;
// We are returned an optional here and should never fail... so use a
// force unwrap.
std::tie(childOffsetSize, childType) =
*iterOffsetSize.walkOneLevelTowardsChild(iterOffsetSize, iterType,
fn);
// Before we destructure ourselves, erase our entire value from the
// map. We do not need to consider the possibility of there being holes
// in our range since we always store values whole to their entire
// subelement range. If we lose a single bit of the value, we split it
// until we again have whole values.
{
auto iter = typeSpanToValue.find(i);
assert(iter.start() == iterOffsetSize.startOffset &&
iter.stop() == iterOffsetSize.getEndOffset() &&
"We should always store complete values");
iter.erase();
}
// Then perform our destructuring.
unsigned childOffsetIterator = iterOffsetSize.startOffset;
builder.emitDestructureValueOperation(
loc, predAvailableValues[i], [&](unsigned index, SILValue value) {
// Now, wire up our new value to its span in the interval map.
TypeSubElementCount childSize(value);
typeSpanToValue.insert(childOffsetIterator, childSize, value);
// Update childOffsetIterator so it points at our next child.
childOffsetIterator += childSize;
});
}
}
LLVM_DEBUG(llvm::dbgs()
<< " Updating available values for bb"
<< predBlock->getDebugID() << "\n Before Update:\n");
LLVM_DEBUG(predAvailableValues.print(llvm::dbgs(), " "));
// Now do one final loop updating our available values using the interval
// map.
for (unsigned i : range(predAvailableValues.size())) {
auto iter = typeSpanToValue.find(i);
if (iter == typeSpanToValue.end() || iter.start() > i ||
iter.stop() <= i) {
predAvailableValues[i] = SILValue();
} else {
predAvailableValues[i] = iter.value();
}
}
LLVM_DEBUG(llvm::dbgs() << " After Update:\n");
LLVM_DEBUG(predAvailableValues.print(llvm::dbgs(), " "));
}
LLVM_DEBUG(llvm::dbgs() << " Inserting phis if needed for bb"
<< block->getDebugID() << '\n');
// At this point, all of our values should be the "appropriate size". Now we
// need to perform the actual phi-ing.
InstructionDeleter deleter;
for (unsigned i = 0, e = smallestTypeAvailable.size(); i != e; ++i) {
// If we don't have a smallest value computed for this, this is not a value