-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSimplifyCFG.cpp
4013 lines (3467 loc) · 137 KB
/
SimplifyCFG.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
//===--- SimplifyCFG.cpp - Clean up the SIL CFG ---------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// Note: Unreachable blocks must always be eliminated before simplifying
/// useless phis. Otherwise self-loops will result in invalid SIL:
///
/// bb1(%phi):
/// apply %use(%phi)
/// %def = apply %getValue()
/// br bb1(%def)
///
/// When bb1 is unreachable, %phi will be removed as useless:
/// bb1:
/// apply %use(%def)
/// %def = apply %getValue()
/// br bb1(%def)
///
/// This is considered invalid SIL because SIL has a special SSA dominance rule
/// that does not allow a use above a def in the same block.
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-simplify-cfg"
#include "swift/SILOptimizer/Transforms/SimplifyCFG.h"
#include "swift/AST/Module.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TerminatorUtils.h"
#include "swift/SIL/Test.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/ProgramTerminationAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/CastOptimizer.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/SILInliner.h"
#include "swift/SILOptimizer/Utils/SILSSAUpdater.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
// This is temporarily used for testing until Swift 5.5 branches to reduce risk.
llvm::cl::opt<bool> EnableOSSASimplifyCFG(
"enable-ossa-simplify-cfg",
llvm::cl::desc(
"Enable non-trivial OSSA simplify-cfg and simple jump threading "
"(staging)."));
// This requires new OwnershipOptUtilities which aren't well tested yet.
llvm::cl::opt<bool> EnableOSSARewriteTerminator(
"enable-ossa-rewriteterminator",
llvm::cl::desc(
"Enable OSSA simplify-cfg with non-trivial terminator rewriting "
"(staging)."));
llvm::cl::opt<bool> IsInfiniteJumpThreadingBudget(
"sil-infinite-jump-threading-budget",
llvm::cl::desc(
"Use infinite budget for jump threading. Useful for testing purposes"));
STATISTIC(NumBlocksDeleted, "Number of unreachable blocks removed");
STATISTIC(NumBlocksMerged, "Number of blocks merged together");
STATISTIC(NumJumpThreads, "Number of jumps threaded");
STATISTIC(NumTermBlockSimplified, "Number of programterm block simplified");
STATISTIC(NumConstantFolded, "Number of terminators constant folded");
STATISTIC(NumDeadArguments, "Number of unused arguments removed");
STATISTIC(NumSROAArguments, "Number of aggregate argument levels split by "
"SROA");
//===----------------------------------------------------------------------===//
// CFG Simplification
//===----------------------------------------------------------------------===//
/// dominatorBasedSimplify iterates between dominator based simplification of
/// terminator branch condition values and CFG simplification. This is the
/// maximum number of iterations we run. The number is the maximum number of
/// iterations encountered when compiling the stdlib on April 2 2015.
///
static unsigned MaxIterationsOfDominatorBasedSimplify = 10;
static SILValue getTerminatorCondition(TermInst *Term) {
if (auto *CondBr = dyn_cast<CondBranchInst>(Term))
return stripExpectIntrinsic(CondBr->getCondition());
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term))
return SEI->getOperand();
return nullptr;
}
/// Is this basic block jump threadable.
static bool isThreadableBlock(SILBasicBlock *BB,
SmallPtrSetImpl<SILBasicBlock *> &LoopHeaders) {
auto TI = BB->getTerminator();
// We know how to handle cond_br and switch_enum.
if (!isa<CondBranchInst>(TI) &&
!isa<SwitchEnumInst>(TI))
return false;
if (LoopHeaders.count(BB))
return false;
unsigned Cost = 0;
for (auto &Inst : *BB) {
if (!Inst.isTriviallyDuplicatable())
return false;
// Don't jumpthread function calls.
if (FullApplySite::isa(&Inst))
return false;
// Only thread 'small blocks'.
if (instructionInlineCost(Inst) != InlineCost::Free)
if (++Cost == 4)
return false;
}
return true;
}
/// A description of an edge leading to a conditionally branching (or switching)
/// block and the successor block to thread to.
///
/// Src:
/// br Dest
/// \
/// \ Edge
/// v
/// Dest:
/// ...
/// switch/cond_br
/// / \
/// ... v
/// EnumCase/ThreadedSuccessorIdx
struct ThreadInfo {
SILBasicBlock *Src;
SILBasicBlock *Dest;
EnumElementDecl *EnumCase;
unsigned ThreadedSuccessorIdx;
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest,
unsigned ThreadedBlockSuccessorIdx)
: Src(Src), Dest(Dest), EnumCase(nullptr),
ThreadedSuccessorIdx(ThreadedBlockSuccessorIdx) {}
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest, EnumElementDecl *EnumCase)
: Src(Src), Dest(Dest), EnumCase(EnumCase), ThreadedSuccessorIdx(0) {}
ThreadInfo() = default;
};
// FIXME: It would be far more efficient to clone the jump-threaded region using
// a single invocation of the RegionCloner (see ArrayPropertyOpt) instead of a
// BasicBlockCloner. Cloning a single block at a time forces the cloner to
// create four extra blocks that immediately become dead after the conditional
// branch and its clone is converted to an unconditional branch.
bool SimplifyCFG::threadEdge(const ThreadInfo &ti) {
LLVM_DEBUG(llvm::dbgs() << "thread edge from bb" << ti.Src->getDebugID()
<< " to bb" << ti.Dest->getDebugID() << '\n');
auto *SrcTerm = cast<BranchInst>(ti.Src->getTerminator());
BasicBlockCloner Cloner(SrcTerm->getDestBB());
if (!Cloner.canCloneBlock())
return false;
Cloner.cloneBranchTarget(SrcTerm);
// We have copied the threaded block into the edge.
auto *clonedSrc = Cloner.getNewBB();
SmallVector<SILBasicBlock *, 4> clonedSuccessors(
clonedSrc->getSuccessorBlocks().begin(),
clonedSrc->getSuccessorBlocks().end());
SILBasicBlock *ThreadedSuccessorBlock = nullptr;
// Rewrite the cloned branch to eliminate the non-taken path.
if (auto *CondTerm = dyn_cast<CondBranchInst>(clonedSrc->getTerminator())) {
// We know the direction this conditional branch is going to take thread
// it.
assert(clonedSrc->getSuccessors().size() > ti.ThreadedSuccessorIdx
&& "Threaded terminator does not have enough successors");
ThreadedSuccessorBlock =
clonedSrc->getSuccessors()[ti.ThreadedSuccessorIdx].getBB();
auto Args = ti.ThreadedSuccessorIdx == 0 ? CondTerm->getTrueArgs()
: CondTerm->getFalseArgs();
SILBuilderWithScope(CondTerm).createBranch(CondTerm->getLoc(),
ThreadedSuccessorBlock, Args);
CondTerm->eraseFromParent();
} else {
// Get the enum element and the destination block of the block we jump
// thread.
auto *SEI = cast<SwitchEnumInst>(clonedSrc->getTerminator());
ThreadedSuccessorBlock = SEI->getCaseDestination(ti.EnumCase);
// Instantiate the payload if necessary.
SILBuilderWithScope Builder(SEI);
if (!ThreadedSuccessorBlock->args_empty()) {
auto EnumVal = SEI->getOperand();
auto EnumTy = EnumVal->getType();
auto Loc = SEI->getLoc();
auto Ty = EnumTy.getEnumElementType(ti.EnumCase, SEI->getModule(),
Builder.getTypeExpansionContext());
SILValue UED(
Builder.createUncheckedEnumData(Loc, EnumVal, ti.EnumCase, Ty));
assert(UED->getType()
== (*ThreadedSuccessorBlock->args_begin())->getType()
&& "Argument types must match");
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock, {UED});
} else {
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock,
ArrayRef<SILValue>());
}
SEI->eraseFromParent();
}
// If the jump-threading target "Dest" had multiple predecessors, then the
// cloner will have created unconditional branch predecessors, which can
// now be removed or folded after converting the source block "Src" to an
// unconditional branch.
for (auto *succBB : clonedSuccessors) {
removeIfDead(succBB);
}
if (auto *branchInst =
dyn_cast<BranchInst>(ThreadedSuccessorBlock->getTerminator())) {
simplifyBranchBlock(branchInst);
}
Cloner.updateSSAAfterCloning();
return true;
}
/// Give a cond_br or switch_enum instruction and one successor block returns
/// true if we can infer the value of the condition/enum along the edge to these
/// successor blocks.
static bool isKnownEdgeValue(TermInst *Term, SILBasicBlock *SuccBB,
EnumElementDecl *&EnumCase) {
assert((isa<CondBranchInst>(Term) || isa<SwitchEnumInst>(Term)) &&
"Expect a cond_br or switch_enum");
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto Case = SEI->getUniqueCaseForDestination(SuccBB)) {
EnumCase = Case.get();
return SuccBB->getSinglePredecessorBlock() != nullptr;
}
return false;
}
return SuccBB->getSinglePredecessorBlock() != nullptr;
}
/// Create an enum element by extracting the operand of a switch_enum.
static SILValue createEnumElement(SILBuilder &Builder,
SwitchEnumInst *SEI,
EnumElementDecl *EnumElement) {
auto EnumVal = SEI->getOperand();
// Do we have a payload.
auto EnumTy = EnumVal->getType();
if (EnumElement->hasAssociatedValues()) {
auto Ty = EnumTy.getEnumElementType(EnumElement, SEI->getModule(),
Builder.getTypeExpansionContext());
SILValue UED(Builder.createUncheckedEnumData(SEI->getLoc(), EnumVal,
EnumElement, Ty));
return Builder.createEnum(SEI->getLoc(), UED, EnumElement, EnumTy);
}
return Builder.createEnum(SEI->getLoc(), SILValue(), EnumElement, EnumTy);
}
/// Create a value for the condition of the terminator that flows along the edge
/// with 'EdgeIdx'. Insert it before the 'UserInst'.
static SILValue createValueForEdge(SILInstruction *UserInst,
SILInstruction *DominatingTerminator,
unsigned EdgeIdx) {
SILBuilderWithScope Builder(UserInst);
if (auto *CBI = dyn_cast<CondBranchInst>(DominatingTerminator))
return Builder.createIntegerLiteral(
CBI->getLoc(), CBI->getCondition()->getType(), EdgeIdx == 0 ? -1 : 0);
auto *SEI = cast<SwitchEnumInst>(DominatingTerminator);
auto *DstBlock = SEI->getSuccessors()[EdgeIdx].getBB();
auto Case = SEI->getUniqueCaseForDestination(DstBlock);
assert(Case && "No unique case found for destination block");
return createEnumElement(Builder, SEI, Case.get());
}
/// Perform dominator based value simplifications and jump threading on all users
/// of the operand of 'DominatingBB's terminator.
static bool tryDominatorBasedSimplifications(
SILBasicBlock *DominatingBB, DominanceInfo *DT,
SmallPtrSetImpl<SILBasicBlock *> &LoopHeaders,
SmallVectorImpl<ThreadInfo> &JumpThreadableEdges,
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>>
&ThreadedEdgeSet,
bool TryJumpThreading,
BasicBlockFlag &isThreadable, BasicBlockFlag &threadableComputed) {
auto *DominatingTerminator = DominatingBB->getTerminator();
// We handle value propagation from cond_br and switch_enum terminators.
bool IsEnumValue = isa<SwitchEnumInst>(DominatingTerminator);
if (!isa<CondBranchInst>(DominatingTerminator) && !IsEnumValue)
return false;
auto DominatingCondition = getTerminatorCondition(DominatingTerminator);
if (!DominatingCondition)
return false;
if (isa<SILUndef>(DominatingCondition))
return false;
bool Changed = false;
// We will look at all the outgoing edges from the conditional branch to see
// whether any other uses of the condition or uses of the condition along an
// edge are dominated by said outgoing edges. The outgoing edge carries the
// value on which we switch/cond_branch.
auto Succs = DominatingBB->getSuccessors();
for (unsigned Idx = 0; Idx < Succs.size(); ++Idx) {
auto *DominatingSuccBB = Succs[Idx].getBB();
EnumElementDecl *EnumCase = nullptr;
if (!isKnownEdgeValue(DominatingTerminator, DominatingSuccBB, EnumCase))
continue;
// Look for other uses of DominatingCondition that are either:
// * dominated by the DominatingSuccBB
//
// cond_br %dominating_cond / switch_enum
// /
// /
// /
// DominatingSuccBB:
// ...
// use %dominating_cond
//
// * are a conditional branch that has an incoming edge that is
// dominated by DominatingSuccBB.
//
// cond_br %dominating_cond
// /
// /
// /
//
// DominatingSuccBB:
// ...
// br DestBB
//
// \
// \ E -> %dominating_cond = true
// \
// v
// DestBB
// cond_br %dominating_cond
SmallVector<SILInstruction *, 16> UsersToReplace;
for (auto *Op : ignore_expect_uses(DominatingCondition)) {
auto *CondUserInst = Op->getUser();
// Ignore the DominatingTerminator itself.
if (CondUserInst->getParent() == DominatingBB)
continue;
// For enum values we are only interested in switch_enum and select_enum
// users.
if (IsEnumValue && !isa<SwitchEnumInst>(CondUserInst) &&
!isa<SelectEnumInst>(CondUserInst))
continue;
// If the use is dominated we can replace this use by the value
// flowing to DominatingSuccBB.
if (DT->dominates(DominatingSuccBB, CondUserInst->getParent())) {
UsersToReplace.push_back(CondUserInst);
continue;
}
// Jump threading is expensive so we don't always do it.
if (!TryJumpThreading)
continue;
auto *DestBB = CondUserInst->getParent();
// The user must be the terminator we are trying to jump thread.
if (CondUserInst != DestBB->getTerminator())
continue;
// Check whether we have seen this destination block already.
if (!threadableComputed.testAndSet(DestBB))
isThreadable.set(DestBB, isThreadableBlock(DestBB, LoopHeaders));
// If the use is a conditional branch/switch then look for an incoming
// edge that is dominated by DominatingSuccBB.
if (isThreadable.get(DestBB)) {
auto Preds = DestBB->getPredecessorBlocks();
for (SILBasicBlock *PredBB : Preds) {
if (!isa<BranchInst>(PredBB->getTerminator()))
continue;
if (!DT->dominates(DominatingSuccBB, PredBB))
continue;
// Don't jumpthread the same edge twice.
if (!ThreadedEdgeSet.insert(std::make_pair(PredBB, DestBB)).second)
continue;
if (isa<CondBranchInst>(DestBB->getTerminator()))
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, Idx));
else
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, EnumCase));
break;
}
}
}
// Replace dominated user instructions.
for (auto *UserInst : UsersToReplace) {
SILValue EdgeValue;
for (auto &Op : UserInst->getAllOperands()) {
if (stripExpectIntrinsic(Op.get()) == DominatingCondition) {
if (!EdgeValue)
EdgeValue = createValueForEdge(UserInst, DominatingTerminator, Idx);
LLVM_DEBUG(llvm::dbgs() << "replace dominated operand\n in "
<< *UserInst << " with " << EdgeValue);
Op.set(EdgeValue);
Changed = true;
}
}
}
}
return Changed;
}
/// Propagate values of branched upon values along the outgoing edges down the
/// dominator tree.
bool SimplifyCFG::dominatorBasedSimplifications(SILFunction &Fn,
DominanceInfo *DT) {
bool Changed = false;
// Collect jump threadable edges and propagate outgoing edge values of
// conditional branches/switches.
SmallVector<ThreadInfo, 8> JumpThreadableEdges;
BasicBlockFlag isThreadable(&Fn);
BasicBlockFlag threadableComputed(&Fn);
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>> ThreadedEdgeSet;
for (auto &BB : Fn) {
if (DT->getNode(&BB)) {
if (!transform.continueWithNextSubpassRun(BB.getTerminator()))
return Changed;
// Only handle reachable blocks.
Changed |= tryDominatorBasedSimplifications(
&BB, DT, LoopHeaders, JumpThreadableEdges, ThreadedEdgeSet,
EnableJumpThread, isThreadable, threadableComputed);
}
}
// Nothing to jump thread?
if (JumpThreadableEdges.empty())
return Changed;
for (auto &ThreadInfo : JumpThreadableEdges) {
if (!transform.continueWithNextSubpassRun())
return Changed;
if (threadEdge(ThreadInfo)) {
Changed = true;
}
}
return Changed;
}
/// Simplify terminators that could have been simplified by threading.
bool SimplifyCFG::simplifyThreadedTerminators() {
bool HaveChangedCFG = false;
for (auto &BB : Fn) {
auto *Term = BB.getTerminator();
if (!transform.continueWithNextSubpassRun(Term))
return HaveChangedCFG;
// Simplify a switch_enum.
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto *EI = dyn_cast<EnumInst>(SEI->getOperand())) {
LLVM_DEBUG(llvm::dbgs() << "simplify threaded " << *SEI);
auto *LiveBlock = SEI->getCaseDestination(EI->getElement());
if (EI->hasOperand() && !LiveBlock->args_empty())
SILBuilderWithScope(SEI)
.createBranch(SEI->getLoc(), LiveBlock, EI->getOperand());
else
SILBuilderWithScope(SEI).createBranch(SEI->getLoc(), LiveBlock);
SEI->eraseFromParent();
if (EI->use_empty())
EI->eraseFromParent();
HaveChangedCFG = true;
}
continue;
} else if (auto *CondBr = dyn_cast<CondBranchInst>(Term)) {
// If the condition is an integer literal, we can constant fold the
// branch.
if (auto *IL = dyn_cast<IntegerLiteralInst>(CondBr->getCondition())) {
LLVM_DEBUG(llvm::dbgs() << "simplify threaded " << *CondBr);
SILBasicBlock *TrueSide = CondBr->getTrueBB();
SILBasicBlock *FalseSide = CondBr->getFalseBB();
auto TrueArgs = CondBr->getTrueArgs();
auto FalseArgs = CondBr->getFalseArgs();
bool isFalse = !IL->getValue();
auto LiveArgs = isFalse ? FalseArgs : TrueArgs;
auto *LiveBlock = isFalse ? FalseSide : TrueSide;
SILBuilderWithScope(CondBr)
.createBranch(CondBr->getLoc(), LiveBlock, LiveArgs);
CondBr->eraseFromParent();
if (IL->use_empty())
IL->eraseFromParent();
HaveChangedCFG = true;
}
}
}
return HaveChangedCFG;
}
// Simplifications that walk the dominator tree to prove redundancy in
// conditional branching.
bool SimplifyCFG::dominatorBasedSimplify(DominanceAnalysis *DA) {
// Get the dominator tree.
DT = DA->get(&Fn);
if (!EnableOSSASimplifyCFG && Fn.hasOwnership())
return false;
// Split all critical edges such that we can move code onto edges. This is
// also required for SSA construction in dominatorBasedSimplifications' jump
// threading. It only splits new critical edges it creates by jump threading.
bool Changed = false;
if (!Fn.hasOwnership() && EnableJumpThread) {
Changed = splitAllCriticalEdges(Fn, DT, nullptr);
}
unsigned MaxIter = MaxIterationsOfDominatorBasedSimplify;
SmallVector<SILBasicBlock *, 16> BlocksForWorklist;
bool HasChangedInCurrentIter;
do {
HasChangedInCurrentIter = false;
if (!transform.continueWithNextSubpassRun())
return Changed;
// Do dominator based simplification of terminator condition. This does not
// and MUST NOT change the CFG without updating the dominator tree to
// reflect such change.
if (tryCheckedCastBrJumpThreading(&Fn, DT, deBlocks, BlocksForWorklist,
EnableOSSARewriteTerminator)) {
for (auto BB: BlocksForWorklist)
addToWorklist(BB);
HasChangedInCurrentIter = true;
DT->recalculate(Fn);
}
BlocksForWorklist.clear();
if (ShouldVerify)
DT->verify();
// Simplify the block argument list. This is extremely subtle: simplifyArgs
// will not change the CFG iff the DT is null. Really we should move that
// one optimization out of simplifyArgs ... I am squinting at you
// simplifySwitchEnumToSelectEnum.
// simplifyArgs does use the dominator tree, though.
for (auto &BB : Fn) {
if (!transform.continueWithNextSubpassRun(BB.getTerminator()))
return Changed;
HasChangedInCurrentIter |= simplifyArgs(&BB);
}
if (ShouldVerify)
DT->verify();
// Jump thread.
if (dominatorBasedSimplifications(Fn, DT)) {
if (!transform.continueWithNextSubpassRun())
return true;
DominanceInfo *InvalidDT = DT;
DT = nullptr;
HasChangedInCurrentIter = true;
// Simplify terminators.
simplifyThreadedTerminators();
DT = InvalidDT;
DT->recalculate(Fn);
}
Changed |= HasChangedInCurrentIter;
} while (HasChangedInCurrentIter && --MaxIter);
// Do the simplification that requires both the dom and postdom tree.
for (auto &BB : Fn)
Changed |= simplifyArgs(&BB);
if (ShouldVerify)
DT->verify();
// The functions we used to simplify the CFG put things in the worklist. Clear
// it here.
clearWorklist();
return Changed;
}
// If BB is trivially unreachable, remove it from the worklist, add its
// successors to the worklist, and then remove the block.
bool SimplifyCFG::removeIfDead(SILBasicBlock *BB) {
if (!BB->pred_empty() || BB == &*Fn.begin())
return false;
removeFromWorklist(BB);
// Add successor blocks to the worklist since their predecessor list is about
// to change.
for (auto &S : BB->getSuccessors())
addToWorklist(S);
LLVM_DEBUG(llvm::dbgs() << "remove dead bb" << BB->getDebugID() << '\n');
removeDeadBlock(BB);
++NumBlocksDeleted;
return true;
}
/// This is called when a predecessor of a block is dropped, to simplify the
/// block and add it to the worklist.
bool SimplifyCFG::simplifyAfterDroppingPredecessor(SILBasicBlock *BB) {
// TODO: If BB has only one predecessor and has bb args, fold them away, then
// use instsimplify on all the users of those values - even ones outside that
// block.
// Make sure that DestBB is in the worklist, as well as its remaining
// predecessors, since they may not be able to be simplified.
addToWorklist(BB);
for (auto *P : BB->getPredecessorBlocks())
addToWorklist(P);
return false;
}
/// This is called after \p BB has been cloned during jump-threading
/// (tail-duplication) and the new critical edge on its successor has been
/// split. This is necessary to continue jump-threading through the split
/// critical edge (since we only jump-thread one block at a time).
bool SimplifyCFG::addToWorklistAfterSplittingEdges(SILBasicBlock *BB) {
addToWorklist(BB);
for (auto *succBB : BB->getSuccessorBlocks()) {
addToWorklist(succBB);
}
return false;
}
static NullablePtr<EnumElementDecl>
getEnumCaseRecursive(SILValue Val, SILBasicBlock *UsedInBB, int RecursionDepth,
llvm::SmallPtrSetImpl<SILArgument *> &HandledArgs) {
// Limit the number of recursions. This is an easy way to cope with cycles
// in the SSA graph.
if (RecursionDepth > 3)
return nullptr;
// Handle the obvious case.
if (auto *EI = dyn_cast<EnumInst>(Val))
return EI->getElement();
// Check if the value is dominated by a switch_enum, e.g.
// switch_enum %val, case A: bb1, case B: bb2
// bb1:
// use %val // We know that %val has case A
SILBasicBlock *Pred = UsedInBB->getSinglePredecessorBlock();
int Limit = 3;
// A very simple dominator check: just walk up the single predecessor chain.
// The limit is just there to not run into an infinite loop in case of an
// unreachable CFG cycle.
while (Pred && --Limit > 0) {
if (auto *PredSEI = dyn_cast<SwitchEnumInst>(Pred->getTerminator())) {
if (PredSEI->getOperand() == Val)
return PredSEI->getUniqueCaseForDestination(UsedInBB);
}
UsedInBB = Pred;
Pred = UsedInBB->getSinglePredecessorBlock();
}
// In case of a phi, recursively check the enum cases of all
// incoming predecessors.
if (auto *Arg = dyn_cast<SILArgument>(Val)) {
HandledArgs.insert(Arg);
llvm::SmallVector<std::pair<SILBasicBlock *, SILValue>, 8> IncomingVals;
if (!Arg->getIncomingPhiValues(IncomingVals))
return nullptr;
EnumElementDecl *CommonCase = nullptr;
for (std::pair<SILBasicBlock *, SILValue> Incoming : IncomingVals) {
SILBasicBlock *IncomingBlock = Incoming.first;
SILValue IncomingVal = Incoming.second;
auto *IncomingArg = dyn_cast<SILArgument>(IncomingVal);
if (IncomingArg && HandledArgs.count(IncomingArg) != 0)
continue;
NullablePtr<EnumElementDecl> IncomingCase =
getEnumCaseRecursive(Incoming.second, IncomingBlock, RecursionDepth + 1,
HandledArgs);
if (!IncomingCase)
return nullptr;
if (IncomingCase.get() != CommonCase) {
if (CommonCase)
return nullptr;
CommonCase = IncomingCase.get();
}
}
return CommonCase;
}
return nullptr;
}
/// Tries to figure out the enum case of an enum value \p Val which is used in
/// block \p UsedInBB.
static NullablePtr<EnumElementDecl> getEnumCase(SILValue Val,
SILBasicBlock *UsedInBB) {
llvm::SmallPtrSet<SILArgument *, 8> HandledArgs;
return getEnumCaseRecursive(Val, UsedInBB, /*RecursionDepth*/ 0, HandledArgs);
}
static int getThreadingCost(SILInstruction *I) {
if (!I->isTriviallyDuplicatable())
return 1000;
// Don't jumpthread function calls.
if (isa<ApplyInst>(I))
return 1000;
// This is a really trivial cost model, which is only intended as a starting
// point.
if (instructionInlineCost(*I) != InlineCost::Free)
return 1;
return 0;
}
static int maxBranchRecursionDepth = 6;
/// couldSimplifyUsers - Check to see if any simplifications are possible if
/// "Val" is substituted for BBArg. If so, return true, if nothing obvious
/// is possible, return false.
static bool couldSimplifyEnumUsers(SILArgument *BBArg, int Budget,
int recursionDepth = 0) {
SILBasicBlock *BB = BBArg->getParent();
int BudgetForBranch = 100;
for (Operand *UI : BBArg->getUses()) {
auto *User = UI->getUser();
if (User->getParent() != BB)
continue;
// We only know we can simplify if the switch_enum user is in the block we
// are trying to jump thread.
// The value must not be define in the same basic block as the switch enum
// user. If this is the case we have a single block switch_enum loop.
if (isa<SwitchEnumInst>(User) || isa<SelectEnumInst>(User))
return true;
// Also allow enum of enum, which usually can be combined to a single
// instruction. This helps to simplify the creation of an enum from an
// integer raw value.
if (isa<EnumInst>(User))
return true;
if (auto *SWI = dyn_cast<SwitchValueInst>(User)) {
if (SWI->getOperand() == BBArg)
return true;
}
if (auto *BI = dyn_cast<BranchInst>(User)) {
if (recursionDepth >= maxBranchRecursionDepth) {
return false;
}
if (BudgetForBranch > Budget) {
BudgetForBranch = Budget;
for (SILInstruction &I : *BB) {
BudgetForBranch -= getThreadingCost(&I);
if (BudgetForBranch < 0)
break;
}
}
if (BudgetForBranch > 0) {
SILBasicBlock *DestBB = BI->getDestBB();
unsigned OpIdx = UI->getOperandNumber();
if (couldSimplifyEnumUsers(DestBB->getArgument(OpIdx), BudgetForBranch,
recursionDepth + 1))
return true;
}
}
}
return false;
}
void SimplifyCFG::findLoopHeaders() {
/// Find back edges in the CFG. This performs a dfs search and identifies
/// back edges as edges going to an ancestor in the dfs search. If a basic
/// block is the target of such a back edge we will identify it as a header.
LoopHeaders.clear();
BasicBlockSet Visited(&Fn);
BasicBlockSet InDFSStack(&Fn);
SmallVector<std::pair<SILBasicBlock *, SILBasicBlock::succ_iterator>, 16>
DFSStack;
auto EntryBB = &Fn.front();
DFSStack.push_back(std::make_pair(EntryBB, EntryBB->succ_begin()));
Visited.insert(EntryBB);
InDFSStack.insert(EntryBB);
while (!DFSStack.empty()) {
auto &D = DFSStack.back();
// No successors.
if (D.second == D.first->succ_end()) {
// Retreat the dfs search.
DFSStack.pop_back();
InDFSStack.erase(D.first);
} else {
// Visit the next successor.
SILBasicBlock *NextSucc = *(D.second);
++D.second;
if (Visited.insert(NextSucc)) {
InDFSStack.insert(NextSucc);
DFSStack.push_back(std::make_pair(NextSucc, NextSucc->succ_begin()));
} else if (InDFSStack.contains(NextSucc)) {
// We have already visited this node and it is in our dfs search. This
// is a back-edge.
LoopHeaders.insert(NextSucc);
}
}
}
}
static bool couldRemoveRelease(SILBasicBlock *SrcBB, SILValue SrcV,
SILBasicBlock *DestBB, SILValue DestV) {
bool IsRetainOfSrc = false;
for (auto *U: SrcV->getUses())
if (U->getUser()->getParent() == SrcBB &&
(isa<StrongRetainInst>(U->getUser()) ||
isa<RetainValueInst>(U->getUser()))) {
IsRetainOfSrc = true;
break;
}
if (!IsRetainOfSrc)
return false;
bool IsReleaseOfDest = false;
for (auto *U: DestV->getUses())
if (U->getUser()->getParent() == DestBB &&
(isa<StrongReleaseInst>(U->getUser()) ||
isa<ReleaseValueInst>(U->getUser()))) {
IsReleaseOfDest = true;
break;
}
return IsReleaseOfDest;
}
/// Returns true if any instruction in \p block may write memory.
static bool blockMayWriteMemory(SILBasicBlock *block) {
for (auto instAndIdx : llvm::enumerate(*block)) {
if (instAndIdx.value().mayWriteToMemory())
return true;
// Only look at the first 20 instructions to avoid compile time problems for
// corner cases of very large blocks without memory writes.
// 20 instructions is more than enough.
if (instAndIdx.index() > 50)
return true;
}
return false;
}
// Returns true if \p block contains an injected an enum case into \p enumAddr
// which is valid at the end of the block.
static bool hasInjectedEnumAtEndOfBlock(SILBasicBlock *block, SILValue enumAddr) {
for (auto instAndIdx : llvm::enumerate(llvm::reverse(*block))) {
SILInstruction &inst = instAndIdx.value();
if (auto *injectInst = dyn_cast<InjectEnumAddrInst>(&inst)) {
return injectInst->getOperand() == enumAddr;
}
if (inst.mayWriteToMemory())
return false;
// Only look at the first 20 instructions to avoid compile time problems for
// corner cases of very large blocks without memory writes.
// 20 instructions is more than enough.
if (instAndIdx.index() > 50)
return false;
}
return false;
}
/// tryJumpThreading - Check to see if it looks profitable to duplicate the
/// destination of an unconditional jump into the bottom of this block.
bool SimplifyCFG::tryJumpThreading(BranchInst *BI) {
if (!EnableOSSASimplifyCFG && Fn.hasOwnership())
return false;
auto *DestBB = BI->getDestBB();
auto *SrcBB = BI->getParent();
TermInst *destTerminator = DestBB->getTerminator();
if (!EnableOSSARewriteTerminator && Fn.hasOwnership()) {
if (llvm::any_of(DestBB->getArguments(), [this](SILValue op) {
return !op->getType().isTrivial(Fn);
})) {
return false;
}
}
// If the destination block ends with a return, we don't want to duplicate it.
// We want to maintain the canonical form of a single return where possible.
if (destTerminator->isFunctionExiting())
return false;
// There is no benefit duplicating such a destination.
if (DestBB->getSinglePredecessorBlock() != nullptr) {
return false;
}
// Jump threading only makes sense if there is an argument on the branch
// (which is reacted on in the DestBB), or if this goes through a memory
// location (switch_enum_addr is the only address-instruction which we
// currently handle).
if (BI->getArgs().empty() && !isa<SwitchEnumAddrInst>(destTerminator))
return false;
// We don't have a great cost model at the SIL level, so we don't want to
// blissly duplicate tons of code with a goal of improved performance (we'll
// leave that to LLVM). However, doing limited code duplication can lead to
// major second order simplifications. Here we only do it if there are
// "constant" arguments to the branch or if we know how to fold something
// given the duplication.
int ThreadingBudget = IsInfiniteJumpThreadingBudget ? INT_MAX : 0;
for (unsigned i : indices(BI->getArgs())) {
SILValue Arg = BI->getArg(i);
// TODO: Verify if we need to jump thread to remove releases in OSSA.
// If the value being substituted on is release there is a chance we could
// remove the release after jump threading.
if (!Arg->getType().isTrivial(*SrcBB->getParent()) &&
couldRemoveRelease(SrcBB, Arg, DestBB,
DestBB->getArgument(i))) {
ThreadingBudget = 8;
break;
}
// If the value being substituted is an enum, check to see if there are any
// switches on it.
if (!getEnumCase(Arg, BI->getParent()) &&
!isa<IntegerLiteralInst>(Arg))
continue;
if (couldSimplifyEnumUsers(DestBB->getArgument(i), 8)) {
ThreadingBudget = 8;
break;
}
}
if (ThreadingBudget == 0) {
if (isa<CondBranchInst>(destTerminator)) {
for (auto V : BI->getArgs()) {
if (isa<IntegerLiteralInst>(V) || isa<FloatLiteralInst>(V)) {
ThreadingBudget = 4;
break;
}
}
} else if (auto *SEA = dyn_cast<SwitchEnumAddrInst>(destTerminator)) {
// If the branch-block injects a certain enum case and the destination
// switches on that enum, it's worth jump threading. E.g.
//
// inject_enum_addr %enum : $*Optional<T>, #Optional.some
// ... // no memory writes here
// br DestBB
// DestBB:
// ... // no memory writes here
// switch_enum_addr %enum : $*Optional<T>, case #Optional.some ...
//
SILValue enumAddr = SEA->getOperand();
if (!blockMayWriteMemory(DestBB) &&
hasInjectedEnumAtEndOfBlock(SrcBB, enumAddr)) {
ThreadingBudget = 4;
}
}
}
ThreadingBudget -= JumpThreadingCost[SrcBB];