forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILCombinerMiscVisitors.cpp
2138 lines (1899 loc) · 75.6 KB
/
SILCombinerMiscVisitors.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
//===--- SILCombinerMiscVisitors.cpp --------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "SILCombiner.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Basic/STLExtras.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/NodeBits.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/ValueTracking.h"
#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/Devirtualize.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using namespace swift::PatternMatch;
/// This flag is used to disable alloc stack optimizations to ease testing of
/// other SILCombine optimizations.
static llvm::cl::opt<bool>
DisableAllocStackOpts("sil-combine-disable-alloc-stack-opts",
llvm::cl::init(false));
SILInstruction*
SILCombiner::visitAllocExistentialBoxInst(AllocExistentialBoxInst *AEBI) {
// Optimize away the pattern below that happens when exceptions are created
// and in some cases, due to inlining, are not needed.
//
// %6 = alloc_existential_box $Error, $ColorError
// %6a = project_existential_box %6
// %7 = enum $VendingMachineError, #ColorError.Red
// store %7 to %6a : $*ColorError
// debug_value %6 : $Error
// strong_release %6 : $Error
//
// %6 = alloc_existential_box $Error, $ColorError
// %6a = project_existential_box %6
// %7 = enum $VendingMachineError, #ColorError.Red
// store %7 to [init] %6a : $*ColorError
// debug_value %6 : $Error
// destroy_value %6 : $Error
SILValue boxedValue =
getConcreteValueOfExistentialBox(AEBI, /*ignoreUser*/ nullptr);
if (!boxedValue)
return nullptr;
// Check if the box is destroyed at a single place. That's the end of its
// lifetime.
SILInstruction *singleDestroy = nullptr;
if (hasOwnership()) {
if (auto *use = AEBI->getSingleConsumingUse()) {
singleDestroy = dyn_cast<DestroyValueInst>(use->getUser());
}
} else {
for (Operand *use : AEBI->getUses()) {
auto *user = use->getUser();
if (isa<StrongReleaseInst>(user) || isa<ReleaseValueInst>(user)) {
if (singleDestroy)
return nullptr;
singleDestroy = user;
}
}
}
if (!singleDestroy)
return nullptr;
// Release the value that was stored into the existential box. The box
// is going away so we need to release the stored value.
// NOTE: It's important that the release is inserted at the single
// release of the box and not at the store, because a balancing retain could
// be _after_ the store, e.g:
// %box = alloc_existential_box
// %addr = project_existential_box %box
// store %value to %addr
// retain_value %value // must insert the release after this retain
// strong_release %box
Builder.setInsertionPoint(singleDestroy);
Builder.emitDestroyValueOperation(AEBI->getLoc(), boxedValue);
eraseInstIncludingUsers(AEBI);
return nullptr;
}
/// Return the enum case injected by an inject_enum_addr if it is the only
/// instruction which writes to \p Addr.
static EnumElementDecl *getInjectEnumCaseTo(SILValue Addr) {
while (true) {
// For everything else than an alloc_stack we cannot easily prove that we
// see all writes.
if (!isa<AllocStackInst>(Addr))
return nullptr;
SILInstruction *WritingInst = nullptr;
int NumWrites = 0;
for (auto *Use : getNonDebugUses(Addr)) {
SILInstruction *User = Use->getUser();
switch (User->getKind()) {
// Handle a very narrow set of known not harmful instructions.
case swift::SILInstructionKind::DestroyAddrInst:
case swift::SILInstructionKind::DeallocStackInst:
case swift::SILInstructionKind::SwitchEnumAddrInst:
break;
case swift::SILInstructionKind::ApplyInst:
case swift::SILInstructionKind::TryApplyInst: {
// Check if the addr is only passed to in_guaranteed arguments.
FullApplySite AI(User);
for (Operand &Op : AI.getArgumentOperands()) {
if (Op.get() == Addr &&
AI.getArgumentConvention(Op) !=
SILArgumentConvention::Indirect_In_Guaranteed)
return nullptr;
}
break;
}
case swift::SILInstructionKind::InjectEnumAddrInst:
WritingInst = User;
++NumWrites;
break;
case swift::SILInstructionKind::CopyAddrInst:
if (Addr == cast<CopyAddrInst>(User)->getDest()) {
WritingInst = User;
++NumWrites;
}
break;
default:
return nullptr;
}
}
if (NumWrites != 1)
return nullptr;
if (auto *IEA = dyn_cast<InjectEnumAddrInst>(WritingInst))
return IEA->getElement();
// In case of a copy_addr continue with the source of the copy.
Addr = dyn_cast<CopyAddrInst>(WritingInst)->getSrc();
}
}
SILInstruction *SILCombiner::visitSwitchEnumAddrInst(SwitchEnumAddrInst *SEAI) {
SILValue Addr = SEAI->getOperand();
// Convert switch_enum_addr -> br
//
// If the only thing which writes to the address is an inject_enum_addr. We
// only perform these optimizations when we are not in OSSA since this
// eliminates an edge from the CFG and we want SILCombine in OSSA to never do
// that, so in the future we can invalidate less.
if (!SEAI->getFunction()->hasOwnership()) {
if (EnumElementDecl *EnumCase = getInjectEnumCaseTo(Addr)) {
SILBasicBlock *Dest = SEAI->getCaseDestination(EnumCase);
// If the only instruction which writes to Addr is an inject_enum_addr we
// know that there cannot be an enum payload.
assert(Dest->getNumArguments() == 0 &&
"didn't expect a payload argument");
Builder.createBranch(SEAI->getLoc(), Dest);
return eraseInstFromFunction(*SEAI);
}
}
SILType Ty = Addr->getType();
if (!Ty.isLoadable(*SEAI->getFunction()))
return nullptr;
// Promote switch_enum_addr to switch_enum if the enum is loadable.
// switch_enum_addr %ptr : $*Optional<SomeClass>, case ...
// ->
// %value = load %ptr
// switch_enum %value
//
// If we are using ownership, we perform a load_borrow right before the new
// switch_enum and end the borrow scope right afterwards.
Builder.setCurrentDebugScope(SEAI->getDebugScope());
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 8> Cases;
for (int i : range(SEAI->getNumCases())) {
Cases.push_back(SEAI->getCase(i));
}
SILBasicBlock *Default = SEAI->hasDefault() ? SEAI->getDefaultBB() : nullptr;
SILValue EnumVal = Builder.emitLoadBorrowOperation(SEAI->getLoc(), Addr);
auto *sei = Builder.createSwitchEnum(SEAI->getLoc(), EnumVal, Default, Cases);
if (Builder.hasOwnership()) {
for (int i : range(sei->getNumCases())) {
auto c = sei->getCase(i);
if (c.first->hasAssociatedValues()) {
auto eltType = Addr->getType().getEnumElementType(
c.first, Builder.getModule(), Builder.getTypeExpansionContext());
eltType = eltType.getObjectType();
sei->createResult(c.second, eltType);
}
Builder.setInsertionPoint(c.second->front().getIterator());
Builder.emitEndBorrowOperation(sei->getLoc(), EnumVal);
}
sei->createDefaultResult();
if (auto defaultBlock = sei->getDefaultBBOrNull()) {
Builder.setInsertionPoint(defaultBlock.get()->front().getIterator());
Builder.emitEndBorrowOperation(sei->getLoc(), EnumVal);
}
}
return eraseInstFromFunction(*SEAI);
}
SILInstruction *SILCombiner::visitSelectEnumAddrInst(SelectEnumAddrInst *seai) {
// Canonicalize a select_enum_addr: if the default refers to exactly one case,
// then replace the default with that case.
Builder.setCurrentDebugScope(seai->getDebugScope());
if (seai->hasDefault()) {
NullablePtr<EnumElementDecl> elementDecl = seai->getUniqueCaseForDefault();
if (elementDecl.isNonNull()) {
// Construct a new instruction by copying all the case entries.
SmallVector<std::pair<EnumElementDecl *, SILValue>, 4> caseValues;
for (int idx = 0, numIdcs = seai->getNumCases(); idx < numIdcs; ++idx) {
caseValues.push_back(seai->getCase(idx));
}
// Add the default-entry of the original instruction as case-entry.
caseValues.push_back(
std::make_pair(elementDecl.get(), seai->getDefaultResult()));
return Builder.createSelectEnumAddr(
seai->getLoc(), seai->getEnumOperand(), seai->getType(), SILValue(),
caseValues);
}
}
// Promote select_enum_addr to select_enum if the enum is loadable.
// = select_enum_addr %ptr : $*Optional<SomeClass>, case ...
// ->
// %value = load %ptr
// = select_enum %value
SILType ty = seai->getEnumOperand()->getType();
if (!ty.isLoadable(*seai->getFunction()))
return nullptr;
SmallVector<std::pair<EnumElementDecl *, SILValue>, 8> cases;
for (int i = 0, e = seai->getNumCases(); i < e; ++i)
cases.push_back(seai->getCase(i));
SILValue defaultCase =
seai->hasDefault() ? seai->getDefaultResult() : SILValue();
auto enumVal =
Builder.emitLoadBorrowOperation(seai->getLoc(), seai->getEnumOperand());
auto *result = Builder.createSelectEnum(seai->getLoc(), enumVal,
seai->getType(), defaultCase, cases);
Builder.emitEndBorrowOperation(seai->getLoc(), enumVal);
replaceInstUsesWith(*seai, result);
return eraseInstFromFunction(*seai);
}
SILInstruction *SILCombiner::visitSwitchValueInst(SwitchValueInst *svi) {
SILValue cond = svi->getOperand();
BuiltinIntegerType *condTy = cond->getType().getAs<BuiltinIntegerType>();
if (!condTy || !condTy->isFixedWidth(1))
return nullptr;
SILBasicBlock *falseBB = nullptr;
SILBasicBlock *trueBB = nullptr;
for (unsigned idx : range(svi->getNumCases())) {
auto switchCase = svi->getCase(idx);
auto *caseVal = dyn_cast<IntegerLiteralInst>(switchCase.first);
if (!caseVal)
return nullptr;
SILBasicBlock *destBB = switchCase.second;
assert(destBB->args_empty() &&
"switch_value case destination cannot take arguments");
if (caseVal->getValue() == 0) {
assert(!falseBB && "double case value 0 in switch_value");
falseBB = destBB;
} else {
assert(!trueBB && "double case value 1 in switch_value");
trueBB = destBB;
}
}
if (svi->hasDefault()) {
assert(svi->getDefaultBB()->args_empty() &&
"switch_value default destination cannot take arguments");
if (!falseBB) {
falseBB = svi->getDefaultBB();
} else if (!trueBB) {
trueBB = svi->getDefaultBB();
}
}
if (!falseBB || !trueBB)
return nullptr;
Builder.setCurrentDebugScope(svi->getDebugScope());
return Builder.createCondBranch(svi->getLoc(), cond, trueBB, falseBB);
}
namespace {
/// A SILInstruction visitor that analyzes alloc stack values for dead live
/// range and promotion opportunities.
///
/// init_existential_addr instructions behave like memory allocation within the
/// allocated object. We can promote the init_existential_addr allocation into a
/// dedicated allocation.
///
/// We detect this pattern
/// %0 = alloc_stack $LogicValue
/// %1 = init_existential_addr %0 : $*LogicValue, $*Bool
/// ...
/// use of %1
/// ...
/// destroy_addr %0 : $*LogicValue
/// dealloc_stack %0 : $*LogicValue
///
/// At the same we time also look for dead alloc_stack live ranges that are only
/// copied into.
///
/// %0 = alloc_stack
/// copy_addr %src, %0
/// destroy_addr %0 : $*LogicValue
/// dealloc_stack %0 : $*LogicValue
struct AllocStackAnalyzer : SILInstructionVisitor<AllocStackAnalyzer> {
/// The alloc_stack that we are analyzing.
AllocStackInst *ASI;
/// Do all of the users of the alloc stack allow us to perform optimizations.
bool LegalUsers = true;
/// If we saw an init_existential_addr in the use list of the alloc_stack,
/// this is the init_existential_addr. We are conservative in the face of
/// having multiple init_existential_addr. In such a case, we say that the use
/// list of the alloc_stack does not allow for optimizations to occur.
InitExistentialAddrInst *IEI = nullptr;
/// If we saw an open_existential_addr in the use list of the alloc_stack,
/// this is the open_existential_addr. We are conservative in the case of
/// multiple open_existential_addr. In such a case, we say that the use list
/// of the alloc_stack does not allow for optimizations to occur.
OpenExistentialAddrInst *OEI = nullptr;
/// Did we see any copies into the alloc stack.
bool HaveSeenCopyInto = false;
public:
AllocStackAnalyzer(AllocStackInst *ASI) : ASI(ASI) {}
/// Analyze the alloc_stack instruction's uses.
void analyze() {
// Scan all of the uses of the AllocStack and check if it is not used for
// anything other than the init_existential_addr/open_existential_addr
// container.
// There is no interesting scenario where a non-copyable type should have
// its allocation eliminated. A destroy_addr cannot be removed because it
// may run the struct-deinit, and the lifetime cannot be shortened. A
// copy_addr [take] [init] cannot be replaced by a destroy_addr because the
// destination may hold a 'discard'ed value, which is never destroyed. This
// analysis assumes memory is deinitialized on all paths, which is not the
// case for discarded values. Eventually copyable types may also be
// discarded; to support that, we will leave a drop_deinit_addr in place.
if (ASI->getType().getASTType()->isNoncopyable()) {
LegalUsers = false;
return;
}
for (auto *Op : getNonDebugUses(ASI)) {
visit(Op->getUser());
// If we found a non-legal user, bail early.
if (!LegalUsers)
break;
}
}
/// Given an unhandled case, we have an illegal use for our optimization
/// purposes. Set LegalUsers to false and return.
void visitSILInstruction(SILInstruction *I) { LegalUsers = false; }
// Destroy and dealloc are both fine.
void visitDestroyAddrInst(DestroyAddrInst *I) {}
void visitDeinitExistentialAddrInst(DeinitExistentialAddrInst *I) {}
void visitDeallocStackInst(DeallocStackInst *I) {}
void visitInitExistentialAddrInst(InitExistentialAddrInst *I) {
// If we have already seen an init_existential_addr, we cannot
// optimize. This is because we only handle the single init_existential_addr
// case.
if (IEI || HaveSeenCopyInto) {
LegalUsers = false;
return;
}
IEI = I;
}
void visitOpenExistentialAddrInst(OpenExistentialAddrInst *I) {
// If we have already seen an open_existential_addr, we cannot
// optimize. This is because we only handle the single open_existential_addr
// case.
if (OEI) {
LegalUsers = false;
return;
}
// Make sure that the open_existential does not have any uses except
// destroy_addr.
for (auto *Use : getNonDebugUses(I)) {
if (!isa<DestroyAddrInst>(Use->getUser())) {
LegalUsers = false;
return;
}
}
OEI = I;
}
void visitCopyAddrInst(CopyAddrInst *I) {
if (IEI) {
LegalUsers = false;
return;
}
// Copies into the alloc_stack live range are safe.
if (I->getDest() == ASI) {
HaveSeenCopyInto = true;
return;
}
LegalUsers = false;
}
};
} // end anonymous namespace
/// Returns true if there is a retain instruction between \p from and the
/// destroy or deallocation of \p alloc.
static bool somethingIsRetained(SILInstruction *from, AllocStackInst *alloc) {
llvm::SmallVector<SILInstruction *, 8> workList;
BasicBlockSet handled(from->getFunction());
workList.push_back(from);
while (!workList.empty()) {
SILInstruction *start = workList.pop_back_val();
for (auto iter = start->getIterator(), end = start->getParent()->end();
iter != end;
++iter) {
SILInstruction *inst = &*iter;
if (isa<RetainValueInst>(inst) || isa<StrongRetainInst>(inst)) {
return true;
}
if ((isa<DeallocStackInst>(inst) || isa<DestroyAddrInst>(inst)) &&
inst->getOperand(0) == alloc) {
break;
}
if (isa<TermInst>(inst)) {
for (SILBasicBlock *succ : start->getParent()->getSuccessors()) {
if (handled.insert(succ))
workList.push_back(&*succ->begin());
}
}
}
}
return false;
}
/// Replaces an alloc_stack of an enum by an alloc_stack of the payload if only
/// one enum case (with payload) is stored to that location.
///
/// For example:
///
/// %loc = alloc_stack $Optional<T>
/// %payload = init_enum_data_addr %loc
/// store %value to %payload
/// ...
/// %take_addr = unchecked_take_enum_data_addr %loc
/// %l = load %take_addr
///
/// is transformed to
///
/// %loc = alloc_stack $T
/// store %value to %loc
/// ...
/// %l = load %loc
bool SILCombiner::optimizeStackAllocatedEnum(AllocStackInst *AS) {
EnumDecl *enumDecl = AS->getType().getEnumOrBoundGenericEnum();
if (!enumDecl)
return false;
EnumElementDecl *element = nullptr;
unsigned numInits =0;
unsigned numTakes = 0;
SILBasicBlock *initBlock = nullptr;
SILBasicBlock *takeBlock = nullptr;
SILType payloadType;
// First step: check if the stack location is only used to hold one specific
// enum case with payload.
for (auto *use : AS->getUses()) {
SILInstruction *user = use->getUser();
switch (user->getKind()) {
case SILInstructionKind::DestroyAddrInst:
case SILInstructionKind::DeallocStackInst:
case SILInstructionKind::InjectEnumAddrInst:
// We'll check init_enum_addr below.
break;
case SILInstructionKind::DebugValueInst:
if (DebugValueInst::hasAddrVal(user))
break;
return false;
case SILInstructionKind::InitEnumDataAddrInst: {
auto *ieda = cast<InitEnumDataAddrInst>(user);
auto *el = ieda->getElement();
if (element && el != element)
return false;
element = el;
assert(!payloadType || payloadType == ieda->getType());
payloadType = ieda->getType();
numInits++;
initBlock = user->getParent();
break;
}
case SILInstructionKind::UncheckedTakeEnumDataAddrInst: {
auto *el = cast<UncheckedTakeEnumDataAddrInst>(user)->getElement();
if (element && el != element)
return false;
element = el;
numTakes++;
takeBlock = user->getParent();
break;
}
default:
return false;
}
}
if (!element || !payloadType)
return false;
// If the enum has a single init-take pair in a single block, we know that
// the enum cannot contain any valid payload outside that init-take pair.
//
// This also means that we can ignore any inject_enum_addr of another enum
// case, because this can only inject a case without a payload.
bool singleInitTakePair =
(numInits == 1 && numTakes == 1 && initBlock == takeBlock);
if (!singleInitTakePair) {
// No single init-take pair: We cannot ignore inject_enum_addrs with a
// mismatching case.
for (auto *use : AS->getUses()) {
if (auto *inject = dyn_cast<InjectEnumAddrInst>(use->getUser())) {
if (inject->getElement() != element)
return false;
}
}
}
// Second step: replace the enum alloc_stack with a payload alloc_stack.
auto *newAlloc = Builder.createAllocStack(
AS->getLoc(), payloadType, AS->getVarInfo(), AS->hasDynamicLifetime());
while (!AS->use_empty()) {
Operand *use = *AS->use_begin();
SILInstruction *user = use->getUser();
switch (user->getKind()) {
case SILInstructionKind::InjectEnumAddrInst:
eraseInstFromFunction(*user);
break;
case SILInstructionKind::DestroyAddrInst:
if (singleInitTakePair) {
// It's not possible that the enum has a payload at the destroy_addr,
// because it must have already been taken by the take of the
// single init-take pair.
// We _have_ to remove the destroy_addr, because we also remove all
// inject_enum_addrs which might inject a payload-less case before
// the destroy_addr.
eraseInstFromFunction(*user);
} else {
// The enum payload can still be valid at the destroy_addr, so we have
// to keep the destroy_addr. Just replace the enum with the payload
// (and because it's not a singleInitTakePair, we can be sure that the
// enum cannot have any other case than the payload case).
use->set(newAlloc);
}
break;
case SILInstructionKind::DeallocStackInst:
use->set(newAlloc);
break;
case SILInstructionKind::InitEnumDataAddrInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst: {
auto *svi = cast<SingleValueInstruction>(user);
svi->replaceAllUsesWith(newAlloc);
eraseInstFromFunction(*svi);
break;
}
case SILInstructionKind::DebugValueInst:
if (DebugValueInst::hasAddrVal(user)) {
eraseInstFromFunction(*user);
break;
}
LLVM_FALLTHROUGH;
default:
llvm_unreachable("unexpected alloc_stack user");
}
}
return true;
}
SILInstruction *SILCombiner::visitAllocStackInst(AllocStackInst *AS) {
if (AS->getFunction()->hasOwnership())
return nullptr;
if (optimizeStackAllocatedEnum(AS))
return nullptr;
// If we are testing SILCombine and we are asked not to eliminate
// alloc_stacks, just return.
if (DisableAllocStackOpts)
return nullptr;
AllocStackAnalyzer Analyzer(AS);
Analyzer.analyze();
// If when analyzing, we found a user that makes our optimization, illegal,
// bail early.
if (!Analyzer.LegalUsers)
return nullptr;
InitExistentialAddrInst *IEI = Analyzer.IEI;
OpenExistentialAddrInst *OEI = Analyzer.OEI;
// If the only users of the alloc_stack are alloc, destroy and
// init_existential_addr then we can promote the allocation of the init
// existential.
// Be careful with open archetypes, because they cannot be moved before
// their definitions.
if (IEI && !OEI &&
!IEI->getLoweredConcreteType().hasOpenedExistential()) {
assert(!IEI->getLoweredConcreteType().isOpenedExistential());
auto *ConcAlloc = Builder.createAllocStack(
AS->getLoc(), IEI->getLoweredConcreteType(), AS->getVarInfo());
IEI->replaceAllUsesWith(ConcAlloc);
eraseInstFromFunction(*IEI);
for (auto UI = AS->use_begin(), UE = AS->use_end(); UI != UE;) {
auto *Op = *UI;
++UI;
if (auto *DA = dyn_cast<DestroyAddrInst>(Op->getUser())) {
Builder.setInsertionPoint(DA);
Builder.createDestroyAddr(DA->getLoc(), ConcAlloc);
eraseInstFromFunction(*DA);
continue;
}
if (isa<DeinitExistentialAddrInst>(Op->getUser())) {
eraseInstFromFunction(*Op->getUser());
continue;
}
if (!isa<DeallocStackInst>(Op->getUser()))
continue;
auto *DS = cast<DeallocStackInst>(Op->getUser());
Builder.setInsertionPoint(DS);
Builder.createDeallocStack(DS->getLoc(), ConcAlloc);
eraseInstFromFunction(*DS);
}
return eraseInstFromFunction(*AS);
}
// If we have a live 'live range' or a live range that we have not sen a copy
// into, bail.
if (!Analyzer.HaveSeenCopyInto || IEI)
return nullptr;
// Otherwise remove the dead live range that is only copied into.
//
// TODO: Do we not remove purely dead live ranges here? Seems like we should.
SmallPtrSet<SILInstruction *, 16> ToDelete;
SmallVector<CopyAddrInst *, 4> takingCopies;
for (auto *Op : AS->getUses()) {
// Replace a copy_addr [take] %src ... by a destroy_addr %src if %src is
// no the alloc_stack.
// Otherwise, just delete the copy_addr.
if (auto *CopyAddr = dyn_cast<CopyAddrInst>(Op->getUser())) {
if (CopyAddr->isTakeOfSrc() && CopyAddr->getSrc() != AS) {
takingCopies.push_back(CopyAddr);
}
}
if (auto *OEAI = dyn_cast<OpenExistentialAddrInst>(Op->getUser())) {
for (auto *Op : OEAI->getUses()) {
assert(isa<DestroyAddrInst>(Op->getUser()) ||
Op->getUser()->isDebugInstruction() && "Unexpected instruction");
ToDelete.insert(Op->getUser());
}
}
assert(isa<CopyAddrInst>(Op->getUser()) ||
isa<OpenExistentialAddrInst>(Op->getUser()) ||
isa<DestroyAddrInst>(Op->getUser()) ||
isa<DeallocStackInst>(Op->getUser()) ||
isa<DeinitExistentialAddrInst>(Op->getUser()) ||
Op->getUser()->isDebugInstruction() && "Unexpected instruction");
ToDelete.insert(Op->getUser());
}
// Check if a retain is moved after the copy_addr. If the retained object
// happens to be the source of the copy_addr it might be only kept alive by
// the stack location. This cannot happen with OSSA.
// TODO: remove this check once we have OSSA.
for (CopyAddrInst *copy : takingCopies) {
if (somethingIsRetained(copy, AS))
return nullptr;
}
for (CopyAddrInst *copy : takingCopies) {
SILBuilderWithScope destroyBuilder(copy, Builder.getBuilderContext());
destroyBuilder.createDestroyAddr(copy->getLoc(), copy->getSrc());
}
// Erase the 'live-range'
for (auto *Inst : ToDelete) {
Inst->replaceAllUsesOfAllResultsWithUndef();
eraseInstFromFunction(*Inst);
}
return eraseInstFromFunction(*AS);
}
/// Returns the base address if \p val is an index_addr with constant index.
static SILValue isConstIndexAddr(SILValue val, unsigned &index) {
auto *IA = dyn_cast<IndexAddrInst>(val);
if (!IA)
return nullptr;
auto *Index = dyn_cast<IntegerLiteralInst>(IA->getIndex());
// Limiting to 32 bits is more than enough. The reason why not limiting to 64
// bits is to leave room for overflow when we add two indices.
if (!Index || Index->getValue().getActiveBits() > 32)
return nullptr;
index = Index->getValue().getZExtValue();
return IA->getBase();
}
SILInstruction *SILCombiner::visitLoadBorrowInst(LoadBorrowInst *lbi) {
// If we have a load_borrow that only has non_debug end_borrow uses, delete
// it.
if (llvm::all_of(getNonDebugUses(lbi), [](Operand *use) {
return isa<EndBorrowInst>(use->getUser());
})) {
eraseInstIncludingUsers(lbi);
return nullptr;
}
return nullptr;
}
/// Optimize nested index_addr instructions:
/// Example in SIL pseudo code:
/// %1 = index_addr %ptr, x
/// %2 = index_addr %1, y
/// ->
/// %2 = index_addr %ptr, x+y
SILInstruction *SILCombiner::visitIndexAddrInst(IndexAddrInst *IA) {
unsigned index = 0;
SILValue base = isConstIndexAddr(IA, index);
if (!base)
return nullptr;
unsigned index2 = 0;
SILValue base2 = isConstIndexAddr(base, index2);
if (!base2)
return nullptr;
auto *newIndex = Builder.createIntegerLiteral(IA->getLoc(),
IA->getIndex()->getType(), index + index2);
return Builder.createIndexAddr(IA->getLoc(), base2, newIndex,
IA->needsStackProtection() || cast<IndexAddrInst>(base)->needsStackProtection());
}
SILInstruction *SILCombiner::visitCondFailInst(CondFailInst *CFI) {
// Remove runtime asserts such as overflow checks and bounds checks.
if (RemoveCondFails)
return eraseInstFromFunction(*CFI);
auto *I = dyn_cast<IntegerLiteralInst>(CFI->getOperand());
if (!I)
return nullptr;
// Erase. (cond_fail 0)
if (!I->getValue().getBoolValue())
return eraseInstFromFunction(*CFI);
// Remove non-lifetime-ending code that follows a (cond_fail 1) and set the
// block's terminator to unreachable.
// Are there instructions after this point to delete?
// First check if the next instruction is unreachable.
if (isa<UnreachableInst>(std::next(SILBasicBlock::iterator(CFI))))
return nullptr;
// Otherwise, check if the only instructions are unreachables and destroys of
// lexical values.
// Collect all instructions and, in OSSA, the values they define.
llvm::SmallVector<SILInstruction *, 32> ToRemove;
ValueSet DefinedValues(CFI->getFunction());
for (auto Iter = std::next(CFI->getIterator());
Iter != CFI->getParent()->end(); ++Iter) {
if (!CFI->getFunction()->hasOwnership()) {
ToRemove.push_back(&*Iter);
continue;
}
for (auto result : Iter->getResults()) {
DefinedValues.insert(result);
}
// Look for destroys of lexical values whose def isn't after the cond_fail.
if (auto *dvi = dyn_cast<DestroyValueInst>(&*Iter)) {
auto value = dvi->getOperand();
if (!DefinedValues.contains(value) && value->isLexical())
continue;
}
ToRemove.push_back(&*Iter);
}
unsigned instructionsToDelete = ToRemove.size();
// If the last instruction is an unreachable already, it needn't be deleted.
if (isa<UnreachableInst>(ToRemove.back())) {
--instructionsToDelete;
}
if (instructionsToDelete == 0)
return nullptr;
for (auto *Inst : ToRemove) {
// Replace any still-remaining uses with undef and erase.
Inst->replaceAllUsesOfAllResultsWithUndef();
eraseInstFromFunction(*Inst);
}
// Add an `unreachable` to be the new terminator for this block
Builder.setInsertionPoint(CFI->getParent());
Builder.createUnreachable(ArtificialUnreachableLocation());
return nullptr;
}
/// Create a value from stores to an address.
///
/// If there are only stores to \p addr, return the stored value. Also, if there
/// are address projections, create aggregate instructions for it.
/// If builder is null, it's just a dry-run to check if it's possible.
static SILValue createValueFromAddr(SILValue addr, SILBuilder *builder,
SILLocation loc) {
SmallVector<SILValue, 4> elems;
enum Kind {
none, store, tuple
} kind = none;
for (Operand *use : addr->getUses()) {
SILInstruction *user = use->getUser();
if (user->isDebugInstruction())
continue;
auto *st = dyn_cast<StoreInst>(user);
if (st && kind == none && st->getDest() == addr) {
elems.push_back(st->getSrc());
kind = store;
// We cannot just return st->getSrc() here because we also have to check
// if the store destination is the only use of addr.
continue;
}
if (auto *telem = dyn_cast<TupleElementAddrInst>(user)) {
if (kind == none) {
elems.resize(addr->getType().castTo<TupleType>()->getNumElements());
kind = tuple;
}
if (kind == tuple) {
if (elems[telem->getFieldIndex()])
return SILValue();
elems[telem->getFieldIndex()] = createValueFromAddr(telem, builder, loc);
continue;
}
}
// TODO: handle StructElementAddrInst to create structs.
return SILValue();
}
switch (kind) {
case none:
return SILValue();
case store:
assert(elems.size() == 1);
return elems[0];
case tuple:
if (std::any_of(elems.begin(), elems.end(),
[](SILValue v){ return !(bool)v; }))
return SILValue();
if (builder) {
return builder->createTuple(loc, addr->getType().getObjectType(), elems);
}
// Just return anything not null for the dry-run.
return elems[0];
}
llvm_unreachable("invalid kind");
}
/// Simplify the following two frontend patterns:
///
/// %payload_addr = init_enum_data_addr %payload_allocation
/// store %payload to %payload_addr
/// inject_enum_addr %payload_allocation, $EnumType.case
///
/// inject_enum_addr %nopayload_allocation, $EnumType.case
///
/// for a concrete enum type $EnumType.case to:
///
/// %1 = enum $EnumType, $EnumType.case, %payload
/// store %1 to %payload_addr
///
/// %1 = enum $EnumType, $EnumType.case
/// store %1 to %nopayload_addr
///
/// We leave the cleaning up to mem2reg.
SILInstruction *
SILCombiner::visitInjectEnumAddrInst(InjectEnumAddrInst *IEAI) {
if (IEAI->getFunction()->hasOwnership())
return nullptr;
// Given an inject_enum_addr of a concrete type without payload, promote it to
// a store of an enum. Mem2reg/load forwarding will clean things up for us. We
// can't handle the payload case here due to the flow problems caused by the
// dependency in between the enum and its data.
// Disable this for empty typle type because empty tuple stack locations maybe
// uninitialized. And converting to value form loses tag information.
if (IEAI->getElement()->hasAssociatedValues()) {
SILType elemType = IEAI->getOperand()->getType().getEnumElementType(
IEAI->getElement(), IEAI->getFunction());
if (elemType.isEmpty(*IEAI->getFunction())) {
return nullptr;
}
}
assert(IEAI->getOperand()->getType().isAddress() && "Must be an address");
Builder.setCurrentDebugScope(IEAI->getDebugScope());
if (IEAI->getOperand()->getType().isAddressOnly(*IEAI->getFunction())) {
// Check for the following pattern inside the current basic block:
// inject_enum_addr %payload_allocation, $EnumType.case1
// ... no insns storing anything into %payload_allocation
// select_enum_addr %payload_allocation,
// case $EnumType.case1: %Result1,
// case case $EnumType.case2: %bResult2
// ...
//
// Replace the select_enum_addr by %Result1
auto *Term = IEAI->getParent()->getTerminator();
if (isa<CondBranchInst>(Term) || isa<SwitchValueInst>(Term)) {
auto BeforeTerm = std::prev(std::prev(IEAI->getParent()->end()));
auto *SEAI = dyn_cast<SelectEnumAddrInst>(BeforeTerm);
if (!SEAI)
return nullptr;
if (SEAI->getOperand() != IEAI->getOperand())
return nullptr;
SILBasicBlock::iterator II = IEAI->getIterator();
StoreInst *SI = nullptr;
for (;;) {
SILInstruction *CI = &*II;
if (CI == SEAI)
break;
++II;
SI = dyn_cast<StoreInst>(CI);
if (SI) {
if (SI->getDest() == IEAI->getOperand())
return nullptr;