-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathPerformanceInliner.cpp
1408 lines (1208 loc) · 53.1 KB
/
PerformanceInliner.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
//===--- PerformanceInliner.cpp - Basic cost based performance inlining ---===//
//
// 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-inliner"
#include "swift/AST/Module.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OptimizationRemark.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.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/Devirtualize.h"
#include "swift/SILOptimizer/Utils/Generics.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/PerformanceInlinerUtils.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/Utils/StackNesting.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumFunctionsInlined, "Number of functions inlined");
llvm::cl::opt<bool> PrintShortestPathInfo(
"print-shortest-path-info", llvm::cl::init(false),
llvm::cl::desc("Print shortest-path information for inlining"));
llvm::cl::opt<bool> EnableSILInliningOfGenerics(
"sil-inline-generics", llvm::cl::init(false),
llvm::cl::desc("Enable inlining of generics"));
llvm::cl::opt<bool>
EnableSILAggressiveInlining("sil-aggressive-inline", llvm::cl::init(false),
llvm::cl::desc("Enable aggressive inlining"));
llvm::cl::opt<bool> EnableVerifyAfterInlining(
"sil-inline-verify-after-inline", llvm::cl::init(false),
llvm::cl::desc("Run sil verification after inlining all found callee apply "
"sites into a caller."));
llvm::cl::opt<bool> SILPrintInliningCallee(
"sil-print-inlining-callee", llvm::cl::init(false),
llvm::cl::desc("Print functions that are inlined into other functions."));
llvm::cl::opt<bool> SILPrintInliningCallerBefore(
"sil-print-inlining-caller-before", llvm::cl::init(false),
llvm::cl::desc(
"Print functions into which another function is about to be inlined."));
llvm::cl::opt<bool> SILPrintInliningCallerAfter(
"sil-print-inlining-caller-after", llvm::cl::init(false),
llvm::cl::desc(
"Print functions into which another function has been inlined."));
llvm::cl::opt<bool> EnableVerifyAfterEachInlining(
"sil-inline-verify-after-each-inline", llvm::cl::init(false),
llvm::cl::desc(
"Run sil verification after inlining each found callee apply "
"site into a caller."));
//===----------------------------------------------------------------------===//
// Printing Helpers
//===----------------------------------------------------------------------===//
extern void printInliningDetailsCallee(StringRef passName, SILFunction *caller,
SILFunction *callee);
extern void printInliningDetailsCallerBefore(StringRef passName,
SILFunction *caller,
SILFunction *callee);
extern void printInliningDetailsCallerAfter(StringRef passName,
SILFunction *caller,
SILFunction *callee);
//===----------------------------------------------------------------------===//
// Performance Inliner
//===----------------------------------------------------------------------===//
namespace {
using Weight = ShortestPathAnalysis::Weight;
class SILPerformanceInliner {
StringRef PassName;
SILOptFunctionBuilder &FuncBuilder;
/// Specifies which functions not to inline, based on @_semantics and
/// global_init attributes.
InlineSelection WhatToInline;
SILPassManager *pm;
DominanceAnalysis *DA;
SILLoopAnalysis *LA;
BasicCalleeAnalysis *BCA;
// For keys of SILFunction and SILLoop.
llvm::DenseMap<SILFunction *, ShortestPathAnalysis *> SPAs;
llvm::SpecificBumpPtrAllocator<ShortestPathAnalysis> SPAAllocator;
ColdBlockInfo CBI;
OptRemark::Emitter &ORE;
/// The following constants define the cost model for inlining. Some constants
/// are also defined in ShortestPathAnalysis.
enum {
/// The base value for every call: it represents the benefit of removing the
/// call overhead itself.
RemovedCallBenefit = 20,
/// The benefit of inlining a `begin_apply`.
RemovedCoroutineCallBenefit = 300,
/// The benefit if the operand of an apply gets constant, e.g. if a closure
/// is passed to an apply instruction in the callee.
RemovedClosureBenefit = RemovedCallBenefit + 50,
/// The benefit if a load can (probably) eliminated because it loads from
/// a stack location in the caller.
RemovedLoadBenefit = RemovedCallBenefit + 5,
/// The benefit if a store can (probably) eliminated because it stores to
/// a stack location in the caller.
RemovedStoreBenefit = RemovedCallBenefit + 10,
/// The benefit if the condition of a terminator instruction gets constant
/// due to inlining.
RemovedTerminatorBenefit = RemovedCallBenefit + 10,
/// The benefit if a retain/release can (probably) be eliminated after
/// inlining.
RefCountBenefit = RemovedCallBenefit + 20,
/// The benefit of a onFastPath builtin.
FastPathBuiltinBenefit = RemovedCallBenefit + 40,
/// The benefit of being able to devirtualize a call.
DevirtualizedCallBenefit = RemovedCallBenefit + 300,
/// The benefit of being able to produce a generic
/// specialization for a call.
GenericSpecializationBenefit = RemovedCallBenefit + 300,
/// The benefit of inlining an exclusivity-containing callee.
/// The exclusivity needs to be: dynamic,
/// has no nested conflict and addresses known storage
ExclusivityBenefit = RemovedCallBenefit + 10,
/// The benefit of inlining class methods with -Osize.
/// We only inline very small class methods with -Osize.
OSizeClassMethodBenefit = 5,
/// Approximately up to this cost level a function can be inlined without
/// increasing the code size.
TrivialFunctionThreshold = 18,
/// Configuration for the "soft" caller block limit. When changing, make
/// sure you update BlockLimitMaxIntNumerator.
BlockLimitDenominator = 3000,
/// Computations with BlockLimitDenominator will overflow with numerators
/// >= this value. This equals cbrt(INT_MAX) * cbrt(BlockLimitDenominator);
/// we hardcode its value because std::cbrt() is not constexpr.
BlockLimitMaxIntNumerator = 18608,
/// No inlining is done if the caller has more than this number of blocks.
OverallCallerBlockLimit = 400,
/// The assumed execution length of a function call.
DefaultApplyLength = 10
};
OptimizationMode OptMode;
#ifndef NDEBUG
SILFunction *LastPrintedCaller = nullptr;
void dumpCaller(SILFunction *Caller) {
if (Caller != LastPrintedCaller) {
llvm::dbgs() << "\nInline into caller: " << Caller->getName() << '\n';
LastPrintedCaller = Caller;
}
}
#endif
ShortestPathAnalysis *getSPA(SILFunction *F, SILLoopInfo *LI) {
ShortestPathAnalysis *&SPA = SPAs[F];
if (!SPA) {
SPA = new (SPAAllocator.Allocate()) ShortestPathAnalysis(F, LI);
}
return SPA;
}
bool profileBasedDecision(
const FullApplySite &AI, int Benefit, SILFunction *Callee, int CalleeCost,
int &NumCallerBlocks,
const llvm::DenseMapIterator<
swift::SILBasicBlock *, uint64_t,
llvm::DenseMapInfo<swift::SILBasicBlock *>,
llvm::detail::DenseMapPair<swift::SILBasicBlock *, uint64_t>, true>
&bbIt);
bool isAutoDiffLinearMapWithControlFlow(FullApplySite AI);
bool isTupleWithAllocsOrPartialApplies(SILValue retVal);
bool isProfitableToInline(
FullApplySite AI, Weight CallerWeight, ConstantTracker &callerTracker,
int &NumCallerBlocks,
const llvm::DenseMap<SILBasicBlock *, uint64_t> &BBToWeightMap);
bool decideInWarmBlock(
FullApplySite AI, Weight CallerWeight, ConstantTracker &callerTracker,
int &NumCallerBlocks,
const llvm::DenseMap<SILBasicBlock *, uint64_t> &BBToWeightMap);
bool decideInColdBlock(FullApplySite AI, SILFunction *Callee, int numCallerBlocks);
void visitColdBlocks(SmallVectorImpl<FullApplySite> &AppliesToInline,
SILBasicBlock *root, DominanceInfo *DT, int numCallerBlocks);
void collectAppliesToInline(SILFunction *Caller,
SmallVectorImpl<FullApplySite> &Applies);
public:
SILPerformanceInliner(StringRef PassName, SILOptFunctionBuilder &FuncBuilder,
InlineSelection WhatToInline,
SILPassManager *pm, DominanceAnalysis *DA,
PostDominanceAnalysis *PDA,
SILLoopAnalysis *LA, BasicCalleeAnalysis *BCA,
OptimizationMode OptMode, OptRemark::Emitter &ORE)
: PassName(PassName), FuncBuilder(FuncBuilder),
WhatToInline(WhatToInline), pm(pm), DA(DA), LA(LA), BCA(BCA), CBI(DA, PDA), ORE(ORE),
OptMode(OptMode) {}
bool inlineCallsIntoFunction(SILFunction *F);
};
} // end anonymous namespace
// Returns true if it is possible to perform a generic
// specialization for a given call.
static bool canSpecializeGeneric(ApplySite AI, SILFunction *F,
SubstitutionMap Subs) {
return ReabstractionInfo::canBeSpecialized(AI, F, Subs);
}
bool SILPerformanceInliner::profileBasedDecision(
const FullApplySite &AI, int Benefit, SILFunction *Callee, int CalleeCost,
int &NumCallerBlocks,
const llvm::DenseMapIterator<
swift::SILBasicBlock *, uint64_t,
llvm::DenseMapInfo<swift::SILBasicBlock *>,
llvm::detail::DenseMapPair<swift::SILBasicBlock *, uint64_t>, true>
&bbIt) {
if (CalleeCost < TrivialFunctionThreshold) {
// We do not increase code size below this threshold
return true;
}
auto callerCount = bbIt->getSecond();
if (callerCount < 1) {
// Never called - do not inline
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << "profiled decision: NO, "
"reason= Never Called.\n");
return false;
}
auto calleeCount = Callee->getEntryCount();
if (calleeCount) {
// If we have Callee count - use SI heuristic:
auto calleCountVal = calleeCount.getValue();
auto percent = (long double)callerCount / (long double)calleCountVal;
if (percent < 0.8) {
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << "profiled decision: NO, reason=SI "
<< std::to_string(percent) << "%\n");
return false;
}
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << "profiled decision: YES, reason=SI "
<< std::to_string(percent) << "%\n");
} else {
// No callee count - use a "modified" aggressive IHF for now
if (CalleeCost > Benefit && callerCount < 100) {
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << "profiled decision: NO, reason=IHF "
<< callerCount << '\n');
return false;
}
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << "profiled decision: YES, reason=IHF "
<< callerCount << '\n');
}
// We're gonna inline!
NumCallerBlocks += Callee->size();
return true;
}
// Checks if `FAI` can be traced back to a specifically named,
// input enum function argument. If so, the callsite
// containing function is a linear map in Swift Autodiff.
bool SILPerformanceInliner::isAutoDiffLinearMapWithControlFlow(
FullApplySite FAI) {
static const std::string LinearMapBranchTracingEnumPrefix = "_AD__";
auto val = FAI.getCallee();
for (;;) {
if (auto *inst = dyn_cast<SingleValueInstruction>(val)) {
if (auto pi = Projection::isObjectProjection(val)) {
// Extract a member from a struct/tuple/enum.
val = pi->getOperand(0);
continue;
} else if (auto base = stripFunctionConversions(inst)) {
val = base;
continue;
}
return false;
} else if (auto *phiArg = dyn_cast<SILPhiArgument>(val)) {
if (auto *predBB = phiArg->getParent()->getSinglePredecessorBlock()) {
// The terminator of this predecessor block must either be a
// (conditional) branch instruction or a switch_enum.
if (auto *bi = dyn_cast<BranchInst>(predBB->getTerminator())) {
val = bi->getArg(phiArg->getIndex());
continue;
} else if (auto *cbi =
dyn_cast<CondBranchInst>(predBB->getTerminator())) {
val = cbi->getArgForDestBB(phiArg->getParent(), phiArg->getIndex());
continue;
} else if (auto *sei =
dyn_cast<SwitchEnumInst>(predBB->getTerminator())) {
val = sei->getOperand();
continue;
}
return false;
}
}
break;
}
// If `val` now points to a function argument then we have successfully traced
// the callee back to a function argument.
//
// We now need to check if this argument is an enum and named like an autodiff
// branch tracing enum.
if (auto *arg = dyn_cast<SILFunctionArgument>(val)) {
if (auto *enumDecl = arg->getType().getEnumOrBoundGenericEnum()) {
return enumDecl->getName().str().starts_with(
LinearMapBranchTracingEnumPrefix);
}
}
return false;
}
// Checks if the given value is a tuple containing allocated objects
// or partial applies.
//
// Returns true if the number of allocated objects or partial applies is
// greater than 0, and false otherwise.
//
// Returns false if the value is not a tuple.
bool SILPerformanceInliner::isTupleWithAllocsOrPartialApplies(SILValue val) {
if (auto *ti = dyn_cast<TupleInst>(val)) {
for (auto i : range(ti->getNumOperands())) {
SILValue val = ti->getOperand(i);
if (auto base = stripFunctionConversions(val))
val = base;
if (isa<AllocationInst>(val) || isa<PartialApplyInst>(val))
return true;
}
}
return false;
}
// Uses a function's mangled name to determine if it is an Autodiff VJP
// function.
//
// TODO: VJPs of differentiable functions with custom silgen names are not
// recognized as VJPs by this function. However, this is not a hard limitation
// and can be fixed.
bool isFunctionAutodiffVJP(SILFunction *callee) {
swift::Demangle::Context Ctx;
if (auto *Root = Ctx.demangleSymbolAsNode(callee->getName())) {
if (auto *node = Root->findByKind(
swift::Demangle::Node::Kind::AutoDiffFunctionKind, 3)) {
if (node->hasIndex()) {
auto index = (char)node->getIndex();
auto ADFunctionKind = swift::Demangle::AutoDiffFunctionKind(index);
if (ADFunctionKind == swift::Demangle::AutoDiffFunctionKind::VJP) {
return true;
}
}
}
}
return false;
}
bool isProfitableToInlineAutodiffVJP(SILFunction *vjp, SILFunction *caller,
InlineSelection whatToInline,
StringRef stageName) {
bool isLowLevelFunctionPassPipeline = stageName == "LowLevel,Function";
auto isHighLevelFunctionPassPipeline =
stageName == "HighLevel,Function+EarlyLoopOpt";
auto calleeHasControlFlow = vjp->size() > 1;
auto isCallerVJP = isFunctionAutodiffVJP(caller);
auto callerHasControlFlow = caller->size() > 1;
// If the pass is being run as part of the low-level function pass pipeline,
// the autodiff closure-spec optimization is done doing its work. Therefore,
// all VJPs should be considered for inlining.
if (isLowLevelFunctionPassPipeline) {
return true;
}
// If callee has control-flow it will definitely not be handled by the
// Autodiff closure-spec optimization. Therefore, we should consider it for
// inlining.
if (calleeHasControlFlow) {
return true;
}
// If this is the EarlyPerfInline pass we want to have the Autodiff
// closure-spec optimization pass optimize VJPs in isolation before they are
// inlined into other VJPs.
if (isHighLevelFunctionPassPipeline) {
return false;
}
// If this is not the EarlyPerfInline pass, VJPs should only be inlined into
// other VJPs that do not contain any control-flow.
if (!isCallerVJP || (isCallerVJP && callerHasControlFlow)) {
return false;
}
return true;
}
bool SILPerformanceInliner::isProfitableToInline(
FullApplySite AI, Weight CallerWeight, ConstantTracker &callerTracker,
int &NumCallerBlocks,
const llvm::DenseMap<SILBasicBlock *, uint64_t> &BBToWeightMap) {
SILFunction *Callee = AI.getReferencedFunctionOrNull();
assert(Callee);
bool IsGeneric = AI.hasSubstitutions();
if (isFunctionAutodiffVJP(Callee) &&
!isProfitableToInlineAutodiffVJP(Callee, AI.getFunction(), WhatToInline,
this->pm->getStageName())) {
return false;
}
// Start with a base benefit.
int BaseBenefit = isa<BeginApplyInst>(AI) ? RemovedCoroutineCallBenefit
: RemovedCallBenefit;
// If function has more than 5 parameters / results, then increase base
// benefit for each additional parameter. We assume that for each extra
// parameter or result we'd eliminate extra pair of loads and stores used to
// pass / return value via stack.
unsigned numParameters = AI->getNumRealOperands(), numResults = AI->getNumResults();
if (numParameters > 5)
BaseBenefit += (RemovedLoadBenefit + RemovedStoreBenefit) * (numParameters - 5);
if (numResults > 5)
BaseBenefit += (RemovedLoadBenefit + RemovedStoreBenefit) * (numResults - 5);
// Osize heuristic.
//
// As a hack, don't apply this at all to coroutine inlining; avoiding
// coroutine allocation overheads is extremely valuable. There might be
// more principled ways of getting this effect.
bool isClassMethodAtOsize = false;
if (OptMode == OptimizationMode::ForSize && !isa<BeginApplyInst>(AI)) {
// Don't inline into thunks.
if (AI.getFunction()->isThunk())
return false;
// Don't inline class methods.
if (Callee->hasSelfParam()) {
auto SelfTy = Callee->getLoweredFunctionType()->getSelfInstanceType(
FuncBuilder.getModule(), AI.getFunction()->getTypeExpansionContext());
if (SelfTy->mayHaveSuperclass() &&
Callee->getRepresentation() == SILFunctionTypeRepresentation::Method)
isClassMethodAtOsize = true;
}
// Use command line option to control inlining in Osize mode.
const uint64_t CallerBaseBenefitReductionFactor = AI.getFunction()->getModule().getOptions().CallerBaseBenefitReductionFactor;
BaseBenefit = BaseBenefit / CallerBaseBenefitReductionFactor;
}
// It is always OK to inline a simple call.
// TODO: May be consider also the size of the callee?
if (isPureCall(AI, BCA)) {
OptRemark::Emitter::emitOrDebug(DEBUG_TYPE, &ORE, [&]() {
using namespace OptRemark;
return RemarkPassed("Inline", *AI.getInstruction())
<< "Pure call. Always profitable to inline "
<< NV("Callee", Callee);
});
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " pure-call decision " << Callee->getName()
<< '\n');
return true;
}
// Bail out if this generic call can be optimized by means of
// the generic specialization, because we prefer generic specialization
// to inlining of generics.
if (IsGeneric && canSpecializeGeneric(AI, Callee, AI.getSubstitutionMap())) {
return false;
}
// Bail out if this is a generic call of a `@_specialize(exported:)` function
// and we are in the early inliner. We want to give the generic specializer
// the opportunity to see specialized call sites.
if (IsGeneric && WhatToInline == InlineSelection::NoSemanticsAndEffects &&
Callee->hasPrespecialization()) {
return false;
}
SILLoopInfo *CalleeLI = LA->get(Callee);
ShortestPathAnalysis *CalleeSPA = getSPA(Callee, CalleeLI);
if (!CalleeSPA->isValid()) {
CalleeSPA->analyze(CBI, [](FullApplySite FAS) {
// We don't compute SPA for another call-level. Functions called from
// the callee are assumed to have DefaultApplyLength.
return DefaultApplyLength;
});
}
ConstantTracker constTracker(Callee, &callerTracker, AI);
DominanceInfo *DT = DA->get(Callee);
SILBasicBlock *CalleeEntry = &Callee->front();
DominanceOrder domOrder(CalleeEntry, DT, Callee->size());
// We don't want to blow up code-size
// We will only inline if *ALL* dynamic accesses are
// known and have no nested conflict
bool AllAccessesBeneficialToInline = true;
bool returnsAllocation = false;
// Calculate the inlining cost of the callee.
int CalleeCost = 0;
int Benefit = 0;
// We don’t know if we want to update the benefit with
// the exclusivity heuristic or not. We can *only* do that
// if AllAccessesBeneficialToInline is true
int ExclusivityBenefitWeight = 0;
int ExclusivityBenefitBase = ExclusivityBenefit;
if (EnableSILAggressiveInlining) {
ExclusivityBenefitBase += 500;
}
SubstitutionMap CalleeSubstMap = AI.getSubstitutionMap();
CallerWeight.updateBenefit(Benefit, BaseBenefit);
// Go through all blocks of the function, accumulate the cost and find
// benefits.
while (SILBasicBlock *block = domOrder.getNext()) {
constTracker.beginBlock();
Weight BlockW = CalleeSPA->getWeight(block, CallerWeight);
for (SILInstruction &I : *block) {
constTracker.trackInst(&I);
CalleeCost += (int)instructionInlineCost(I);
if (FullApplySite FAI = FullApplySite::isa(&I)) {
// Check if the callee is passed as an argument. If so, increase the
// threshold, because inlining will (probably) eliminate the closure.
SILInstruction *def = constTracker.getDefInCaller(FAI.getCallee());
if (def && (isa<FunctionRefInst>(def) || isa<PartialApplyInst>(def)))
BlockW.updateBenefit(Benefit, RemovedClosureBenefit);
else if (isAutoDiffLinearMapWithControlFlow(FAI)) {
// TODO: Do we need to tweak inlining benefits given to pullbacks
// (with and without control-flow)?
// For linear maps in Swift Autodiff, callees may be passed as an
// argument, however, they may be hidden behind a branch-tracing
// enum (tracing execution flow of the original function).
//
// If we can establish that we are inside of a Swift Autodiff linear
// map and that the branch tracing input enum is wrapping pullback
// closures, then we can update this function's benefit with
// `RemovedClosureBenefit` because inlining will (probably) eliminate
// the closure.
BlockW.updateBenefit(Benefit, RemovedClosureBenefit);
}
// Check if inlining the callee would allow for further
// optimizations like devirtualization or generic specialization.
if (!def)
def = dyn_cast_or_null<SingleValueInstruction>(FAI.getCallee());
if (!def)
continue;
auto Subs = FAI.getSubstitutionMap();
// Bail if it is not a generic call or inlining of generics is forbidden.
if (!EnableSILInliningOfGenerics || !Subs.hasAnySubstitutableParams())
continue;
if (!isa<FunctionRefInst>(def) && !isa<ClassMethodInst>(def) &&
!isa<WitnessMethodInst>(def))
continue;
// It is a generic call inside the callee. Check if after inlining
// it will be possible to perform a generic specialization or
// devirtualization of this call.
// Create the list of substitutions as they will be after
// inlining.
auto SubMap = Subs.subst(CalleeSubstMap);
// Check if the call can be devirtualized.
if (isa<ClassMethodInst>(def) || isa<WitnessMethodInst>(def) ||
isa<SuperMethodInst>(def)) {
// TODO: Take AI.getSubstitutions() into account.
if (canDevirtualizeApply(FAI, nullptr)) {
LLVM_DEBUG(llvm::dbgs() << "Devirtualization will be possible "
"after inlining for the call:\n";
FAI.getInstruction()->dumpInContext());
BlockW.updateBenefit(Benefit, DevirtualizedCallBenefit);
}
}
// Check if a generic specialization would be possible.
if (isa<FunctionRefInst>(def)) {
auto CalleeF = FAI.getCalleeFunction();
if (!canSpecializeGeneric(FAI, CalleeF, SubMap))
continue;
LLVM_DEBUG(llvm::dbgs() << "Generic specialization will be possible "
"after inlining for the call:\n";
FAI.getInstruction()->dumpInContext());
BlockW.updateBenefit(Benefit, GenericSpecializationBenefit);
}
} else if (auto *LI = dyn_cast<LoadInst>(&I)) {
// Check if it's a load from a stack location in the caller. Such a load
// might be optimized away if inlined.
if (constTracker.isStackAddrInCaller(LI->getOperand()))
BlockW.updateBenefit(Benefit, RemovedLoadBenefit);
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
// Check if it's a store to a stack location in the caller. Such a load
// might be optimized away if inlined.
if (constTracker.isStackAddrInCaller(SI->getDest()))
BlockW.updateBenefit(Benefit, RemovedStoreBenefit);
} else if (isa<StrongReleaseInst>(&I) || isa<ReleaseValueInst>(&I)) {
SILValue Op = stripCasts(I.getOperand(0));
if (auto *Arg = dyn_cast<SILFunctionArgument>(Op)) {
if (Arg->getArgumentConvention() ==
SILArgumentConvention::Direct_Guaranteed) {
BlockW.updateBenefit(Benefit, RefCountBenefit);
}
}
} else if (auto *BI = dyn_cast<BuiltinInst>(&I)) {
if (BI->getBuiltinInfo().ID == BuiltinValueKind::OnFastPath)
BlockW.updateBenefit(Benefit, FastPathBuiltinBenefit);
} else if (auto *BAI = dyn_cast<BeginAccessInst>(&I)) {
if (BAI->getEnforcement() == SILAccessEnforcement::Dynamic) {
// The access is dynamic and has no nested conflict
// See if the storage location is considered by
// access enforcement optimizations
auto storage = AccessStorage::compute(BAI->getSource());
if (BAI->hasNoNestedConflict() && (storage.isFormalAccessBase())) {
BlockW.updateBenefit(ExclusivityBenefitWeight,
ExclusivityBenefitBase);
} else {
AllAccessesBeneficialToInline = false;
}
}
} else if (auto ri = dyn_cast<ReturnInst>(&I)) {
SILValue retVal = ri->getOperand();
if (auto *eir = dyn_cast<EndInitLetRefInst>(retVal))
retVal = eir->getOperand();
if (auto *uci = dyn_cast<UpcastInst>(retVal))
retVal = uci->getOperand();
// Inlining functions which return an allocated object or partial_apply
// most likely has a benefit in the caller, because e.g. it can enable
// de-virtualization.
if (isa<AllocationInst>(retVal) || isa<PartialApplyInst>(retVal) || isTupleWithAllocsOrPartialApplies(retVal)) {
BlockW.updateBenefit(Benefit, RemovedCallBenefit + 10);
returnsAllocation = true;
}
}
}
// Don't count costs in blocks which are dead after inlining.
SILBasicBlock *takenBlock = constTracker.getTakenBlock(block->getTerminator());
if (takenBlock) {
BlockW.updateBenefit(Benefit, RemovedTerminatorBenefit);
domOrder.pushChildrenIf(block, [=](SILBasicBlock *child) {
return child->getSinglePredecessorBlock() != block ||
child == takenBlock;
});
} else {
domOrder.pushChildren(block);
}
}
if (AllAccessesBeneficialToInline) {
Benefit = std::max(Benefit, ExclusivityBenefitWeight);
}
if (AI.getFunction()->isThunk()) {
// Only inline trivial functions into thunks (which will not increase the
// code size).
if (CalleeCost > TrivialFunctionThreshold) {
return false;
}
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " decision {" << CalleeCost << " into thunk} "
<< Callee->getName() << '\n');
return true;
}
// We reduce the benefit if the caller is too large. For this we use a
// cubic function on the number of caller blocks. This starts to prevent
// inlining at about 800 - 1000 caller blocks.
if (NumCallerBlocks < BlockLimitMaxIntNumerator)
Benefit -=
(NumCallerBlocks * NumCallerBlocks) / BlockLimitDenominator *
NumCallerBlocks / BlockLimitDenominator;
else
// The calculation in the if branch would overflow if we performed it.
Benefit = 0;
// If we have profile info - use it for final inlining decision.
auto *bb = AI.getInstruction()->getParent();
auto bbIt = BBToWeightMap.find(bb);
if (bbIt != BBToWeightMap.end()) {
if (profileBasedDecision(AI, Benefit, Callee, CalleeCost, NumCallerBlocks,
bbIt)) {
OptRemark::Emitter::emitOrDebug(DEBUG_TYPE, &ORE, [&]() {
using namespace OptRemark;
return RemarkPassed("Inline", *AI.getInstruction())
<< "Profitable due to provided profile";
});
return true;
}
OptRemark::Emitter::emitOrDebug(DEBUG_TYPE, &ORE, [&]() {
using namespace OptRemark;
return RemarkMissed("Inline", *AI.getInstruction())
<< "Not profitable due to provided profile";
});
return false;
}
if (isClassMethodAtOsize && Benefit > OSizeClassMethodBenefit) {
Benefit = OSizeClassMethodBenefit;
if (returnsAllocation)
Benefit += 10;
}
// This is the final inlining decision.
if (CalleeCost > Benefit) {
OptRemark::Emitter::emitOrDebug(DEBUG_TYPE, &ORE, [&]() {
using namespace OptRemark;
return RemarkMissed("Inline", *AI.getInstruction())
<< "Not profitable to inline function " << NV("Callee", Callee)
<< " (cost = " << NV("Cost", CalleeCost)
<< ", benefit = " << NV("Benefit", Benefit) << ")";
});
return false;
}
NumCallerBlocks += Callee->size();
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " decision {c=" << CalleeCost
<< ", b=" << Benefit
<< ", l=" << CalleeSPA->getScopeLength(CalleeEntry, 0)
<< ", c-w=" << CallerWeight
<< ", bb=" << Callee->size()
<< ", c-bb=" << NumCallerBlocks
<< "} " << Callee->getName() << '\n');
OptRemark::Emitter::emitOrDebug(DEBUG_TYPE, &ORE, [&]() {
using namespace OptRemark;
return RemarkPassed("Inlined", *AI.getInstruction())
<< NV("Callee", Callee) << " inlined into "
<< NV("Caller", AI.getFunction())
<< " (cost = " << NV("Cost", CalleeCost)
<< ", benefit = " << NV("Benefit", Benefit) << ")";
});
return true;
}
static bool returnsClosure(SILFunction *F) {
for (SILBasicBlock &BB : *F) {
if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
return isa<PartialApplyInst>(RI->getOperand());
}
}
return false;
}
static bool hasMaxNumberOfBasicBlocks(SILFunction *f, int limit) {
for (SILBasicBlock &block : *f) {
(void)block;
if (limit == 0)
return false;
limit--;
}
return true;
}
static bool isInlineAlwaysCallSite(SILFunction *Callee, int numCallerBlocks) {
if (Callee->isTransparent())
return true;
if (Callee->getInlineStrategy() == AlwaysInline &&
!Callee->getModule().getOptions().IgnoreAlwaysInline &&
// Protect against misuse of @inline(__always).
// Inline-always should only be used on relatively small functions.
// It must not be used on recursive functions. This check prevents that
// the compiler blows up if @inline(__always) is put on a recursive function.
(numCallerBlocks < 64 || hasMaxNumberOfBasicBlocks(Callee, 64))) {
return true;
}
return false;
}
/// Checks if a given generic apply should be inlined unconditionally, i.e.
/// without any complex analysis using e.g. a cost model.
/// It returns true if a function should be inlined.
/// It returns false if a function should not be inlined.
/// It returns None if the decision cannot be made without a more complex
/// analysis.
static std::optional<bool> shouldInlineGeneric(FullApplySite AI,
int numCallerBlocks) {
assert(AI.hasSubstitutions() &&
"Expected a generic apply");
SILFunction *Callee = AI.getReferencedFunctionOrNull();
// Do not inline @_semantics functions when compiling the stdlib,
// because they need to be preserved, so that the optimizer
// can properly optimize a user code later.
ModuleDecl *SwiftModule = Callee->getModule().getSwiftModule();
if ((Callee->hasSemanticsAttrThatStartsWith("array.") ||
Callee->hasSemanticsAttrThatStartsWith("fixed_storage.")) &&
(SwiftModule->isStdlibModule() || SwiftModule->isOnoneSupportModule()))
return false;
// Do not inline into thunks.
if (AI.getFunction()->isThunk())
return false;
// Always inline generic functions which are marked as
// AlwaysInline or transparent.
if (isInlineAlwaysCallSite(Callee, numCallerBlocks))
return true;
// If all substitutions are concrete, then there is no need to perform the
// generic inlining. Let the generic specializer create a specialized
// function and then decide if it is beneficial to inline it.
if (!AI.getSubstitutionMap().getRecursiveProperties().hasArchetype())
return false;
if (Callee->getLoweredFunctionType()->getCoroutineKind() !=
SILCoroutineKind::None) {
// Co-routines are so expensive (e.g. Array.subscript.read) that we always
// enable inlining them in a generic context. Though the final inlining
// decision is done by the usual heuristics. Therefore we return None and
// not true.
return std::nullopt;
}
// The returned partial_apply of a thunk is most likely being optimized away
// if inlined. Because some thunks cannot be specialized (e.g. if an opened
// existential is in the substitution list), we inline such thunks also in case
// they are generic.
if (Callee->isThunk() && returnsClosure(Callee))
return true;
// All other generic functions should not be inlined if this kind of inlining
// is disabled.
if (!EnableSILInliningOfGenerics)
return false;
// It is not clear yet if this function should be decided or not.
return std::nullopt;
}
bool SILPerformanceInliner::decideInWarmBlock(
FullApplySite AI, Weight CallerWeight, ConstantTracker &callerTracker,
int &NumCallerBlocks,
const llvm::DenseMap<SILBasicBlock *, uint64_t> &BBToWeightMap) {
if (AI.hasSubstitutions()) {
// Only inline generics if definitively clear that it should be done.
auto ShouldInlineGeneric = shouldInlineGeneric(AI, NumCallerBlocks);
if (ShouldInlineGeneric.has_value())
return ShouldInlineGeneric.value();
}
SILFunction *Callee = AI.getReferencedFunctionOrNull();
if (isInlineAlwaysCallSite(Callee, NumCallerBlocks)) {
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " always-inline decision "
<< Callee->getName() << '\n');
return true;
}
return isProfitableToInline(AI, CallerWeight, callerTracker, NumCallerBlocks,
BBToWeightMap);
}
/// Return true if inlining this call site into a cold block is profitable.
bool SILPerformanceInliner::decideInColdBlock(FullApplySite AI,
SILFunction *Callee, int numCallerBlocks) {
if (AI.hasSubstitutions()) {
// Only inline generics if definitively clear that it should be done.
auto ShouldInlineGeneric = shouldInlineGeneric(AI, numCallerBlocks);
if (ShouldInlineGeneric.has_value())
return ShouldInlineGeneric.value();
return false;
}
if (isInlineAlwaysCallSite(Callee, numCallerBlocks)) {
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " always-inline decision "
<< Callee->getName() << '\n');
return true;
}
int CalleeCost = 0;
for (SILBasicBlock &Block : *Callee) {
for (SILInstruction &I : Block) {
CalleeCost += int(instructionInlineCost(I));
if (CalleeCost > TrivialFunctionThreshold)
return false;
}
}
LLVM_DEBUG(dumpCaller(AI.getFunction());
llvm::dbgs() << " cold decision {" << CalleeCost << "} "
<< Callee->getName() << '\n');
return true;
}
/// Record additional weight increases.
///
/// Why can't we just add the weight when we call isProfitableToInline? Because
/// the additional weight is for _another_ function than the current handled
/// callee.
static void addWeightCorrection(FullApplySite FAS,
llvm::DenseMap<FullApplySite, int> &WeightCorrections) {
SILFunction *Callee = FAS.getReferencedFunctionOrNull();
if (Callee && Callee->hasSemanticsAttr(semantics::ARRAY_UNINITIALIZED)) {
// We want to inline the argument to an array.uninitialized call, because
// this argument is most likely a call to a function which contains the
// buffer allocation for the array. It is essential to inline it for stack
// promotion of the array buffer.
SILValue BufferArg = FAS.getArgument(0);
SILValue Base = stripValueProjections(stripCasts(BufferArg));
if (auto BaseApply = FullApplySite::isa(Base))
WeightCorrections[BaseApply] += 6;
}
}
static bool containsWeight(TermInst *inst) {
for (auto &succ : inst->getSuccessors()) {
if (succ.getCount()) {
return true;
}
}
return false;
}
static void
addToBBCounts(llvm::DenseMap<SILBasicBlock *, uint64_t> &BBToWeightMap,
uint64_t numToAdd, swift::TermInst *termInst) {
for (auto &succ : termInst->getSuccessors()) {
auto *currBB = succ.getBB();
assert(BBToWeightMap.find(currBB) != BBToWeightMap.end() &&