-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathAddressLowering.cpp
1539 lines (1338 loc) · 56.6 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 - 2017 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 lowers SILTypes. On completion, the SILType of every SILValue is
// its SIL storage type. A SIL storage type is always an address type for values
// that require indirect storage at the LLVM IR level. Consequently, this pass
// is required for IRGen. It is a mandatory IRGen preparation pass (not a
// diagnostic pass).
//
// In the following text, items marked "[REUSE]" only apply to the proposed
// storage reuse optimization, which is not currently implemented.
//
// ## State
//
// A `valueStorageMap` maps each opaque SIL value to its storage
// information containing:
//
// - An ordinal representing the position of this instruction.
//
// - [REUSE] The identifier of the storage object. An optimized storage object
// may have multiple disjoint lifetimes. A storage object may also have
// subobjects. Each subobject has its own live range. When considering
// liveness of the subobject, one must also consider liveness of the
// parent object.
//
// - If this is a subobject projection, refer back to the value whose
// storage object will be the parent that this storage address is a
// projection of.
//
// - The storage address for this subobject.
//
// ## Step #1: Map opaque values
//
// Populate `valueStorageMap` in forward order (RPO), giving each opaque value
// an ordinal position.
//
// [REUSE] Assign a storage identifier to each opaque value. Optionally optimize
// storage by assigning multiple values the same identifier.
//
// ## Step #2: Allocate storage
//
// In reverse order (PO), allocate the parent storage object for each opaque
// value.
//
// [REUSE] If storage has already been allocated for the current live range,
// then simply reuse it.
//
// If the value's use composes a parent object from this value, and use's
// storage can be projected from, then mark the value's storage as a projection
// from the use value. [REUSE] Also inherit the use's storage identifier, and
// add an interval to the live range with the current projection path.
//
// A use can be projected from if its allocation is available at (dominates)
// this value and using the same storage over the interval from this value to
// the use does not overlap with the existing live range.
//
// Checking interference requires checking all operands that have been marked as
// projections. In the case of block arguments, it means checking the terminator
// operands of all predecessor blocks.
//
// [REUSE] Rather than checking all value operands, each live range will contain
// a set of intervals. Each interval will be associated with a projection path.
//
// Opaque value's that are the root of all projection paths now have their
// `storageAddress` assigned to an `alloc_stack` or argument. Opaque value's
// that are projections do not yet have a `storageAddress`.
//
// ## 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 projection of the value defined by its composing
// use, 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.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "address-lowering"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using llvm::SmallSetVector;
using llvm::PointerIntPair;
llvm::cl::opt<bool>
OptimizeOpaqueAddressLowering("optimize-opaque-address-lowering",
llvm::cl::init(false));
// Visit all call results.
// Stop when the visitor returns `false`.
static void visitCallResults(ApplySite apply,
llvm::function_ref<bool(SILValue)> visitor) {
// FIXME: this entire implementation only really works for ApplyInst.
auto applyInst = cast<ApplyInst>(apply);
if (applyInst->getType().is<TupleType>()) {
// TODO: MultiValueInstruction
for (auto *operand : applyInst->getUses()) {
if (auto extract = dyn_cast<TupleExtractInst>(operand->getUser()))
if (!visitor(extract))
break;
}
} else
visitor(applyInst);
}
//===----------------------------------------------------------------------===//
// ValueStorageMap: Map Opaque/Resilient SILValues to abstract storage units.
//===----------------------------------------------------------------------===//
namespace {
struct ValueStorage {
enum { IsProjectionMask = 0x1, IsRewrittenMask = 0x2 };
PointerIntPair<Operand *, 2, unsigned> projectionAndFlags;
/// The final address of this storage unit after rewriting the SIL.
/// For values linked to their own storage, this is set during storage
/// allocation. For projections, it is only set after instruction rewriting.
SILValue storageAddress;
bool isProjection() const {
return projectionAndFlags.getInt() & IsProjectionMask;
}
/// Return the operand the composes an aggregate from this value.
Operand *getComposedOperand() const {
assert(isProjection());
return projectionAndFlags.getPointer();
}
void setComposedOperand(Operand *oper) {
projectionAndFlags.setPointer(oper);
projectionAndFlags.setInt(projectionAndFlags.getInt() | IsProjectionMask);
}
bool isRewritten() const {
if (projectionAndFlags.getInt() & IsRewrittenMask) {
assert(storageAddress);
return true;
}
return false;
}
void markRewritten() {
projectionAndFlags.setInt(projectionAndFlags.getInt() | IsRewrittenMask);
}
};
/// Map each opaque/resilient SILValue to its abstract storage.
/// O(1) membership test.
/// O(n) iteration in RPO order.
class ValueStorageMap {
typedef std::vector<std::pair<SILValue, ValueStorage>> ValueVector;
// Hash of values to ValueVector indices.
typedef llvm::DenseMap<SILValue, unsigned> ValueHashMap;
ValueVector valueVector;
ValueHashMap valueHashMap;
public:
bool empty() const { return valueVector.empty(); }
void clear() {
valueVector.clear();
valueHashMap.clear();
}
ValueVector::iterator begin() { return valueVector.begin(); }
ValueVector::iterator end() { return valueVector.end(); }
ValueVector::reverse_iterator rbegin() { return valueVector.rbegin(); }
ValueVector::reverse_iterator rend() { return valueVector.rend(); }
bool contains(SILValue value) const {
return valueHashMap.find(value) != valueHashMap.end();
}
unsigned getOrdinal(SILValue value) {
auto hashIter = valueHashMap.find(value);
assert(hashIter != valueHashMap.end() && "Missing SILValue");
return hashIter->second;
}
ValueStorage &getStorage(SILValue value) {
return valueVector[getOrdinal(value)].second;
}
// This must be called in RPO order.
ValueStorage &insertValue(SILValue value) {
auto hashResult =
valueHashMap.insert(std::make_pair(value, valueVector.size()));
(void)hashResult;
assert(hashResult.second && "SILValue already mapped");
valueVector.emplace_back(value, ValueStorage());
return valueVector.back().second;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// AddressLoweringState: shared state for the pass's analysis and transforms.
//===----------------------------------------------------------------------===//
namespace {
struct AddressLoweringState {
SILFunction *F;
SILFunctionConventions loweredFnConv;
// Dominators remain valid throughout this pass.
DominanceInfo *domInfo;
// All opaque values and associated storage.
ValueStorageMap valueStorageMap;
// All call sites with formally indirect SILArgument or SILResult conventions.
// Calls are removed from the set when rewritten.
SmallSetVector<ApplySite, 16> indirectApplies;
// All function-exiting terminators (return or throw instructions).
SmallVector<TermInst *, 8> returnInsts;
// Delete these instructions after performing transformations.
// They must not have any remaining users.
SmallSetVector<SILInstruction *, 16> instsToDelete;
AddressLoweringState(SILFunction *F, DominanceInfo *domInfo)
: F(F),
loweredFnConv(F->getLoweredFunctionType(),
SILModuleConventions::getLoweredAddressConventions(F->getModule())),
domInfo(domInfo) {}
bool isDead(SILInstruction *inst) const { return instsToDelete.count(inst); }
void markDead(SILInstruction *inst) {
#ifndef NDEBUG
for (auto result : inst->getResults())
for (Operand *use : result->getUses())
assert(instsToDelete.count(use->getUser()));
#endif
instsToDelete.insert(inst);
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// OpaqueValueVisitor: Map OpaqueValues to ValueStorage.
//===----------------------------------------------------------------------===//
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.F) {}
void mapValueStorage();
protected:
void visitApply(ApplySite applySite);
void visitValue(SILValue value);
};
} // end anonymous namespace
/// Top-level entry: Populate `valueStorageMap`, `indirectResults`, and
/// `indirectOperands`.
///
/// Find all Opaque/Resilient SILValues and add them
/// to valueStorageMap in RPO.
void OpaqueValueVisitor::mapValueStorage() {
for (auto *BB : postorderInfo.getReversePostOrder()) {
if (BB->getTerminator()->isFunctionExiting())
pass.returnInsts.push_back(BB->getTerminator());
// Opaque function arguments have already been replaced.
if (BB != pass.F->getEntryBlock()) {
for (auto argI = BB->args_begin(), argEnd = BB->args_end();
argI != argEnd; ++argI) {
visitValue(*argI);
}
}
for (auto &II : *BB) {
if (auto apply = ApplySite::isa(&II))
visitApply(apply);
for (auto result : II.getResults())
visitValue(result);
}
}
}
/// Populate `indirectApplies` and insert this apply in `valueStorageMap` if
/// the call's non-tuple result is returned indirectly.
void OpaqueValueVisitor::visitApply(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);
}
}
++calleeArgIdx;
}
if (applySite.getSubstCalleeType()->hasIndirectFormalResults()) {
pass.indirectApplies.insert(applySite);
if (!applySite.getType().is<TupleType>())
pass.valueStorageMap.insertValue(cast<ApplyInst>(applySite));
return;
}
}
/// If `value` is address-only add it to the `valueStorageMap`.
void OpaqueValueVisitor::visitValue(SILValue value) {
if (value->getType().isObject()
&& value->getType().isAddressOnly(*pass.F)) {
if (pass.valueStorageMap.contains(value)) {
assert(isa<SILFunctionArgument>(
pass.valueStorageMap.getStorage(value).storageAddress));
return;
}
pass.valueStorageMap.insertValue(value);
}
}
//===----------------------------------------------------------------------===//
// OpaqueStorageAllocation: Generate alloc_stack and address projections for all
// abstract storage locations.
//===----------------------------------------------------------------------===//
namespace {
/// Allocate storage on the stack for every opaque value defined in this
/// function in RPO order. If the definition is an argument of this function,
/// simply replace the function argument with an address representing the
/// caller's storage.
///
/// TODO: shrink lifetimes by inserting alloc_stack at the dominance LCA and
/// finding the lifetime boundary with a simple backward walk from uses.
class OpaqueStorageAllocation {
AddressLoweringState &pass;
public:
explicit OpaqueStorageAllocation(AddressLoweringState &pass) : pass(pass) {}
void allocateOpaqueStorage();
protected:
void convertIndirectFunctionArgs();
unsigned insertIndirectReturnArgs();
bool canProjectFrom(SingleValueInstruction *innerVal,
SILInstruction *composingUse);
void allocateForValue(SILValue value, ValueStorage &storage);
};
} // end anonymous namespace
/// Top-level entry point: allocate storage for all opaque/resilient values.
void OpaqueStorageAllocation::allocateOpaqueStorage() {
// Fixup this function's argument types with temporary loads.
convertIndirectFunctionArgs();
// Create a new function argument for each indirect result.
insertIndirectReturnArgs();
// Populate valueStorageMap.
OpaqueValueVisitor(pass).mapValueStorage();
// Create an AllocStack for every opaque value defined in the function. Visit
// values in post-order to create storage for aggregates before subobjects.
for (auto &valueStorageI : llvm::reverse(pass.valueStorageMap))
allocateForValue(valueStorageI.first, valueStorageI.second);
}
/// Replace each value-typed argument to the current function with an
/// address-typed argument by inserting a temporary load instruction.
void OpaqueStorageAllocation::convertIndirectFunctionArgs() {
// Insert temporary argument loads at the top of the function.
SILBuilder argBuilder(pass.F->getEntryBlock()->begin());
argBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(pass.F->getModule()));
auto fnConv = pass.F->getConventions();
unsigned argIdx = fnConv.getSILArgIndexOfFirstParam();
for (SILParameterInfo param :
pass.F->getLoweredFunctionType()->getParameters()) {
if (param.isFormalIndirect() && !fnConv.isSILIndirect(param)) {
SILArgument *arg = pass.F->getArgument(argIdx);
SILType addrType = arg->getType().getAddressType();
LoadInst *loadArg = argBuilder.createLoad(
RegularLocation(const_cast<ValueDecl *>(arg->getDecl())),
SILUndef::get(addrType, *pass.F),
LoadOwnershipQualifier::Unqualified);
arg->replaceAllUsesWith(loadArg);
assert(!pass.valueStorageMap.contains(arg));
arg = arg->getParent()->replaceFunctionArgument(
arg->getIndex(), addrType, OwnershipKind::None, arg->getDecl());
loadArg->setOperand(arg);
if (addrType.isAddressOnly(*pass.F))
pass.valueStorageMap.insertValue(loadArg).storageAddress = arg;
}
++argIdx;
}
assert(argIdx
== fnConv.getSILArgIndexOfFirstParam() + fnConv.getNumSILArguments());
}
/// Insert function arguments for any @out result type. Return the number of
/// indirect result arguments added.
unsigned OpaqueStorageAllocation::insertIndirectReturnArgs() {
auto &ctx = pass.F->getModule().getASTContext();
unsigned argIdx = 0;
for (auto resultTy : pass.loweredFnConv.getIndirectSILResultTypes(
pass.F->getTypeExpansionContext())) {
auto bodyResultTy = pass.F->mapTypeIntoContext(resultTy);
auto var = new (ctx)
ParamDecl(SourceLoc(), SourceLoc(),
ctx.getIdentifier("$return_value"), SourceLoc(),
ctx.getIdentifier("$return_value"),
pass.F->getDeclContext());
var->setSpecifier(ParamSpecifier::InOut);
pass.F->begin()->insertFunctionArgument(
argIdx, bodyResultTy.getAddressType(), OwnershipKind::None, var);
++argIdx;
}
assert(argIdx == pass.loweredFnConv.getNumIndirectSILResults());
return argIdx;
}
/// Is this operand composing an aggregate from a subobject, or simply
/// forwarding the operand's value to storage defined elsewhere?
///
/// TODO: Handle struct.
/// TODO: Make this a visitor.
bool OpaqueStorageAllocation::canProjectFrom(SingleValueInstruction *innerVal,
SILInstruction *composingUse) {
if (!OptimizeOpaqueAddressLowering)
return false;
SILValue composingValue;
switch (composingUse->getKind()) {
default:
return false;
case SILInstructionKind::ApplyInst:
// @in operands never need their own storage since they are non-mutating
// uses. They simply reuse the storage allocated for their operand. So it
// wouldn't make sense to "project" out of the apply argument.
return false;
case SILInstructionKind::EnumInst:
composingValue = cast<EnumInst>(composingUse);
break;
case SILInstructionKind::InitExistentialValueInst: {
// Ensure that all opened archetypes are available at the inner value's
// definition.
auto *initExistential = cast<InitExistentialValueInst>(composingUse);
for (Operand &operand : initExistential->getTypeDependentOperands()) {
if (!pass.domInfo->properlyDominates(operand.get(), innerVal))
return false;
}
composingValue = initExistential;
break;
}
case SILInstructionKind::ReturnInst:
return true;
case SILInstructionKind::StoreInst: {
if (cast<StoreInst>(composingUse)->getSrc() == innerVal
&& isa<CopyValueInst>(innerVal)) {
return true;
}
return false;
}
case SILInstructionKind::TupleInst:
composingValue = cast<TupleInst>(composingUse);
break;
}
ValueStorage &storage = pass.valueStorageMap.getStorage(composingValue);
if (SILValue addr = storage.storageAddress) {
if (auto *stackInst = dyn_cast<AllocStackInst>(addr)) {
assert(pass.domInfo->properlyDominates(stackInst, innerVal));
return true;
}
if (isa<SILFunctionArgument>(addr)) {
return true;
}
} else if (storage.isProjection())
return canProjectFrom(innerVal, storage.getComposedOperand()->getUser());
return false;
}
/// Allocate storage for a single opaque/resilient value.
void OpaqueStorageAllocation::allocateForValue(SILValue value,
ValueStorage &storage) {
assert(!isa<SILFunctionArgument>(value));
if (auto apply = ApplySite::isa(value)) {
// Result tuples will be canonicalized during apply rewriting so the tuple
// itself is unused.
if (value->getType().is<TupleType>()) {
assert(apply.getSubstCalleeType()->getNumResults() > 1);
return;
}
}
// Argument loads already have a storage address.
if (storage.storageAddress) {
assert(isa<SILFunctionArgument>(storage.storageAddress));
return;
}
if (value->hasOneUse()) {
// TODO: Handle block arguments.
// TODO: Handle subobjects with a single composition, and other non-mutating
// uses such as @in arguments.
if (auto *def = dyn_cast<SingleValueInstruction>(value)) {
Operand *useOper = *value->use_begin();
if (canProjectFrom(def, useOper->getUser())) {
storage.setComposedOperand(useOper);
return;
}
}
}
SILBuilder allocBuilder(pass.F->begin()->begin());
allocBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(pass.F->getModule()));
AllocStackInst *allocInstr =
allocBuilder.createAllocStack(value.getLoc(), value->getType());
storage.storageAddress = allocInstr;
// Insert stack deallocations.
for (TermInst *termInst : pass.returnInsts) {
SILBuilder deallocBuilder(termInst);
deallocBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(pass.F->getModule()));
deallocBuilder.createDeallocStack(allocInstr->getLoc(), allocInstr);
}
}
//===----------------------------------------------------------------------===//
// AddressMaterialization - materialize storage addresses, generate projections.
//===----------------------------------------------------------------------===//
namespace {
/// Materialize the address of a value's storage. For values that are directly
/// mapped to a storage location, simply return the mapped `AllocStackInst`.
/// For subobjects emit any necessary `_addr` projections using the provided
/// `SILBuilder`.
///
/// This is a common utility for ApplyRewriter, AddressOnlyDefRewriter,
/// and AddressOnlyUseRewriter.
class AddressMaterialization {
AddressLoweringState &pass;
SILBuilder &B;
public:
AddressMaterialization(AddressLoweringState &pass, SILBuilder &B)
: pass(pass), B(B) {}
SILValue initializeOperandMem(Operand *operand);
SILValue materializeAddress(SILValue origValue);
protected:
SILValue materializeProjection(Operand *operand);
};
} // anonymous namespace
// Materialize an address pointing to initialized memory for this operand,
// generating a projection and copy if needed.
SILValue AddressMaterialization::initializeOperandMem(Operand *operand) {
SILValue def = operand->get();
SILValue destAddr;
if (operand->get()->getType().isAddressOnly(*pass.F)) {
ValueStorage &storage = pass.valueStorageMap.getStorage(def);
// Source value should already be rewritten.
assert(storage.isRewritten());
if (storage.isProjection())
destAddr = storage.storageAddress;
else {
destAddr = materializeProjection(operand);
B.createCopyAddr(operand->getUser()->getLoc(), storage.storageAddress,
destAddr, IsTake, IsInitialization);
}
} else {
destAddr = materializeProjection(operand);
B.createStore(operand->getUser()->getLoc(), operand->get(), destAddr,
StoreOwnershipQualifier::Unqualified);
}
return destAddr;
}
/// Return the address of the storage for `origValue`. This may involve
/// materializing projections.
SILValue AddressMaterialization::materializeAddress(SILValue origValue) {
ValueStorage &storage = pass.valueStorageMap.getStorage(origValue);
if (!storage.storageAddress)
storage.storageAddress =
materializeProjection(storage.getComposedOperand());
return storage.storageAddress;
}
SILValue AddressMaterialization::materializeProjection(Operand *operand) {
SILInstruction *user = operand->getUser();
switch (user->getKind()) {
default:
LLVM_DEBUG(user->dump());
llvm_unreachable("Unexpected subobject composition.");
case SILInstructionKind::EnumInst: {
auto *enumInst = cast<EnumInst>(user);
SILValue enumAddr = materializeAddress(enumInst);
return B.createInitEnumDataAddr(enumInst->getLoc(), enumAddr,
enumInst->getElement(),
operand->get()->getType().getAddressType());
}
case SILInstructionKind::InitExistentialValueInst: {
auto *initExistentialValue = cast<InitExistentialValueInst>(user);
SILValue containerAddr = materializeAddress(initExistentialValue);
auto canTy = initExistentialValue->getFormalConcreteType();
auto opaque = Lowering::AbstractionPattern::getOpaque();
auto &concreteTL = pass.F->getTypeLowering(opaque, canTy);
return B.createInitExistentialAddr(
initExistentialValue->getLoc(), containerAddr, canTy,
concreteTL.getLoweredType(), initExistentialValue->getConformances());
}
case SILInstructionKind::ReturnInst: {
assert(pass.loweredFnConv.hasIndirectSILResults());
return pass.F->getArguments()[0];
}
case SILInstructionKind::TupleInst: {
auto *tupleInst = cast<TupleInst>(user);
// Function return values.
if (tupleInst->hasOneUse()
&& isa<ReturnInst>(tupleInst->use_begin()->getUser())) {
unsigned resultIdx = tupleInst->getElementIndex(operand);
assert(resultIdx < pass.loweredFnConv.getNumIndirectSILResults());
// Cannot call getIndirectSILResults here because that API uses the
// original function type.
return pass.F->getArguments()[resultIdx];
}
// TODO: emit tuple_element_addr
llvm_unreachable("Unimplemented");
}
}
}
//===----------------------------------------------------------------------===//
// ApplyRewriter - rewrite call sites with indirect arguments.
//===----------------------------------------------------------------------===//
namespace {
/// Rewrite an Apply, lowering its indirect SIL arguments.
///
/// Replace indirect parameter arguments of this function with address-type
/// arguments.
///
/// Insert new indirect result arguments for this function to represent the
/// caller's storage.
class ApplyRewriter {
AddressLoweringState &pass;
ApplySite apply;
SILBuilder argBuilder;
/// For now, we assume that the apply site is a normal apply.
ApplyInst *getApplyInst() const { return cast<ApplyInst>(apply); }
public:
ApplyRewriter(ApplySite origCall, AddressLoweringState &pass)
: pass(pass), apply(origCall), argBuilder(origCall.getInstruction()) {
argBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(origCall.getModule()));
}
void rewriteParameters();
void rewriteIndirectParameter(Operand *operand);
void convertApplyWithIndirectResults();
protected:
void
canonicalizeResults(MutableArrayRef<SingleValueInstruction *> directResultValues,
ArrayRef<Operand *> nonCanonicalUses);
SILValue materializeIndirectResultAddress(
SingleValueInstruction *origDirectResultVal,
SILType argTy);
};
} // end anonymous namespace
/// Rewrite any indirect parameter in place.
void ApplyRewriter::rewriteParameters() {
// Rewrite all incoming indirect operands.
unsigned calleeArgIdx = apply.getCalleeArgIndexOfFirstAppliedArg();
for (Operand &operand : apply.getArgumentOperands()) {
if (operand.get()->getType().isObject()) {
auto argConv =
apply.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx);
if (argConv.isIndirectConvention())
rewriteIndirectParameter(&operand);
}
++calleeArgIdx;
}
}
/// Deallocate temporary call-site stack storage.
///
/// `argLoad` is non-null for @out args that are loaded.
static void insertStackDeallocationAtCall(AllocStackInst *allocInst,
SILInstruction *applyInst,
SILInstruction *argLoad) {
SILInstruction *lastUse = argLoad ? argLoad : applyInst;
switch (applyInst->getKind()) {
case SILInstructionKind::ApplyInst: {
SILBuilder deallocBuilder(&*std::next(lastUse->getIterator()));
deallocBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(applyInst->getModule()));
deallocBuilder.createDeallocStack(allocInst->getLoc(), allocInst);
break;
}
case SILInstructionKind::TryApplyInst:
// TODO!!!: insert dealloc in the catch block.
llvm_unreachable("not implemented for this instruction!");
case SILInstructionKind::PartialApplyInst:
llvm_unreachable("partial apply cannot have indirect results.");
default:
llvm_unreachable("not implemented for this instruction!");
}
}
/// Rewrite a formally indirect parameter in place.
/// Update the operand to the incoming value's storage address.
/// After this, the SIL argument types no longer match SIL function conventions.
///
/// Temporary argument storage may be created for loadable values.
///
/// Note: Temporary argument storage does not own its value. If the argument
/// is owned, the stored value should already have been copied.
void ApplyRewriter::rewriteIndirectParameter(Operand *operand) {
SILValue argValue = operand->get();
if (argValue->getType().isAddressOnly(*pass.F)) {
ValueStorage &storage = pass.valueStorageMap.getStorage(argValue);
// Source value should already be rewritten.
assert(storage.isRewritten());
operand->set(storage.storageAddress);
return;
}
// Allocate temporary storage for a loadable operand.
AllocStackInst *allocInstr =
argBuilder.createAllocStack(apply.getLoc(), argValue->getType());
argBuilder.createStore(apply.getLoc(), argValue, allocInstr,
StoreOwnershipQualifier::Unqualified);
operand->set(allocInstr);
insertStackDeallocationAtCall(allocInstr, apply.getInstruction(),
/*argLoad=*/nullptr);
}
// Canonicalize call result uses. Treat each result of a multi-result call as
// an independent value. Currently, SILGen may generate tuple_extract for each
// result but generate a single destroy_value for the entire tuple of
// results. This makes it impossible to reason about each call result as an
// independent value according to the callee's function type.
//
// directResultValues has an entry for each tuple extract corresponding to
// that result if one exists. This function will add an entry to
// directResultValues whenever it needs to materialize a TupleExtractInst.
void ApplyRewriter::canonicalizeResults(
MutableArrayRef<SingleValueInstruction *> directResultValues,
ArrayRef<Operand *> nonCanonicalUses) {
auto *applyInst = getApplyInst();
for (Operand *operand : nonCanonicalUses) {
auto *destroyInst = dyn_cast<DestroyValueInst>(operand->getUser());
if (!destroyInst)
llvm::report_fatal_error("Simultaneous use of multiple call results.");
for (unsigned resultIdx : indices(directResultValues)) {
SingleValueInstruction *result = directResultValues[resultIdx];
if (!result) {
SILBuilder resultBuilder(std::next(SILBasicBlock::iterator(applyInst)));
resultBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(applyInst->getModule()));
result = resultBuilder.createTupleExtract(applyInst->getLoc(),
applyInst, resultIdx);
directResultValues[resultIdx] = result;
}
SILBuilder B(destroyInst);
B.setSILConventions(SILModuleConventions::getLoweredAddressConventions(applyInst->getModule()));
auto &TL = pass.F->getTypeLowering(result->getType());
TL.emitDestroyValue(B, destroyInst->getLoc(), result);
}
destroyInst->eraseFromParent();
}
}
/// Return the storage address for the indirect result corresponding to the
/// given original result value. Allocate temporary argument storage for any
/// indirect results that are unmapped because they are loadable or unused.
///
/// origDirectResultVal may be nullptr for unused results.
SILValue ApplyRewriter::materializeIndirectResultAddress(
SingleValueInstruction *origDirectResultVal, SILType argTy) {
if (origDirectResultVal
&& origDirectResultVal->getType().isAddressOnly(*pass.F)) {
auto &storage = pass.valueStorageMap.getStorage(origDirectResultVal);
storage.markRewritten();
// Pass the local storage address as the indirect result address.
return storage.storageAddress;
}
// Allocate temporary call-site storage for an unused or loadable result.
SILInstruction *origCallInst = apply.getInstruction();
SILLocation loc = origCallInst->getLoc();
auto *allocInst = argBuilder.createAllocStack(loc, argTy);
LoadInst *loadInst = nullptr;
if (origDirectResultVal) {
// TODO: Find the try_apply's result block.
// Build results outside-in to next stack allocations.
SILBuilder resultBuilder(std::next(SILBasicBlock::iterator(origCallInst)));
resultBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(origCallInst->getModule()));
// This is a formally indirect argument, but is loadable.
loadInst = resultBuilder.createLoad(loc, allocInst,
LoadOwnershipQualifier::Unqualified);
origDirectResultVal->replaceAllUsesWith(loadInst);
pass.markDead(origDirectResultVal);
}
insertStackDeallocationAtCall(allocInst, origCallInst, loadInst);
return SILValue(allocInst);
}
/// Allocate storage for formally indirect results at the given call site.
/// Create a new call instruction with indirect SIL arguments.
void ApplyRewriter::convertApplyWithIndirectResults() {
assert(apply.getSubstCalleeType()->hasIndirectFormalResults());
auto *origCallInst = getApplyInst();
SILFunctionConventions origFnConv = apply.getSubstCalleeConv();
// Gather the original direct return values.
// Canonicalize results so no user uses more than one result.
SmallVector<SingleValueInstruction *, 8> origDirectResultValues(
origFnConv.getNumDirectSILResults());
SmallVector<Operand *, 4> nonCanonicalUses;
if (origCallInst->getType().is<TupleType>()) {
for (Operand *operand : origCallInst->getUses()) {
if (auto *extract = dyn_cast<TupleExtractInst>(operand->getUser()))
origDirectResultValues[extract->getFieldIndex()] = extract;
else
nonCanonicalUses.push_back(operand);
}
if (!nonCanonicalUses.empty())
canonicalizeResults(origDirectResultValues, nonCanonicalUses);
} else {
// This call has a single, indirect result (convertApplyWithIndirectResults
// only handles call with at least one indirect result).
// An unused result can remain unmapped. Temporary storage will be allocated
// later when fixing up the call's uses.
assert(origDirectResultValues.size() == 1);
if (!origCallInst->use_empty()) {
assert(pass.valueStorageMap.contains(origCallInst));
origDirectResultValues[0] = origCallInst;
}
}
// Prepare to emit a new call instruction.
SILLocation loc = origCallInst->getLoc();
SILBuilder callBuilder(origCallInst);
callBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(origCallInst->getModule()));
// The new call instruction's SIL calling convention.
SILFunctionConventions loweredCalleeConv(
apply.getSubstCalleeType(),
SILModuleConventions::getLoweredAddressConventions(origCallInst->getModule()));
// The new call instruction's SIL argument list.
SmallVector<SILValue, 8> newCallArgs(loweredCalleeConv.getNumSILArguments());
// Map the original result indices to new result indices.
SmallVector<unsigned, 8> newDirectResultIndices(
origFnConv.getNumDirectSILResults());
// Indices used to populate newDirectResultIndices.
unsigned oldDirectResultIdx = 0, newDirectResultIdx = 0;
// The index of the next indirect result argument.
unsigned newResultArgIdx =
loweredCalleeConv.getSILArgIndexOfFirstIndirectResult();
// Visit each result. Redirect results that are now indirect by calling
// materializeIndirectResultAddress. Result that remain direct will be
// redirected later. Populate newCallArgs and newDirectResultIndices.
for_each(
apply.getSubstCalleeType()->getResults(),
origDirectResultValues,
[&](SILResultInfo resultInfo, SingleValueInstruction *origDirectResultVal) {
// Assume that all original results are direct in SIL.
assert(!origFnConv.isSILIndirect(resultInfo));
if (loweredCalleeConv.isSILIndirect(resultInfo)) {
SILValue indirectResultAddr = materializeIndirectResultAddress(
origDirectResultVal,
loweredCalleeConv.getSILType(
resultInfo, callBuilder.getTypeExpansionContext()));
// Record the new indirect call argument.
newCallArgs[newResultArgIdx++] = indirectResultAddr;
// Leave a placeholder for indirect results.
newDirectResultIndices[oldDirectResultIdx++] = ~0;
} else {
// Record the new direct result, and advance the direct result indices.
newDirectResultIndices[oldDirectResultIdx++] = newDirectResultIdx++;
}
// replaceAllUses will be called later to handle direct results that
// remain direct results of the new call instruction.
});
// Append the existing call arguments to the SIL argument list. They were
// already lowered to addresses by rewriteIncomingArgument.
assert(newResultArgIdx == loweredCalleeConv.getSILArgIndexOfFirstParam());
unsigned origArgIdx = apply.getSubstCalleeConv().getSILArgIndexOfFirstParam();
for (unsigned endIdx = newCallArgs.size(); newResultArgIdx < endIdx;
++newResultArgIdx, ++origArgIdx) {
newCallArgs[newResultArgIdx] = apply.getArgument(origArgIdx);
}
// Create a new apply with indirect result operands.
ApplyInst *newCallInst;
switch (origCallInst->getKind()) {
case SILInstructionKind::ApplyInst:
newCallInst = callBuilder.createApply(
loc, apply.getCallee(), apply.getSubstitutionMap(), newCallArgs,
cast<ApplyInst>(origCallInst)->getApplyOptions());
break;
case SILInstructionKind::TryApplyInst:
// TODO: insert dealloc in the catch block.
llvm_unreachable("not implemented for this instruction!");
case SILInstructionKind::PartialApplyInst:
// Partial apply does not have formally indirect results.
default:
llvm_unreachable("not implemented for this instruction!");
}
// Replace all unmapped uses of the original call with uses of the new call.
//
// TODO: handle bbargs from try_apply.
SILBuilder resultBuilder(
std::next(SILBasicBlock::iterator(origCallInst)));
resultBuilder.setSILConventions(
SILModuleConventions::getLoweredAddressConventions(apply.getModule()));
SmallVector<Operand*, 8> origUses(origCallInst->getUses());
for (Operand *operand : origUses) {
auto *extractInst = dyn_cast<TupleExtractInst>(operand->getUser());
if (!extractInst) {