-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathConsumeOperatorCopyableAddressesChecker.cpp
2684 lines (2361 loc) · 103 KB
/
ConsumeOperatorCopyableAddressesChecker.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
//===--- ConsumeOperatorCopyableAddressChecker.cpp ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
///
/// NOTE: This pass is assumed to run before all memory optimizations that
/// manipulate the lifetimes of values in memory such as any of the -Onone
/// predictable memory optimizations. allocbox to stack is ok since it doesn't
/// effect the actual memory itself, just whether the memory is boxed or not.
///
/// In this file, we implement a checker that for memory objects in SIL checks
/// that after a call to _move, one can no longer use a var or a let with an
/// address only type. If you use it after that point, but before a known
/// destroy point, you get an error. Example:
///
/// var x = Class()
/// let y = _move(x)
/// _use(x) // error!
/// x = Class()
/// _use(x) // Ok, we reinitialized the memory.
///
/// Below, I describe in detail the algorithm. NOTE: The design below will be
/// updated to support inits once we actually support vars. Currently, we only
/// support lets.
///
/// # Design
///
/// ## Introduction
///
/// At its heart this checker is a dataflow checker that first understands the
/// lifetime of a specific address and then optimizes based off of that
/// information. It uses AccessUseVisitor to reliably get all users of an
/// address. Then it partitions those uses into three sets:
///
/// * A set of mark_unresolved_move_addr. A mark_unresolved_move_addr is an
/// instruction that marks an invocation by _move on a value. Since we have
/// not yet proven using dataflow that it can be a move, semantically this
/// instruction is actually a copy_addr [init] so we maintain a valid IR if
/// we have uses later that we want to error upon. This is where we always
/// begin tracking dataflow.
///
/// * A set of destroy_value operations. These are points where we stop
/// tracking dataflow.
///
/// * A set of misc uses that just require liveness, We call the last category
/// "livenessUses". These are the uses that can not exist in between the move
/// and the destroy_addr operation and if we see any, we emit an error to the
/// user.
///
/// ## Gathering information to prepare for the Dataflow
///
/// We perform several different dataflow operations:
///
/// 1. First mark_unresolved_move_addr are propagated downwards to determine if
/// they propagate downwards out of blocks. When this is done, we perform the
/// single basic block form of this diagnostic. If we emit a diagnostic while
/// doing that, we exit. Otherwise, we know that there must not be any uses
/// or consumes in the given block, so it propagates move out.
///
/// 2. Then mark_unresolved_move_addr and all liveness uses are propagated up to
/// determine if a block propagates liveness up. We always use the earliest
/// user in the block. Once we find that user, we insert it into a
/// DenseMap<SILBasicBlock *, SILInstruction *>. This is so we can emit a
/// nice diagnostic.
///
/// 3. Then we propagate destroy_addr upwards stopping if we see an init. If we
/// do not see an init, then we know that we propagated that destroy upward
/// out of the block. We then insert that into a DenseMap<SILBasicBlock *,
/// DestroyAddrInst *> we are maintaining. NOTE: We do not need to check for
/// moves here since any move in our block would have either resulted in the
/// destroy_addr being eliminated earlier by the single block form of the
/// diagnostic and us exiting early or us emitting an error diagnostic and
/// exiting early.
///
/// NOTE: The reason why we do not track init information on a per block is that
/// in our dataflow, we are treating inits as normal uses and if we see an init
/// without seeing a destroy_addr, we will error on the use and bail. Once we
/// decide to support vars, this will change.
///
/// NOTE: The reason why we do not track all consuming operations, just destroy
/// operations is that instead we are treating a consuming operation as a
/// liveness use. Since we are always going to just exit on the first error for
/// any specific move (all moves will be checked individually of course), we
/// know that we will stop processing blocks at that point.
///
/// ## Performing the Global Dataflow
///
/// Finally using this information we gathered above, for each markMoveAddrOut
/// block individually, we walk the CFG downwards starting with said block's
/// successors looking for liveness uses and destroy_addr blocks.
///
/// 1. If we visit any "liveness block", immediately emit an error diagnostic as
/// the user requested and return. We can not convert the
/// mark_unresolved_move_addr into a move safely.
///
/// 2. If we visit a DestroyAddr block instead, we mark the destroy_addr as
/// being a destroy_addr that is associated with a move. This is done a per
/// address basis.
///
/// Once we have finished visiting mark_unresolved_move_addr, if we found /any/
/// mark_unresolved_move_addr that were safe to convert to a take (and that we
/// did convert to a take), we need to then cleanup destroys.
///
/// ## Cleaning up Destroys
///
/// We do this simultaneously for all of the mark_unresolved_move_addr applied
/// to a single address. Specifically, we place into a worklist all of the
/// predecessor blocks of all destroy_addr blocks that we found while performing
/// global dataflow. Then for each block b until we run out of blocks:
///
/// 1. If b is a block associated with one of our converted
/// mark_unresolved_move_addr, continue. Along that path, we are shortening
/// the lifetime of the address as requested by the user.
///
/// 2. Then we check if b is a block that was not visited when processing the
/// new moves. In such a case, we have found the dominance frontier of one or
/// many of the moves and insert a destroy_addr at the end of the b and
/// continue.
///
/// 3. Finally, if b is not on our dominance frontier and isn't a stopping
/// point, we add its predecessors to the worklist and continue.
///
/// Once these steps have been completed, we delete all of the old destroy_addr
/// since the lifetime of the address has now been handled appropriately along
/// all paths through the program.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-consume-operator-copyable-addresses-checker"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/BlotSetVector.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/GraphNodeWorklist.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILCloner.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/ClosureScope.h"
#include "swift/SILOptimizer/Analysis/LoopAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "llvm/ADT/PointerEmbeddedInt.h"
#include "llvm/ADT/PointerSumType.h"
using namespace swift;
static llvm::cl::opt<bool> DisableUnhandledConsumeOperator(
"sil-consume-operator-disable-unknown-moveaddr-diagnostic");
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
template <typename... T, typename... U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
U &&...args) {
Context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
static SourceLoc getSourceLocFromValue(SILValue value) {
if (auto *defInst = value->getDefiningInstruction())
return defInst->getLoc().getSourceLoc();
if (auto *arg = dyn_cast<SILFunctionArgument>(value))
return arg->getDecl()->getLoc();
llvm_unreachable("Do not know how to get source loc for value?!");
}
#ifndef NDEBUG
static void dumpBitVector(llvm::raw_ostream &os, const SmallBitVector &bv) {
for (unsigned i = 0; i < bv.size(); ++i) {
os << (bv[i] ? '1' : '0');
}
}
#endif
/// Returns true if a value has one or zero debug uses.
static bool hasMoreThanOneDebugUse(SILValue v) {
auto Range = getDebugUses(v);
auto i = Range.begin(), e = Range.end();
if (i == e)
return false;
++i;
return i != e;
}
//===----------------------------------------------------------------------===//
// Forward Declarations
//===----------------------------------------------------------------------===//
namespace {
enum class DownwardScanResult {
Invalid,
Destroy,
Reinit,
// NOTE: We use UseForDiagnostic both for defer uses and normal uses.
UseForDiagnostic,
MoveOut,
ClosureConsume,
ClosureUse,
};
struct ClosureOperandState {
/// This is the downward scan result that visiting a full applysite of this
/// closure will effect on the address being analyzed.
DownwardScanResult result = DownwardScanResult::Invalid;
/// Instructions that act as consumes in the closure callee. This is the set
/// of earliest post dominating consumes that should be eliminated in the
/// cloned callee. Only set if state is upwards consume.
TinyPtrVector<SILInstruction *> pairedConsumingInsts;
/// The set of instructions in the callee that are uses that require the move
/// to be alive. Only set if state is upwards use.
TinyPtrVector<SILInstruction *> pairedUseInsts;
/// The single debug value in the closure callee that we sink to the reinit
/// points.
DebugValueInst *singleDebugValue = nullptr;
bool isUpwardsUse() const { return result == DownwardScanResult::ClosureUse; }
bool isUpwardsConsume() const {
return result == DownwardScanResult::ClosureConsume;
}
};
} // namespace
/// Is this a reinit instruction that we know how to convert into its init form.
static bool isReinitToInitConvertibleInst(Operand *memUse) {
auto *memInst = memUse->getUser();
switch (memInst->getKind()) {
default:
return false;
case SILInstructionKind::CopyAddrInst: {
auto *cai = cast<CopyAddrInst>(memInst);
return !cai->isInitializationOfDest();
}
case SILInstructionKind::StoreInst: {
auto *si = cast<StoreInst>(memInst);
return si->getOwnershipQualifier() == StoreOwnershipQualifier::Assign;
}
}
}
static void convertMemoryReinitToInitForm(SILInstruction *memInst) {
switch (memInst->getKind()) {
default:
llvm_unreachable("unsupported?!");
case SILInstructionKind::CopyAddrInst: {
auto *cai = cast<CopyAddrInst>(memInst);
cai->setIsInitializationOfDest(IsInitialization_t::IsInitialization);
return;
}
case SILInstructionKind::StoreInst: {
auto *si = cast<StoreInst>(memInst);
si->setOwnershipQualifier(StoreOwnershipQualifier::Init);
return;
}
}
}
//===----------------------------------------------------------------------===//
// Use State
//===----------------------------------------------------------------------===//
namespace {
struct UseState {
SILValue address;
SmallVector<MarkUnresolvedMoveAddrInst *, 1> markMoves;
SmallPtrSet<SILInstruction *, 1> seenMarkMoves;
llvm::SmallSetVector<SILInstruction *, 2> inits;
llvm::SmallSetVector<SILInstruction *, 4> livenessUses;
SmallBlotSetVector<DestroyAddrInst *, 4> destroys;
llvm::SmallDenseMap<SILInstruction *, unsigned, 4> destroyToIndexMap;
SmallBlotSetVector<SILInstruction *, 4> reinits;
llvm::SmallDenseMap<SILInstruction *, unsigned, 4> reinitToIndexMap;
llvm::SmallMapVector<Operand *, ClosureOperandState, 1> closureUses;
llvm::SmallDenseMap<Operand *, unsigned, 1> closureOperandToIndexMap;
void insertMarkUnresolvedMoveAddr(MarkUnresolvedMoveAddrInst *inst) {
if (!seenMarkMoves.insert(inst).second)
return;
markMoves.emplace_back(inst);
}
void insertDestroy(DestroyAddrInst *dai) {
destroyToIndexMap[dai] = destroys.size();
destroys.insert(dai);
}
void insertReinit(SILInstruction *inst) {
reinitToIndexMap[inst] = reinits.size();
reinits.insert(inst);
}
void insertClosureOperand(Operand *op) {
closureOperandToIndexMap[op] = closureUses.size();
closureUses[op] = {};
}
void clear() {
address = SILValue();
markMoves.clear();
seenMarkMoves.clear();
inits.clear();
livenessUses.clear();
destroys.clear();
destroyToIndexMap.clear();
reinits.clear();
reinitToIndexMap.clear();
closureUses.clear();
closureOperandToIndexMap.clear();
}
SILFunction *getFunction() const { return address->getFunction(); }
};
} // namespace
//===----------------------------------------------------------------------===//
// Dataflow
//===----------------------------------------------------------------------===//
/// Returns true if we are move out, false otherwise. If we find an interesting
/// inst, we return it in foundInst. If no inst is returned, one must continue.
static DownwardScanResult
downwardScanForMoveOut(MarkUnresolvedMoveAddrInst *mvi, UseState &useState,
SILInstruction **foundInst, Operand **foundOperand,
TinyPtrVector<SILInstruction *> &foundClosureInsts) {
// Forward scan looking for uses or reinits.
for (auto &next : llvm::make_range(std::next(mvi->getIterator()),
mvi->getParent()->end())) {
LLVM_DEBUG(llvm::dbgs() << "DownwardScan. Checking: " << next);
// If we hit a non-destroy_addr, then we immediately know that we found an
// error. Return the special result with the next stashed within it.
if (useState.livenessUses.count(&next) ||
useState.seenMarkMoves.count(&next) || useState.inits.count(&next)) {
// Emit a diagnostic error and process the next mark_unresolved_move_addr.
LLVM_DEBUG(llvm::dbgs() << "SingleBlock liveness user: " << next);
*foundInst = &next;
return DownwardScanResult::UseForDiagnostic;
}
{
auto iter = useState.reinitToIndexMap.find(&next);
if (iter != useState.reinitToIndexMap.end()) {
LLVM_DEBUG(llvm::dbgs() << "DownwardScan: reinit: " << next);
*foundInst = &next;
return DownwardScanResult::Reinit;
}
}
// If we see a destroy_addr, then stop processing since it pairs directly
// with our move.
{
auto iter = useState.destroyToIndexMap.find(&next);
if (iter != useState.destroyToIndexMap.end()) {
auto *dai = cast<DestroyAddrInst>(iter->first);
LLVM_DEBUG(llvm::dbgs() << "DownwardScan: Destroy: " << *dai);
*foundInst = dai;
return DownwardScanResult::Destroy;
}
}
// Finally check if we have a closure user that we were able to handle.
if (auto fas = FullApplySite::isa(&next)) {
LLVM_DEBUG(llvm::dbgs() << "DownwardScan: ClosureCheck: " << **fas);
for (auto &op : fas.getArgumentOperands()) {
auto iter = useState.closureUses.find(&op);
if (iter == useState.closureUses.end()) {
continue;
}
LLVM_DEBUG(llvm::dbgs()
<< "DownwardScan: ClosureCheck: Matching Operand: "
<< fas.getAppliedArgIndex(op));
*foundInst = &next;
*foundOperand = &op;
switch (iter->second.result) {
case DownwardScanResult::Invalid:
case DownwardScanResult::Destroy:
case DownwardScanResult::Reinit:
case DownwardScanResult::UseForDiagnostic:
case DownwardScanResult::MoveOut:
llvm_unreachable("unhandled");
case DownwardScanResult::ClosureConsume:
LLVM_DEBUG(llvm::dbgs() << ". ClosureConsume.\n");
llvm::copy(iter->second.pairedConsumingInsts,
std::back_inserter(foundClosureInsts));
break;
case DownwardScanResult::ClosureUse:
LLVM_DEBUG(llvm::dbgs() << ". ClosureUse.\n");
llvm::copy(iter->second.pairedUseInsts,
std::back_inserter(foundClosureInsts));
break;
}
return iter->second.result;
}
}
}
// We are move out!
LLVM_DEBUG(llvm::dbgs() << "DownwardScan. We are move out!\n");
return DownwardScanResult::MoveOut;
}
/// Scan backwards from \p inst to the beginning of its parent block looking for
/// uses. We return true if \p inst is the first use that we are tracking for
/// the given block. This means it propagates liveness upwards through the CFG.
///
/// This works only for an instruction expected to be a normal use.
static bool upwardScanForUseOut(SILInstruction *inst, UseState &useState) {
// We scan backwards from the instruction before \p inst to the beginning of
// the block.
for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
inst->getParent()->rend())) {
// If we hit another liveness use, then this isn't the first use in the
// block. We want to store only the first use in the block. In such a case,
// we bail since when we visit that earlier instruction, we will do the
// appropriate check.
if (useState.livenessUses.contains(&iter))
// If we are not tracking a destroy, we stop at liveness uses. If we have
// a destroy_addr, we use the destroy blocks to ignore the liveness uses
// since we use the destroy_addr to signal we should stop tracking when we
// use dataflow and to pair/delete with a move.
return false;
if (useState.destroyToIndexMap.count(&iter))
return false;
if (auto *mmai = dyn_cast<MarkUnresolvedMoveAddrInst>(&iter))
if (useState.seenMarkMoves.count(mmai))
return false;
if (useState.inits.contains(&iter))
return false;
if (useState.reinitToIndexMap.count(&iter))
return false;
if (auto fas = FullApplySite::isa(&iter)) {
for (auto &op : fas.getArgumentOperands()) {
if (useState.closureUses.find(&op) != useState.closureUses.end())
return false;
}
}
}
return true;
}
/// Scan backwards from \p inst to the beginning of its parent block looking for
/// uses. We return true if \p inst is the first use that we are tracking for
/// the given block. This means it propagates liveness upwards through the CFG.
static bool upwardScanForDestroys(SILInstruction *inst, UseState &useState) {
// We scan backwards from the instruction before \p inst to the beginning of
// the block.
for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
inst->getParent()->rend())) {
// If we find a destroy_addr earlier in the block, do not mark this block as
// being associated with this destroy. We always want to associate the move
// with the earliest destroy_addr.
if (useState.destroyToIndexMap.count(&iter))
return false;
if (useState.reinitToIndexMap.count(&iter))
return false;
// If we see an init, then we return found other use to not track this
// destroy_addr up since it is balanced by the init.
if (useState.inits.contains(&iter))
return false;
if (auto fas = FullApplySite::isa(&iter)) {
for (auto &op : fas.getArgumentOperands()) {
if (useState.closureUses.find(&op) != useState.closureUses.end())
return false;
}
}
// Otherwise, we have a normal use, just ignore it.
}
// Ok, this instruction is the first use in the block of our value. So return
// true so we track it as such.
return true;
}
/// Search for the first init in the block.
static bool upwardScanForInit(SILInstruction *inst, UseState &useState) {
// We scan backwards from the instruction before \p inst to the beginning of
// the block.
for (auto &iter : llvm::make_range(std::next(inst->getReverseIterator()),
inst->getParent()->rend())) {
if (useState.inits.contains(&iter))
return false;
if (auto fas = FullApplySite::isa(&iter)) {
for (auto &op : fas.getArgumentOperands()) {
if (useState.closureUses.find(&op) != useState.closureUses.end())
return false;
}
}
}
return true;
}
//===----------------------------------------------------------------------===//
// Closure Argument Global Dataflow
//===----------------------------------------------------------------------===//
namespace {
/// A utility class that analyzes a closure that captures a moved value. It is
/// used to perform move checking within the closure as well as to determine a
/// set of reinit/destroys that we will need to convert to init and or eliminate
/// while cloning the closure.
///
/// NOTE: We do not need to consider if the closure reinitializes the memory
/// since there must be some sort of use for the closure to even reference it
/// and the compiler emits assigns when it reinitializes vars this early in the
/// pipeline.
struct ClosureArgDataflowState {
ASTContext &C;
SmallVector<SILInstruction *, 32> livenessWorklist;
SmallVector<SILInstruction *, 32> consumingWorklist;
MultiDefPrunedLiveness livenessForConsumes;
UseState &useState;
public:
ClosureArgDataflowState(SILFunction *function, UseState &useState)
: C(function->getASTContext()),
livenessForConsumes(function), useState(useState) {}
bool process(
SILArgument *arg, ClosureOperandState &state,
SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers);
private:
/// Perform our liveness dataflow. Returns true if we found any liveness uses
/// at all. These we will need to error upon.
bool performLivenessDataflow(const BasicBlockSet &initBlocks,
const BasicBlockSet &livenessBlocks,
const BasicBlockSet &consumingBlocks);
/// Perform our consuming dataflow. Returns true if we found an earliest set
/// of consuming uses that we can handle that post-dominate the argument.
/// Returns false otherwise.
bool performConsumingDataflow(const BasicBlockSet &initBlocks,
const BasicBlockSet &consumingBlocks);
void classifyUses(BasicBlockSet &initBlocks, BasicBlockSet &livenessBlocks,
BasicBlockSet &consumingBlocks);
bool handleSingleBlockCase(SILArgument *address, ClosureOperandState &state);
};
} // namespace
bool ClosureArgDataflowState::handleSingleBlockCase(
SILArgument *address, ClosureOperandState &state) {
// Walk the instructions from the beginning of the block to the end.
for (auto &inst : *address->getParent()) {
assert(!useState.inits.count(&inst) &&
"Shouldn't see an init before a destroy or reinit");
// If we see a destroy, then we know we are upwards consume... stash it so
// that we can destroy it
if (auto *dvi = dyn_cast<DestroyAddrInst>(&inst)) {
if (useState.destroyToIndexMap.count(dvi)) {
LLVM_DEBUG(llvm::dbgs()
<< "ClosureArgDataflow: Found Consume: " << *dvi);
if (hasMoreThanOneDebugUse(address))
return false;
state.pairedConsumingInsts.push_back(dvi);
state.result = DownwardScanResult::ClosureConsume;
return true;
}
}
// Same for reinits.
if (useState.reinits.count(&inst)) {
LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Found Reinit: " << inst);
if (hasMoreThanOneDebugUse(address))
return false;
state.pairedConsumingInsts.push_back(&inst);
state.result = DownwardScanResult::ClosureConsume;
return true;
}
// Finally, if we have a liveness use, report it for a diagnostic.
if (useState.livenessUses.count(&inst)) {
LLVM_DEBUG(llvm::dbgs()
<< "ClosureArgDataflow: Found liveness use: " << inst);
state.pairedUseInsts.push_back(&inst);
state.result = DownwardScanResult::ClosureUse;
return true;
}
}
LLVM_DEBUG(
llvm::dbgs() << "ClosureArgDataflow: Did not find interesting uses.\n");
return false;
}
bool ClosureArgDataflowState::performLivenessDataflow(
const BasicBlockSet &initBlocks, const BasicBlockSet &livenessBlocks,
const BasicBlockSet &consumingBlocks) {
LLVM_DEBUG(llvm::dbgs() << "ClosureArgLivenessDataflow. Start!\n");
bool foundSingleLivenessUse = false;
auto *fn = useState.getFunction();
auto *frontBlock = &*fn->begin();
BasicBlockWorklist worklist(fn);
for (unsigned i : indices(livenessWorklist)) {
auto *&user = livenessWorklist[i];
// If our use is in the first block, then we are done with this user. Set
// the found single liveness use flag and continue!
if (frontBlock == user->getParent()) {
foundSingleLivenessUse = true;
continue;
}
bool success = false;
for (auto *predBlock : user->getParent()->getPredecessorBlocks()) {
worklist.pushIfNotVisited(predBlock);
}
while (auto *next = worklist.pop()) {
if (livenessBlocks.contains(next) || initBlocks.contains(next) ||
consumingBlocks.contains(next)) {
continue;
}
if (frontBlock == next) {
success = true;
foundSingleLivenessUse = true;
break;
}
for (auto *predBlock : next->getPredecessorBlocks()) {
worklist.pushIfNotVisited(predBlock);
}
}
if (!success) {
user = nullptr;
}
}
return foundSingleLivenessUse;
}
bool ClosureArgDataflowState::performConsumingDataflow(
const BasicBlockSet &initBlocks, const BasicBlockSet &consumingBlocks) {
auto *fn = useState.getFunction();
auto *frontBlock = &*fn->begin();
bool foundSingleConsumingUse = false;
BasicBlockWorklist worklist(fn);
for (unsigned i : indices(consumingWorklist)) {
auto *&user = consumingWorklist[i];
if (frontBlock == user->getParent())
continue;
bool success = false;
for (auto *predBlock : user->getParent()->getPredecessorBlocks()) {
worklist.pushIfNotVisited(predBlock);
}
while (auto *next = worklist.pop()) {
if (initBlocks.contains(next) || consumingBlocks.contains(next)) {
continue;
}
if (frontBlock == next) {
success = true;
foundSingleConsumingUse = true;
break;
}
for (auto *predBlock : next->getPredecessorBlocks()) {
worklist.pushIfNotVisited(predBlock);
}
}
if (!success) {
user = nullptr;
}
}
return foundSingleConsumingUse;
}
void ClosureArgDataflowState::classifyUses(BasicBlockSet &initBlocks,
BasicBlockSet &livenessBlocks,
BasicBlockSet &consumingBlocks) {
for (auto *user : useState.inits) {
if (upwardScanForInit(user, useState)) {
LLVM_DEBUG(llvm::dbgs() << " Found init block during classifyUses at: " << *user);
livenessForConsumes.initializeDef(user);
initBlocks.insert(user->getParent());
}
}
for (auto *user : useState.livenessUses) {
if (upwardScanForUseOut(user, useState)) {
LLVM_DEBUG(llvm::dbgs() << " Found use block during classifyUses at: " << *user);
livenessBlocks.insert(user->getParent());
livenessWorklist.push_back(user);
}
}
for (auto destroyOpt : useState.destroys) {
assert(destroyOpt);
auto *destroy = *destroyOpt;
auto iter = useState.destroyToIndexMap.find(destroy);
assert(iter != useState.destroyToIndexMap.end());
if (upwardScanForDestroys(destroy, useState)) {
LLVM_DEBUG(llvm::dbgs() << " Found destroy block during classifyUses at: " << *destroy);
consumingBlocks.insert(destroy->getParent());
consumingWorklist.push_back(destroy);
}
}
for (auto reinitOpt : useState.reinits) {
assert(reinitOpt);
auto *reinit = *reinitOpt;
auto iter = useState.reinitToIndexMap.find(reinit);
assert(iter != useState.reinitToIndexMap.end());
// TODO: Reinitialization analysis is currently incomplete and leads
// to miscompiles. Treat reinitializations as regular uses for now.
if (!C.LangOpts.hasFeature(Feature::ReinitializeConsumeInMultiBlockDefer)) {
LLVM_DEBUG(llvm::dbgs() << " Treating reinit as use block during classifyUses at: " << *reinit);
livenessBlocks.insert(reinit->getParent());
livenessWorklist.push_back(reinit);
continue;
}
if (upwardScanForDestroys(reinit, useState)) {
LLVM_DEBUG(llvm::dbgs() << " Found reinit block during classifyUses at: " << *reinit);
consumingBlocks.insert(reinit->getParent());
consumingWorklist.push_back(reinit);
}
}
}
bool ClosureArgDataflowState::process(
SILArgument *address, ClosureOperandState &state,
SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers) {
SILFunction *fn = address->getFunction();
assert(fn);
// First see if our function only has a single block. In such a case,
// summarize using the single processing routine.
if (address->getParent()->getTerminator()->isFunctionExiting()) {
LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Single Block Case.\n");
return handleSingleBlockCase(address, state);
}
LLVM_DEBUG(llvm::dbgs() << "ClosureArgDataflow: Multiple Block Case.\n");
// At this point, we begin by classifying the uses of our address into init
// blocks, liveness blocks, consuming blocks. We also seed the worklist for
// our two dataflows.
SWIFT_DEFER {
livenessWorklist.clear();
consumingWorklist.clear();
};
BasicBlockSet initBlocks(fn);
BasicBlockSet livenessBlocks(fn);
BasicBlockSet consumingBlocks(fn);
classifyUses(initBlocks, livenessBlocks, consumingBlocks);
// Liveness Dataflow:
//
// The way that we do this is that for each such instruction:
//
// 1. If the instruction is in the entrance block, then it is our only answer.
//
// 2. If the user is not in the entrance block, visit recursively its
// predecessor blocks until one either hits the entrance block (in which
// case this is the result) /or/ one hits a block in one of our basic block
// sets which means there is an earlier use. Consuming blocks only stop for
// consuming blocks and init blocks. Liveness blocks stop for all other
// blocks.
//
// The result is what remains in our set. Thus we start by processing
// liveness.
if (performLivenessDataflow(initBlocks, livenessBlocks, consumingBlocks)) {
for (unsigned i : indices(livenessWorklist)) {
if (auto *ptr = livenessWorklist[i]) {
LLVM_DEBUG(llvm::dbgs()
<< "ClosureArgLivenessDataflow. Final: Liveness User: "
<< *ptr);
state.pairedUseInsts.push_back(ptr);
}
}
state.result = DownwardScanResult::ClosureUse;
return true;
}
// Then perform the consuming use dataflow. In this case, we think we may have
// found a set of post-dominating consuming uses for our inout_aliasable
// parameter. We are going to change it to be an out parameter and eliminate
// these when we clone the closure.
if (performConsumingDataflow(initBlocks, consumingBlocks)) {
LLVM_DEBUG(llvm::dbgs() << "found single consuming use!\n");
// Before we do anything, make sure our argument has at least one single
// debug_value user. If we have many we can't handle it since something in
// SILGen is emitting weird code. Our tests will ensure that SILGen does not
// diverge by mistake. So we are really just being careful.
if (hasMoreThanOneDebugUse(address)) {
// Failing b/c more than one debug use!
LLVM_DEBUG(llvm::dbgs() << "...but argument has more than one debug use!\n");
return false;
}
//!!! FIXME: Why?
//auto *frontBlock = &*fn->begin();
//livenessForConsumes.initializeDef(address);
for (unsigned i : indices(consumingWorklist)) {
if (auto *ptr = consumingWorklist[i]) {
LLVM_DEBUG(llvm::dbgs() << "liveness for consume: " << *ptr);
state.pairedConsumingInsts.push_back(ptr);
//livenessForConsumes.updateForUse(ptr, true /*is lifetime ending*/);
}
}
// If our consumes do not have a linear lifetime, bail. We will error on the
// move being unknown.
for (auto *ptr : state.pairedConsumingInsts) {
/*if (livenessForConsumes.isWithinBoundary(ptr)) {
LLVM_DEBUG(llvm::dbgs() << "consuming inst within boundary; bailing: "
<< *ptr);
return false;
}*/
postDominatingConsumingUsers.insert(ptr);
}
state.result = DownwardScanResult::ClosureConsume;
return true;
}
return true;
}
//===----------------------------------------------------------------------===//
// Closure Use Gatherer
//===----------------------------------------------------------------------===//
namespace {
/// Visit all of the uses of a closure argument, initializing useState as we go.
struct GatherClosureUseVisitor : public AccessUseVisitor {
UseState &useState;
GatherClosureUseVisitor(UseState &useState)
: AccessUseVisitor(AccessUseType::Overlapping,
NestedAccessType::IgnoreAccessBegin),
useState(useState) {}
bool visitUse(Operand *op, AccessUseType useTy) override;
void reset(SILValue address) { useState.address = address; }
void clear() { useState.clear(); }
};
} // end anonymous namespace
// Filter out recognized uses that do not write to memory.
//
// TODO: Ensure that all of the conditional-write logic below is encapsulated in
// mayWriteToMemory and just call that instead. Possibly add additional
// verification that visitAccessPathUses recognizes all instructions that may
// propagate pointers (even though they don't write).
bool GatherClosureUseVisitor::visitUse(Operand *op, AccessUseType useTy) {
// If this operand is for a dependent type, then it does not actually access
// the operand's address value. It only uses the metatype defined by the
// operation (e.g. open_existential).
if (op->isTypeDependent()) {
return true;
}
// Ignore debug_values. We should leave them on the argument so that later in
// the function the user can still access the out parameter once it is
// updated.
if (isa<DebugValueInst>(op->getUser()))
return true;
// Ignore end_access. For our purposes, they are irrelevant and we do not want
// to treat them like liveness uses.
if (isa<EndAccessInst>(op->getUser()))
return true;
if (memInstMustInitialize(op)) {
if (stripAccessMarkers(op->get()) != useState.address) {
LLVM_DEBUG(llvm::dbgs()
<< "!!! Error! Found init use not on base address: "
<< *op->getUser());
return false;
}
LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found init: " << *op->getUser());
useState.inits.insert(op->getUser());
return true;
}
if (isReinitToInitConvertibleInst(op)) {
if (stripAccessMarkers(op->get()) != useState.address) {
LLVM_DEBUG(llvm::dbgs()
<< "!!! Error! Found reinit use not on base address: "
<< *op->getUser());
return false;
}
LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found reinit: " << *op->getUser());
useState.insertReinit(op->getUser());
return true;
}
if (auto *dvi = dyn_cast<DestroyAddrInst>(op->getUser())) {
// If we see a destroy_addr not on our base address, bail! Just error and
// say that we do not understand the code.
if (dvi->getOperand() != useState.address) {
LLVM_DEBUG(llvm::dbgs()
<< "!!! Error! Found destroy_addr no on base address: "
<< *dvi);
return false;
}
LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found destroy_addr: " << *dvi);
useState.insertDestroy(dvi);
return true;
}
LLVM_DEBUG(llvm::dbgs() << "ClosureUse: Found liveness use: "
<< *op->getUser());
useState.livenessUses.insert(op->getUser());
return true;
}
//===----------------------------------------------------------------------===//
// Closure Argument Cloner
//===----------------------------------------------------------------------===//
namespace {
struct ClosureArgumentInOutToOutCloner
: SILClonerWithScopes<ClosureArgumentInOutToOutCloner> {
friend class SILInstructionVisitor<ClosureArgumentInOutToOutCloner>;
friend class SILCloner<ClosureArgumentInOutToOutCloner>;
SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers;
SILFunction *orig;
const SmallBitVector &argsToConvertIndices;
SmallPtrSet<SILValue, 8> oldArgSet;
// Map from clonedArg -> oldArg.
llvm::SmallMapVector<SILValue, SILValue, 4> clonedArgToOldArgMap;
public:
ClosureArgumentInOutToOutCloner(
SILOptFunctionBuilder &funcBuilder, SILFunction *orig,
SerializedKind_t serializedKind,
SmallBlotSetVector<SILInstruction *, 8> &postDominatingConsumingUsers,
const SmallBitVector &argsToConvertIndices, StringRef name);
void populateCloned();