forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddressLowering.cpp
4505 lines (3954 loc) · 169 KB
/
AddressLowering.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
//===--- AddressLowering.cpp - Lower SIL address-only types. --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// This pass removes "opaque SILValues" by translating them into addressable
/// memory locations such as a stack locations. This is mandatory for IRGen.
///
/// Lowering to LLVM IR requires each SILValue's type to be a valid "SIL storage
/// type". Opaque SILValues have address-only types. These require indirect
/// storage in LLVM, so their SIL storage type must be an address type.
///
/// This pass never creates copies except to replace explicit value copies
/// (copy_value, load [copy], store). For move-only values, this allows complete
/// diagnostics. And in general, this makes it impossible for SIL passes to
/// "accidentally" create copies.
///
/// This pass inserts moves (copy_addr [take] [initialize]) of owned values to
/// - compose aggregates
/// - resolve phi interference
///
/// For guaranteed values, this pass inserts neither copies nor moves. Opaque
/// values are potentially unmovable when borrowed. This means that guaranteed
/// address-only aggregates and phis are prohibited. This SIL invariant is
/// enforced by SILVerifier::checkOwnershipForwardingInst() and
/// SILVerifier::visitSILPhiArgument().
///
/// The simplest approach to address lowering is to map each opaque SILValue to
/// a separate alloc_stack. This pass avoids doing that in the following cases:
///
/// 1. Reused-storage: Some operations are guaranteed to reuse their operand's
/// storage. This includes extracting an enum payload and opening an existential
/// value. This is required to avoid introducing new copies or moves.
///
/// // %data's storage must reuse storage allocated for %enum
/// %data = unchecked_enum_data %enum : $Optional<T>, #Optional.some!enumelt
///
/// 2. Def-projection: Some operations are guaranteed to directly project out of
/// their operand's storage. This is also required to avoid introducing new
/// copies or moves. Unlike reused-storage, such projections are non-destructive
/// and repeatable.
///
/// // %field's storage is part of the storage allocated for %struct
/// %field = struct_extract %struct, #field
///
/// 3. Use-projection: Operations that compose aggregates may optionally allow
/// their operands to project into the storage allocated for their result. This
/// is only an optimization but is essential for reasonable code generation.
///
/// // %field's storage may be part of the storage allocated for %struct
/// %struct = struct(..., %field, ...)
///
/// 4. Phi-projection: Phi's may optionally allow their (branch) operands to
/// reuse the storage allocated for their result (block argument). This is only
/// an optimization, but is important to avoid many useless moves:
///
/// // %arg's storage may be part of the storage allocated for %phi
/// br bb(%arg)
/// bb(%phi : @owned $T)
///
/// The algorithm proceeds as follows:
///
/// ## Step #1: Map opaque values
///
/// Populate a map from each opaque SILValue to its ValueStorage in forward
/// order (RPO). Each opaque value is mapped to an ordinal ID representing the
/// storage. Storage locations can now be optimized by remapping the values.
///
/// Reused-storage operations are not mapped to ValueStorage.
///
/// ## Step #2: Allocate storage
///
/// In reverse order (PO), allocate the parent storage object for each opaque
/// value.
///
/// Handle def-projection: If the value is a subobject extraction
/// (struct_extract, tuple_extract, open_existential_value,
/// unchecked_enum_data), then mark the value's storage as a projection from the
/// def's storage.
///
/// Handle use-projection: If the value's use composes a parent object from this
/// value (struct, tuple, enum), and the use's storage dominates this value,
/// then mark the value's storage as a projection into the use's storage.
///
/// ValueStorage projections can be chained. A non-projection ValueStorage is
/// the root of a tree of projections.
///
/// When allocating storage, each ValueStorage root has its `storageAddress`
/// assigned to an `alloc_stack` or an argument. Opaque values that are storage
/// projections are not mapped to a `storageAddress` at this point. That happens
/// during rewriting.
///
/// Handle phi-projection: After allocating storage for all non-phi opaque
/// values, phi storage is allocated. (Phi values are block arguments in which
/// phi's arguments are branch operands). This is handled by a
/// PhiStorageOptimizer that checks for interference among the phi operands and
/// reuses storage allocated to other values.
///
/// ## Step #3. Rewrite opaque values
///
/// In forward order (RPO), rewrite each opaque value definition, and all its
/// uses. This generally involves creating a new `_addr` variant of the
/// instruction and obtaining the storage address from the `valueStorageMap`.
///
/// If this value's storage is a def-projection (the value is used to compose an
/// aggregate), then first generate instructions to materialize the
/// projection. This is a recursive process starting with the root of the
/// projection path.
///
/// A projection path will be materialized once for the leaf subobject. When
/// this happens, the `storageAddress` will be assigned for any intermediate
/// projection paths. When those values are rewritten, their `storageAddress`
/// will already be available.
///
//===----------------------------------------------------------------------===//
///
/// TODO: Much of the implementation complexity, including most of the general
/// helper routines, stems from handling calls with multiple return values as
/// tuples. Once those calls are properly represented as instructions with
/// multiple results, then the implementation complexity will fall away. See the
/// code tagged "TODO: Multi-Result".
///
/// TODO: Some complexity stems from the SILPhiArgument type/opcode being used
/// for terminator results rather than phis.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "address-lowering"
#include "PhiStorageOptimizer.h"
#include "swift/AST/Decl.h"
#include "swift/Basic/BlotSetVector.h"
#include "swift/Basic/Range.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/StackList.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "swift/SILOptimizer/Utils/StackNesting.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using llvm::SmallSetVector;
/// Get a function's convention for Lowered SIL, even though the SIL stage is
/// still Canonical.
static SILFunctionConventions getLoweredFnConv(SILFunction *function) {
return SILFunctionConventions(
function->getLoweredFunctionType(),
SILModuleConventions::getLoweredAddressConventions(
function->getModule()));
}
/// Get a call's function convention for Lowered SIL even though the SIL stage
/// is still Canonical.
static SILFunctionConventions getLoweredCallConv(ApplySite call) {
return SILFunctionConventions(
call.getSubstCalleeType(),
SILModuleConventions::getLoweredAddressConventions(call.getModule()));
}
//===----------------------------------------------------------------------===//
// Multi-Result
//
// TODO: These helpers all compensate for the legacy representation of return
// values as tuples. Once calls are properly represented as multi-value
// instructions, this complexity all goes away.
//
// Calls are currently SILValues, but when the result type is a tuple, the call
// value does not represent a real value with storage. This is a bad situation
// for address lowering because there's no way to tell from any given value
// whether it's legal to assign storage to that value. As a result, the
// implementation of call lowering doesn't fall out naturally from the algorithm
// that lowers values to storage.
//===----------------------------------------------------------------------===//
/// If \p pseudoResult represents multiple results and at least one result is
/// used, then return the destructure.
static DestructureTupleInst *getCallDestructure(FullApplySite apply) {
if (apply.getKind() == FullApplySiteKind::BeginApplyInst)
return nullptr;
if (apply.getSubstCalleeConv().getNumDirectSILResults() == 1)
return nullptr;
SILValue pseudoResult = apply.getResult();
assert(pseudoResult->getType().is<TupleType>());
if (auto *use = pseudoResult->getSingleUse())
return cast<DestructureTupleInst>(use->getUser());
assert(pseudoResult->use_empty()
&& "pseudo result can only be used by a single destructure_tuple");
return nullptr;
}
/// \p destructure is the pseudo result of a multi-result call.
/// Visit all real call results. Stop when the visitor returns `false`.
static bool visitCallMultiResults(
DestructureTupleInst *destructure, SILFunctionConventions fnConv,
llvm::function_ref<bool(SILValue, SILResultInfo)> visitor) {
assert(fnConv.getNumDirectSILResults() == destructure->getNumResults());
auto resultIter = destructure->getAllResults().begin();
for (auto resultInfo : fnConv.getDirectSILResults()) {
if (!visitor(*resultIter++, resultInfo))
return false;
}
return true;
}
/// Visit all real call results. Stop when the visitor returns `false`.
static bool
visitCallResults(FullApplySite apply,
llvm::function_ref<bool(SILValue, SILResultInfo)> visitor) {
auto fnConv = apply.getSubstCalleeConv();
if (auto *destructure = getCallDestructure(apply)) {
return visitCallMultiResults(destructure, fnConv, visitor);
}
return visitor(apply.getResult(), *fnConv.getDirectSILResults().begin());
}
/// Return true if the given value is either a "fake" tuple that represents all
/// of a call's results or an empty tuple of no results. This may return true
/// for either an apply instruction or a block argument.
static bool isPseudoCallResult(SILValue value) {
if (auto *apply = dyn_cast<ApplyInst>(value))
return ApplySite(apply).getSubstCalleeConv().getNumDirectSILResults() > 1;
auto *bbArg = dyn_cast<SILPhiArgument>(value);
if (!bbArg)
return false;
auto *term = bbArg->getTerminatorForResult();
if (!term)
return false;
auto *tryApply = dyn_cast<TryApplyInst>(term);
if (!tryApply)
return false;
return ApplySite(tryApply).getSubstCalleeConv().getNumDirectSILResults() > 1;
}
/// Return true if this is a pseudo-return value.
static bool isPseudoReturnValue(SILValue value) {
if (value->getFunction()->getConventions().getNumDirectSILResults() < 2)
return false;
if (auto *tuple = dyn_cast<TupleInst>(value)) {
Operand *singleUse = tuple->getSingleUse();
return singleUse && isa<ReturnInst>(singleUse->getUser());
}
return false;
}
/// Return the value representing storage of an address-only or indirectly
/// returned tuple element. For real tuples, return the tuple value itself. If
/// the tuple is a pseudo-return value, return the indirect function argument
/// for the corresponding result after lowering.
///
/// bb0(..., %loweredIndirectResult : $*T, ...)
/// ....
/// %tuple = tuple(..., %operand, ...)
/// return %tuple
///
/// When called on %operand, return %loweredIndirectResult.
///
/// Precondition: \p operand's user is a TupleInst
///
/// Precondition: indirect function arguments have already been rewritten
/// (see insertIndirectReturnArgs()).
static SILValue getTupleStorageValue(Operand *operand) {
auto *tuple = cast<TupleInst>(operand->getUser());
if (!isPseudoReturnValue(tuple))
return tuple;
unsigned resultIdx = tuple->getElementIndex(operand);
auto *function = tuple->getFunction();
auto loweredFnConv = getLoweredFnConv(function);
assert(loweredFnConv.getResults().size() == tuple->getElements().size());
unsigned indirectResultIdx = 0;
for (SILResultInfo result : loweredFnConv.getResults().slice(0, resultIdx)) {
if (loweredFnConv.isSILIndirect(result))
++indirectResultIdx;
}
// Cannot call function->getIndirectSILResults here because that API uses the
// function conventions before address lowering.
return function->getArguments()[indirectResultIdx];
}
/// Return the value representing storage for a single return value.
///
/// bb0(..., %loweredIndirectResult : $*T, ...) // function entry
/// return %oper
///
/// For %oper, return %loweredIndirectResult
static SILValue getSingleReturnAddress(Operand *operand) {
assert(!isPseudoReturnValue(operand->get()));
auto *function = operand->getParentFunction();
assert(getLoweredFnConv(function).getNumIndirectSILResults() == 1);
// Cannot call getIndirectSILResults here because that API uses the
// function conventions before address lowering.
return function->getArguments()[0];
}
//===----------------------------------------------------------------------===//
// ValueStorageMap
//
// Map Opaque SILValues to abstract storage units.
//===----------------------------------------------------------------------===//
/// Check if this is a copy->store pair. If so, the copy storage will be
/// projected from the source, and the copy semantics will be handled by
/// UseRewriter::visitStoreInst.
static bool isStoreCopy(SILValue value) {
auto *copyInst = dyn_cast<CopyValueInst>(value);
if (!copyInst)
return false;
if (!copyInst->hasOneUse())
return false;
auto *user = value->getSingleUse()->getUser();
auto *storeInst = dyn_cast<StoreInst>(user);
if (!storeInst)
return false;
SSAPrunedLiveness liveness(copyInst->getFunction());
auto isStoreOutOfRange = [&liveness, storeInst](SILValue root) {
liveness.initializeDef(root);
auto summary = liveness.computeSimple();
if (summary.addressUseKind != AddressUseKind::NonEscaping) {
return true;
}
if (summary.innerBorrowKind != InnerBorrowKind::Contained) {
return true;
}
if (!liveness.isWithinBoundary(storeInst)) {
return true;
}
return false;
};
auto source = copyInst->getOperand();
if (source->getOwnershipKind() == OwnershipKind::Guaranteed) {
// [in_guaranteed_begin_apply_results] If any root of the source is a
// begin_apply, we can't rely on projecting from the (rewritten) source:
// The store may not be in the coroutine's range. The result would be
// attempting to access invalid storage.
SmallVector<SILValue, 4> roots;
findGuaranteedReferenceRoots(source, /*lookThroughNestedBorrows=*/true,
roots);
// TODO: Rather than checking whether the store is out of range of any
// guaranteed root's SSAPrunedLiveness, instead check whether it is out of
// range of ExtendedLiveness of the borrow introducers:
// - visit borrow introducers via visitBorrowIntroducers
// - call ExtendedLiveness.compute on each borrow introducer
if (llvm::any_of(roots, [&](SILValue root) {
// Nothing is out of range of a function argument.
if (isa<SILFunctionArgument>(root))
return false;
// Handle forwarding phis conservatively rather than recursing.
if (SILArgument::asPhi(root) && !BorrowedValue(root))
return true;
if (isa<BeginApplyInst>(root->getDefiningInstruction())) {
return true;
}
return isStoreOutOfRange(root);
})) {
return false;
}
} else if (source->getOwnershipKind() == OwnershipKind::Owned) {
if (isStoreOutOfRange(source)) {
return false;
}
}
return true;
}
void ValueStorageMap::insertValue(SILValue value, SILValue storageAddress) {
assert(!stableStorage && "cannot grow stable storage map");
auto hashResult =
valueHashMap.insert(std::make_pair(value, valueVector.size()));
(void)hashResult;
assert(hashResult.second && "SILValue already mapped");
valueVector.emplace_back(value, ValueStorage(storageAddress));
}
void ValueStorageMap::replaceValue(SILValue oldValue, SILValue newValue) {
auto pos = valueHashMap.find(oldValue);
assert(pos != valueHashMap.end());
unsigned ordinal = pos->second;
valueHashMap.erase(pos);
auto hashResult = valueHashMap.insert(std::make_pair(newValue, ordinal));
(void)hashResult;
assert(hashResult.second && "SILValue already mapped");
valueVector[ordinal].value = newValue;
}
#ifndef NDEBUG
void ValueStorage::print(llvm::raw_ostream &OS) const {
OS << "projectedStorageID: " << projectedStorageID << "\n";
OS << "projectedOperandNum: " << projectedOperandNum << "\n";
OS << "isDefProjection: " << isDefProjection << "\n";
OS << "isUseProjection: " << isUseProjection << "\n";
OS << "isRewritten: " << isRewritten << "\n";
OS << "initializes: " << initializes << "\n";
}
void ValueStorage::dump() const { print(llvm::dbgs()); }
void ValueStorageMap::ValueStoragePair::print(llvm::raw_ostream &OS) const {
OS << "value: ";
value->print(OS);
OS << "address: ";
if (storage.storageAddress)
storage.storageAddress->print(OS);
else
OS << "UNKNOWN!\n";
storage.print(OS);
}
void ValueStorageMap::ValueStoragePair::dump() const { print(llvm::dbgs()); }
void ValueStorageMap::printProjections(SILValue value,
llvm::raw_ostream &OS) const {
for (auto *pair : getProjections(value)) {
pair->print(OS);
}
}
void ValueStorageMap::dumpProjections(SILValue value) const {
printProjections(value, llvm::dbgs());
}
void ValueStorageMap::print(llvm::raw_ostream &OS) const {
OS << "ValueStorageMap:\n";
for (unsigned ordinal : indices(valueVector)) {
auto &valStoragePair = valueVector[ordinal];
OS << "value: ";
valStoragePair.value->print(OS);
auto &storage = valStoragePair.storage;
if (storage.isUseProjection) {
OS << " use projection: ";
if (!storage.isRewritten)
valueVector[storage.projectedStorageID].value->print(OS);
} else if (storage.isDefProjection) {
OS << " def projection: ";
if (!storage.isRewritten)
valueVector[storage.projectedStorageID].value->print(OS);
}
if (storage.storageAddress) {
OS << " storage: ";
storage.storageAddress->print(OS);
}
}
}
void ValueStorageMap::dump() const { print(llvm::dbgs()); }
#endif
//===----------------------------------------------------------------------===//
// AddressLoweringState
//
// Shared state for the pass's analysis and transforms.
//===----------------------------------------------------------------------===//
namespace {
class PhiRewriter;
struct AddressLoweringState {
SILFunction *function;
SILFunctionConventions loweredFnConv;
// Dominators remain valid throughout this pass.
DominanceInfo *domInfo;
// Dead-end blocks remain valid through this pass.
DeadEndBlocks *deBlocks;
InstructionDeleter deleter;
// All opaque values mapped to their associated storage.
ValueStorageMap valueStorageMap;
// All call sites with formally indirect SILArgument or SILResult conventions.
//
// Applies with indirect results are removed as they are rewritten. Applies
// with only indirect arguments are rewritten in a post-pass, only after all
// parameters are rewritten.
SmallBlotSetVector<ApplySite, 16> indirectApplies;
// unconditional_checked_cast instructions of loadable type which need to be
// rewritten.
SmallVector<UnconditionalCheckedCastInst *, 2> nonopaqueResultUCCs;
// checked_cast_br instructions to loadable type which need to be rewritten.
SmallVector<CheckedCastBranchInst *, 2> nonopaqueResultCCBs;
// All function-exiting terminators (return or throw instructions).
SmallVector<TermInst *, 8> exitingInsts;
// All instructions that yield values to callees.
TinyPtrVector<YieldInst *> yieldInsts;
// Handle moves from a phi's operand storage to the phi storage.
std::unique_ptr<PhiRewriter> phiRewriter;
// Projections created for uses, recorded in order to be sunk.
//
// Not all use projections are recorded in the valueStorageMap. It's not
// legal to reuse use projections for non-canonical users or for phis.
SmallVector<SILValue, 16> useProjections;
AddressLoweringState(SILFunction *function, DominanceInfo *domInfo,
DeadEndBlocks *deBlocks)
: function(function), loweredFnConv(getLoweredFnConv(function)),
domInfo(domInfo), deBlocks(deBlocks) {
for (auto &block : *function) {
if (block.getTerminator()->isFunctionExiting())
exitingInsts.push_back(block.getTerminator());
}
}
SILModule *getModule() const { return &function->getModule(); }
SILLocation genLoc() const {
return RegularLocation::getAutoGeneratedLocation();
}
// Get a builder that uses function conventions for the Lowered SIL stage even
// though the SIL stage hasn't explicitly changed yet.
SILBuilder getBuilder(SILBasicBlock::iterator insertPt) const {
return getBuilder(insertPt, &*insertPt);
}
SILBuilder getTermBuilder(TermInst *term) const {
return getBuilder(term->getParent()->end(), term);
}
/// The values which must be dominated by some opaque value in order for it
/// to reuse the storage allocated for `userValue`.
///
/// If that's not possible, returns false.
///
/// Precondition: `userValue` must be a value into which a use could be
/// projected, e.g. an aggregation instruction.
///
/// Each dominand could be:
/// - an address argument
/// - an alloc_stack
/// - an instruction which opens a type (open_existential_ref, etc.)
///
/// Related to getProjectionInsertionPoint. Specifically, the dominands
/// discovered here must all be rediscovered there and must all be dominated
/// by the insertion point it returns.
void getDominandsForUseProjection(SILValue userValue,
SmallVectorImpl<SILValue> &dominands) const;
/// Finds and caches the latest opening instruction of the type of the value
/// in \p pair.
///
/// @returns nullable instruction
SILInstruction *
getLatestOpeningInst(const ValueStorageMap::ValueStoragePair *) const;
/// The latest instruction which opens an archetype involved in the indicated
/// type.
///
/// @returns nullable instruction
SILInstruction *getLatestOpeningInst(SILType ty) const;
PhiRewriter &getPhiRewriter();
SILValue getMaterializedAddress(SILValue origValue) const {
return valueStorageMap.getStorage(origValue).getMaterializedAddress();
}
protected:
SILBuilder getBuilder(SILBasicBlock::iterator insertPt,
SILInstruction *originalInst) const {
SILBuilder builder(originalInst->getParent(), insertPt);
builder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(
builder.getModule()));
builder.setCurrentDebugScope(originalInst->getDebugScope());
return builder;
}
void prepareBuilder(SILBuilder &builder) {
builder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(
builder.getModule()));
};
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// OpaqueValueVisitor
//
// Map opaque values to ValueStorage.
//===----------------------------------------------------------------------===//
/// Before populating the ValueStorageMap, replace each value-typed argument to
/// the current function with an address-typed argument by inserting a temporary
/// load instruction.
static void convertDirectToIndirectFunctionArgs(AddressLoweringState &pass) {
// Insert temporary argument loads at the top of the function.
SILBuilder argBuilder =
pass.getBuilder(pass.function->getEntryBlock()->begin());
auto fnConv = pass.function->getConventions();
unsigned argIdx = fnConv.getSILArgIndexOfFirstParam();
for (SILParameterInfo param :
pass.function->getLoweredFunctionType()->getParameters()) {
if (param.isFormalIndirect() && !fnConv.isSILIndirect(param)) {
SILArgument *arg = pass.function->getArgument(argIdx);
SILType addrType = arg->getType().getAddressType();
auto loc = SILValue(arg).getLoc();
SILValue undefAddress = SILUndef::get(addrType, *pass.function);
SingleValueInstruction *load;
if (addrType.isTrivial(*pass.function)) {
load = argBuilder.createLoad(loc, undefAddress,
LoadOwnershipQualifier::Trivial);
} else if (param.isConsumed()) {
load = argBuilder.createLoad(loc, undefAddress,
LoadOwnershipQualifier::Take);
} else {
load = argBuilder.createLoadBorrow(loc, undefAddress);
for (SILInstruction *termInst : pass.exitingInsts) {
pass.getBuilder(termInst->getIterator())
.createEndBorrow(pass.genLoc(), load);
}
}
arg->replaceAllUsesWith(load);
assert(!pass.valueStorageMap.contains(arg));
arg = arg->getParent()->replaceFunctionArgument(
arg->getIndex(), addrType, OwnershipKind::None, arg->getDecl());
assert(isa<LoadInst>(load) || isa<LoadBorrowInst>(load));
load->setOperand(0, arg);
// Indirect calling convention may be used for loadable types. In that
// case, generating the argument loads is sufficient.
if (addrType.isAddressOnly(*pass.function)) {
pass.valueStorageMap.insertValue(load, arg);
}
}
++argIdx;
}
assert(argIdx ==
fnConv.getSILArgIndexOfFirstParam() + fnConv.getNumSILArguments());
}
/// Before populating the ValueStorageMap, insert function arguments for any
/// @out result type. Return the number of indirect result arguments added.
static unsigned insertIndirectReturnArgs(AddressLoweringState &pass) {
auto &astCtx = pass.getModule()->getASTContext();
auto typeCtx = pass.function->getTypeExpansionContext();
auto *declCtx = pass.function->getDeclContext();
if (!declCtx) {
// Fall back to using the module as the decl context if the function
// doesn't have one. The can happen with default argument getters, for
// example.
declCtx = pass.function->getModule().getSwiftModule();
}
unsigned argIdx = 0;
for (auto resultTy : pass.loweredFnConv.getIndirectSILResultTypes(typeCtx)) {
auto resultTyInContext = pass.function->mapTypeIntoContext(resultTy);
auto bodyResultTy = pass.function->getModule().Types.getLoweredType(
resultTyInContext.getASTType(), *pass.function);
auto var = new (astCtx) ParamDecl(
SourceLoc(), SourceLoc(), astCtx.getIdentifier("$return_value"),
SourceLoc(), astCtx.getIdentifier("$return_value"), declCtx);
var->setSpecifier(ParamSpecifier::InOut);
SILFunctionArgument *funcArg =
pass.function->begin()->insertFunctionArgument(
argIdx, bodyResultTy.getAddressType(), OwnershipKind::None, var);
// Insert function results into valueStorageMap so that the caller storage
// can be projected onto values inside the function as use projections.
//
// This is the only case where a value defines its own storage.
pass.valueStorageMap.insertValue(funcArg, funcArg);
++argIdx;
}
assert(argIdx == pass.loweredFnConv.getNumIndirectSILResults());
return argIdx;
}
namespace {
/// Collect all opaque/resilient values, inserting them in `valueStorageMap` in
/// RPO order.
///
/// Collect all call arguments with formally indirect SIL argument convention in
/// `indirectOperands` and formally indirect SIL results in `indirectResults`.
///
/// TODO: Perform linear-scan style in-place stack slot coloring by keeping
/// track of each value's last use.
class OpaqueValueVisitor {
AddressLoweringState &pass;
PostOrderFunctionInfo postorderInfo;
public:
explicit OpaqueValueVisitor(AddressLoweringState &pass)
: pass(pass), postorderInfo(pass.function) {}
void mapValueStorage();
protected:
void checkForIndirectApply(ApplySite applySite);
void visitValue(SILValue value);
void canonicalizeReturnValues();
};
} // end anonymous namespace
/// Top-level entry. Populates AddressLoweringState's `valueStorageMap`,
/// `indirectApplies`, and `exitingInsts`.
///
/// Find all Opaque/Resilient SILValues and add them
/// to valueStorageMap in RPO.
void OpaqueValueVisitor::mapValueStorage() {
for (auto *block : postorderInfo.getReversePostOrder()) {
// Opaque function arguments have already been replaced.
if (block != pass.function->getEntryBlock()) {
for (auto *arg : block->getArguments()) {
if (isPseudoCallResult(arg))
continue;
visitValue(arg);
}
}
for (auto &inst : *block) {
if (auto apply = ApplySite::isa(&inst))
checkForIndirectApply(apply);
if (auto *yieldInst = dyn_cast<YieldInst>(&inst)) {
pass.yieldInsts.push_back(yieldInst);
}
for (auto result : inst.getResults()) {
if (isPseudoCallResult(result) || isPseudoReturnValue(result))
continue;
visitValue(result);
}
}
}
canonicalizeReturnValues();
}
/// Populate `indirectApplies`.
void OpaqueValueVisitor::checkForIndirectApply(ApplySite applySite) {
auto calleeConv = applySite.getSubstCalleeConv();
unsigned calleeArgIdx = applySite.getCalleeArgIndexOfFirstAppliedArg();
for (Operand &operand : applySite.getArgumentOperands()) {
if (operand.get()->getType().isObject()) {
auto argConv = calleeConv.getSILArgumentConvention(calleeArgIdx);
if (argConv.isIndirectConvention()) {
pass.indirectApplies.insert(applySite);
return;
}
}
++calleeArgIdx;
}
if (applySite.getSubstCalleeType()->hasIndirectFormalResults() ||
applySite.getSubstCalleeType()->hasIndirectFormalYields()) {
pass.indirectApplies.insert(applySite);
}
}
/// If `value` is address-only, add it to the `valueStorageMap`.
void OpaqueValueVisitor::visitValue(SILValue value) {
if (!value->getType().isObject())
return;
if (!value->getType().isAddressOnly(*pass.function)) {
if (auto *ucci = dyn_cast<UnconditionalCheckedCastInst>(value)) {
if (ucci->getSourceLoweredType().isAddressOnly(*pass.function))
return;
if (!canIRGenUseScalarCheckedCastInstructions(
pass.function->getModule(), ucci->getSourceFormalType(),
ucci->getTargetFormalType())) {
pass.nonopaqueResultUCCs.push_back(ucci);
}
} else if (auto *arg = dyn_cast<SILArgument>(value)) {
if (auto *ccbi = dyn_cast_or_null<CheckedCastBranchInst>(
arg->getTerminatorForResult())) {
if (ccbi->getSuccessBB() != arg->getParent())
return;
if (ccbi->getSourceLoweredType().isAddressOnly(*pass.function))
return;
if (!canIRGenUseScalarCheckedCastInstructions(
pass.function->getModule(), ccbi->getSourceFormalType(),
ccbi->getTargetFormalType())) {
pass.nonopaqueResultCCBs.push_back(ccbi);
}
}
}
return;
}
if (pass.valueStorageMap.contains(value)) {
// Function arguments are already mapped from loads.
assert(isa<SILFunctionArgument>(
pass.valueStorageMap.getStorage(value).storageAddress));
return;
}
pass.valueStorageMap.insertValue(value, SILValue());
}
// Canonicalize returned values. For multiple direct results, the operand of the
// return instruction must be a tuple with no other uses.
//
// Given $() -> @out (T, T):
// %t = def : $(T, T)
// use %t : $(T, T)
// return %t : $(T, T)
//
// Produce:
// %t = def
// use %t : $(T, T)
// (%e0, %e1) = destructure_tuple %t : $(T, T)
// %r = tuple (%e0 : $T, %e1 : $T)
// return %r : $(T, T)
//
// TODO: Multi-Result. This should be a standard OSSA canonicalization until
// returns are fixed to take multiple operands.
void OpaqueValueVisitor::canonicalizeReturnValues() {
auto numResults = pass.function->getConventions().getNumDirectSILResults();
if (numResults < 2)
return;
for (SILInstruction *termInst : pass.exitingInsts) {
auto *returnInst = dyn_cast<ReturnInst>(termInst);
if (!returnInst) {
assert(isa<ThrowInst>(termInst));
continue;
}
SILValue oldResult = returnInst->getOperand();
if (oldResult->getOwnershipKind() != OwnershipKind::Owned)
continue;
assert(oldResult->getType().is<TupleType>());
if (oldResult->hasOneUse()) {
assert(isPseudoReturnValue(oldResult));
continue;
}
// There is another nonconsuming use of the returned tuple.
SILBuilderWithScope returnBuilder(returnInst);
auto loc = pass.genLoc();
auto *destructure = returnBuilder.createDestructureTuple(loc, oldResult);
SmallVector<SILValue, 4> results;
results.reserve(numResults);
for (auto result : destructure->getResults()) {
// Update the value storage map for new instructions. Since they are
// created at function exits, they are naturally in RPO order.
this->visitValue(result);
results.push_back(result);
}
auto *newResult = returnBuilder.createTuple(
pass.genLoc(), oldResult->getType(), results, OwnershipKind::Owned);
returnInst->setOperand(newResult);
assert(isPseudoReturnValue(newResult));
}
}
/// Top-level entry point.
///
/// Prepare the SIL by rewriting function arguments and returns.
/// Initialize the ValueStorageMap with an entry for each opaque value in the
/// function.
static void prepareValueStorage(AddressLoweringState &pass) {
// Fixup this function's argument types with temporary loads.
convertDirectToIndirectFunctionArgs(pass);
// Create a new function argument for each indirect result.
insertIndirectReturnArgs(pass);
// Populate valueStorageMap.
OpaqueValueVisitor(pass).mapValueStorage();
}
//===----------------------------------------------------------------------===//
// Storage Projection
//
// These queries determine whether storage for a SILValue can be projected from
// its operands or into its uses.
// ===---------------------------------------------------------------------===//
/// Return the operand whose source is an aggregate value that is extracted
/// into the given subobject, \p value. Or return nullptr.
///
/// Def-projection oracle: The answer must be consistent across both
/// OpaqueStorageAllocation and AddressMaterialization.
///
/// Invariant:
/// `getProjectedDefOperand(value) != nullptr`
/// if-and-only-if
/// `pass.valueStorageMap.getStorage(value).isDefProjection`
///
/// Invariant: if \p value has guaranteed ownership, this must return a nonnull
/// value.
static Operand *getProjectedDefOperand(SILValue value) {
switch (value->getKind()) {
default:
return nullptr;
case ValueKind::BeginBorrowInst:
return &cast<BeginBorrowInst>(value)->getOperandRef();
case ValueKind::CopyValueInst:
if (isStoreCopy(value))
return &cast<CopyValueInst>(value)->getOperandRef();
return nullptr;
case ValueKind::MoveValueInst:
return &cast<MoveValueInst>(value)->getOperandRef();
case ValueKind::MultipleValueInstructionResult: {
SILInstruction *destructure =
cast<MultipleValueInstructionResult>(value)->getParent();
switch (destructure->getKind()) {
default:
return nullptr;
case SILInstructionKind::DestructureStructInst:
return &destructure->getOperandRef(0);
case SILInstructionKind::DestructureTupleInst: {
auto *oper = &destructure->getOperandRef(0);
if (isPseudoCallResult(oper->get()))
return nullptr;
return oper;
}
}
}
case ValueKind::TupleExtractInst: {
auto *TEI = cast<TupleExtractInst>(value);
// TODO: Multi-Result: TupleExtract from an apply are handled specially
// until we have multi-result calls. Force them to allocate storage.
if (ApplySite::isa(TEI->getOperand()))
return nullptr;
LLVM_FALLTHROUGH;
}
case ValueKind::StructExtractInst:
case ValueKind::OpenExistentialValueInst:
case ValueKind::OpenExistentialBoxValueInst:
assert(value->getOwnershipKind() == OwnershipKind::Guaranteed);
return &cast<SingleValueInstruction>(value)->getAllOperands()[0];
case ValueKind::TuplePackExtractInst:
assert(value->getOwnershipKind() == OwnershipKind::Guaranteed);
return &cast<SingleValueInstruction>(value)->getAllOperands()[1];
}
}
/// If \p value is a an existential or enum, then return the existential or enum
/// operand. These operations are always rewritten by the UseRewriter and always
/// reuse the same storage as their operand. Note that if the operation's result
/// is address-only, then the operand must be address-only and therefore must
/// mapped to ValueStorage.
///
/// If \p value is an unchecked_bitwise_cast, then return the cast operand.
///
/// open_existential_value must reuse storage because the boxed value is shared
/// with other instances of the existential. An explicit copy is needed to
/// obtain an owned value.