Repository navigation
Expand file tree
/
Copy pathAOTHeatGraph.cpp
More file actions
2312 lines (2209 loc) · 112 KB
/
Copy pathAOTHeatGraph.cpp
File metadata and controls
2312 lines (2209 loc) · 112 KB
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
/*
* Copyright (C) 2026 Oven, Inc. All rights reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "config.h"
#include "AOTHeatGraph.h"
#if ENABLE(AOT)
#include "AOTBlockFrequencies.h"
#include "AOTBodyIndex.h"
#include "AOTBuildContext.h"
#include "AOTBuiltinIDs.h"
#include "AOTCallGraph.h"
#include "AOTDiagnostics.h"
#include "AOTEffectSummaries.h"
#include "AOTEffectsDescription.h"
#include "AOTEffectsOfOperands.h"
#include "AOTEffectsOfProtocols.h"
#include "AOTFlowResults.h"
#include "AOTFunctionAnalyses.h"
#include "AOTGrouping.h"
#include "AOTHeldOperands.h"
#include "AOTIR.h"
#include "AOTImagesBelow.h"
#include "AOTLargeVectors.h"
#include "AOTLayout.h"
#include "AOTOpcodesNamingRecords.h"
#include "AOTPropertyAccessElements.h"
#include "AOTSort.h"
#include "AOTThreshold.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <concepts>
#include <optional>
#include <tuple>
#include <wtf/Atomics.h>
#include <wtf/BitVector.h>
#include <wtf/CycleForest.h>
#include <wtf/FrequencyEstimator.h>
#include <wtf/HashMap.h>
#include <wtf/Hasher.h>
#include <wtf/Lock.h>
#include <wtf/PrintStream.h>
#include <wtf/ThreadSafeRefCounted.h>
namespace JSC { namespace AOT { namespace Typed {
static_assert(HeatModel::eventsPerRun == frequencyConstants.maxMultiplier);
namespace {
struct WeightedCall {
uint32_t node;
double weight;
// How surely the call is made once its function is entered, where an even branch counts as taken.
double share { 0 };
// The caller also calls a long set that holds the node. The weight and the share are those of both together.
bool isAlsoInLongSet { false };
};
using WeightedCallList = Vector<WeightedCall, 4>;
struct SharedCallList : ThreadSafeRefCounted<SharedCallList> {
explicit SharedCallList(WeightedCallList&& calls)
: calls(WTF::move(calls))
{
}
WeightedCallList calls;
};
class SharedCallLists {
public:
Ref<SharedCallList> intern(WeightedCallList&& calls)
{
Hasher hasher;
for (const WeightedCall& call : calls)
add(hasher, call.node, call.weight, call.share, call.isAlsoInLongSet);
auto isSame = [](const WeightedCall& a, const WeightedCall& b) {
return a.node == b.node && a.weight == b.weight && a.share == b.share && a.isAlsoInLongSet == b.isAlsoInLongSet;
};
Locker locker { m_lock };
auto& lists = m_listsByHash.add(hasher.hash(), Vector<Ref<SharedCallList>, 1> { }).iterator->value;
for (const Ref<SharedCallList>& list : lists) {
if (std::ranges::equal(list->calls, calls, isSame))
return list;
}
calls.shrinkToFit();
lists.append(adoptRef(*new SharedCallList(WTF::move(calls))));
return lists.last();
}
private:
Lock m_lock;
UncheckedKeyHashMap<uint64_t, Vector<Ref<SharedCallList>, 1>, DefaultHash<uint64_t>, WTF::UnsignedWithZeroKeyHashTraits<uint64_t>> m_listsByHash;
};
// The calls of one node. n functions that each may call any of the n have n equal lists of n calls, so nodes with equal long lists share one.
class CallsOfNode {
public:
std::span<const WeightedCall> span() const LIFETIME_BOUND { return m_shared ? m_shared->calls.span() : m_own.span(); }
auto begin() const LIFETIME_BOUND { return span().begin(); }
auto end() const LIFETIME_BOUND { return span().end(); }
size_t size() const { return span().size(); }
const SharedCallList* sharedList() const { return m_shared.get(); }
CallsOfNode& operator=(WeightedCallList&& calls)
{
m_shared = nullptr;
m_own = WTF::move(calls);
return *this;
}
void take(WeightedCallList&& calls, SharedCallLists& sharedLists)
{
AOT_THRESHOLD(size_t, minCallsOfSharedList, 16);
if (calls.size() < minCallsOfSharedList) {
*this = WTF::move(calls);
return;
}
m_own = { };
m_shared = sharedLists.intern(WTF::move(calls));
}
void clear() { *this = WeightedCallList(); }
void removeAllMatching(NOESCAPE const Invocable<bool(const WeightedCall&)> auto& matches)
{
if (m_shared) {
if (std::ranges::none_of(m_shared->calls, matches))
return;
*this = WeightedCallList(m_shared->calls);
}
m_own.removeAllMatching(matches);
}
private:
WeightedCallList m_own;
RefPtr<SharedCallList> m_shared;
};
enum class CallOfHost : uint8_t { StaysUnlessCalleeRunsOnce, IsReplaced };
// Ranks say which of two functions runs more often: a call of a name shares its weight among the functions under the name.
// Classes say whether a function runs at all, and about how often: what a call of a name may enter is entered as a loop would enter it, or as often as events come.
enum class EstimateOf : uint8_t { Ranks, Classes };
} // anonymous namespace
static void mergeEdges(WeightedCallList& calls)
{
AOT::stableSortInLine(calls, [](const WeightedCall& a, const WeightedCall& b) {
return a.node < b.node;
});
size_t mergedSize = 0;
for (size_t index = 0; index < calls.size(); ++index) {
WeightedCall call = calls[index];
if (mergedSize && calls[mergedSize - 1].node == call.node) {
calls[mergedSize - 1].weight += call.weight;
calls[mergedSize - 1].share = std::max(calls[mergedSize - 1].share, call.share);
} else
calls[mergedSize++] = call;
}
calls.shrink(mergedSize);
}
static bool mayHaveNoLayout(const Type& object) { return object.anyObject || !object.classes.isEmpty(); }
static bool saysNothingAboutCalls(OperandUses uses) { return uses.containsAll(callingUses); }
static constexpr OpcodeSet opcodesThatMayEnterBuiltins = []() consteval {
OpcodeSet opcodes;
for (unsigned index = 0; index < numberOfEnumerators<Opcode>; ++index) {
EffectRule rule = effectRuleOf(static_cast<Opcode>(index));
if (rule == EffectRule::Call || rule == EffectRule::Builtin)
opcodes.add(static_cast<Opcode>(index));
}
return opcodes;
}();
static bool entersOnlyBuiltins(const Program& program, const Value& call)
{
if (effectRuleOf(call.opcode) == EffectRule::Builtin)
return true;
CalleeList list = calleesOfCall(program, call);
std::optional<ProvenValue<Callees>> callees = list.all();
return callees && callees->value().functions.empty() && !callees->value().builtins.empty();
}
static double estimateCallbackCalls(OperandUses uses)
{
if (saysNothingAboutCalls(uses))
return 1;
if (uses.contains(OperandUse::CallsRepeatedly))
return HeatModel::callsOfRepeatedCallback;
if (uses.contains(OperandUse::CallsPerElement))
return HeatModel::callsPerElement;
return 1;
}
static bool isHandedToCodeThatRuns(const Value& user, uint32_t operandIndex)
{
if (effectRuleOf(user.opcode) != EffectRule::Call)
return true;
return !user.operandUses(operandIndex).containsAny(callingUses) && OperandPosition::newTarget(user.opcode) != operandIndex;
}
static bool isHandedToCodeThatRuns(const Terminator&, uint32_t) { return true; }
static double shareOfClass(Expected<BlockFrequency> frequency)
{
if (frequency.predicted() == BlockFrequency::Normal)
return 1;
return frequency.predicted() == BlockFrequency::Unlikely ? frequencyConstants.unlikelyEdgeShare : frequencyConstants.rareEdgeShare;
}
static Vector<WeightOfBlock> computeWeightsOfBlocks(FunctionAnalyses& analyses)
{
const BlockFrequencies& frequencies = analyses.blockFrequencies();
Vector<WeightOfBlock> weights;
weights.reserveInitialCapacity(analyses.cfg().reversePostOrder().size());
for (BlockID id : analyses.cfg().reversePostOrder())
weights.append(WeightOfBlock { id, frequencies.frequencyOf(id).predicted(), shareOfClass(frequencies.classOf(id)) });
return weights;
}
static double estimateIndirectCalls(const FlowIndirectCall& call)
{
bool describesSite = call.kind == FlowIndirectCallKind::BuiltinCallback || call.times.predicted() == BuiltinCallbackTimes::Once;
double runsOfSite = call.isInCycle && describesSite ? frequencyConstants.iterationsPerLoop : 1;
switch (call.times.predicted()) {
case BuiltinCallbackTimes::PerEvent:
return 0;
case BuiltinCallbackTimes::Repeatedly:
return runsOfSite * HeatModel::callsOfRepeatedCallback;
case BuiltinCallbackTimes::PerElement:
return runsOfSite * HeatModel::callsPerElement;
case BuiltinCallbackTimes::Later:
case BuiltinCallbackTimes::Once:
return runsOfSite;
}
RELEASE_ASSERT_NOT_REACHED();
}
namespace {
// The functions that a store, a definition or a literal of the program puts under a name, and whose callers are not all known.
class FunctionsUnderNames {
public:
FunctionsUnderNames() = default;
FunctionsUnderNames(const Program&, const CallGraph&, const ParallelLoops&);
size_t size() const { return m_names.size(); }
std::optional<size_t> find(PropertyKeyID name) const
{
auto found = std::ranges::lower_bound(m_names, name);
if (found == m_names.end() || *found != name)
return std::nullopt;
return found - m_names.begin();
}
std::span<const FunctionID> at(size_t position) const LIFETIME_BOUND { return m_functions.span().subspan(m_first[position], m_first[position + 1] - m_first[position]); }
std::span<const FunctionID> accessorsAt(size_t position, FunctionKind kind) const LIFETIME_BOUND
{
uint32_t first = kind == FunctionKind::Getter ? m_firstGetter[position] : m_firstSetter[position];
uint32_t end = kind == FunctionKind::Getter ? m_firstSetter[position] : m_firstGetter[position + 1];
return m_accessors.span().subspan(first, end - first);
}
bool isUnderSomeName(FunctionID function) const { return m_isUnderSomeName.get(function.index()); }
// Of these functions, the ones that lie in objects of one layout, under whatever name. No layout stands for the objects whose layout nobody knows.
static uint32_t holderOf(LayoutID layout) { return layout ? layout.index() + 1 : 0; }
size_t numberOfHolders() const { return m_firstInHolder.isEmpty() ? 0 : m_firstInHolder.size() - 1; }
std::span<const FunctionID> inHolder(uint32_t holder) const LIFETIME_BOUND { return m_functionsInHolders.span().subspan(m_firstInHolder[holder], m_firstInHolder[holder + 1] - m_firstInHolder[holder]); }
private:
Vector<PropertyKeyID> m_names;
Vector<uint32_t> m_first;
Vector<FunctionID> m_functions;
Vector<uint32_t> m_firstGetter;
Vector<uint32_t> m_firstSetter;
Vector<FunctionID> m_accessors;
BitVector m_isUnderSomeName;
Vector<uint32_t> m_firstInHolder;
Vector<FunctionID> m_functionsInHolders;
};
} // anonymous namespace
// A value that may be one of more functions than this tells nothing about what lies under the name.
AOT_THRESHOLD(size_t, maxFunctionsOfStoredValue, 8);
static_assert(OperandIndex::PropSet::object == OperandIndex::PropDefine::object && OperandIndex::PropSet::value == OperandIndex::PropDefine::value);
static_assert(OperandIndex::PutSlot::object == OperandIndex::PutSlotOrAdd::object && OperandIndex::PutSlot::value == OperandIndex::PutSlotOrAdd::value);
FunctionsUnderNames::FunctionsUnderNames(const Program& program, const CallGraph& callGraph, const ParallelLoops& loops)
{
auto packedKeyOf = [](PropertyKeyID name, FunctionID function) {
return static_cast<uint64_t>(name.index()) << 32 | function.index();
};
auto isWanted = [&](FunctionID function) {
return program.at(function).hasBody() && callGraph.callerSet(function) != CallerSet::Complete;
};
// Behind every name in the order of the packed keys.
constexpr uint64_t namesHolder = 1ull << 63;
auto packedHolderOf = [&](LayoutID layout, FunctionID function) {
return namesHolder | static_cast<uint64_t>(holderOf(layout ? declaredLayoutOf(program, layout) : layout)) << 32 | function.index();
};
Vector<uint64_t> allStored = collectInParallel<uint64_t>(loops, program.functions.size(), [&](unsigned index, Vector<uint64_t>& stored) {
const Function& function = program.functions[index];
if (!function.hasBody())
return;
auto add = [&](PropertyKeyID name, ValueID value, const auto& forEachLayoutOfHolder) {
if (!name || !value)
return;
const Type& type = program.typeOf(function, value);
if (type.functions.size() > maxFunctionsOfStoredValue)
return;
for (FunctionID callee : type.functions) {
if (!isWanted(callee))
continue;
stored.append(packedKeyOf(name, callee));
forEachLayoutOfHolder([&](LayoutID layout) {
stored.append(packedHolderOf(layout, callee));
});
}
};
auto addTo = [&](ValueID holder, PropertyKeyID name, ValueID value) {
add(name, value, [&](const auto& note) {
const Type& type = program.typeOf(function, holder);
for (LayoutID layout : membersOf(program, type))
note(layout);
if (mayHaveNoLayout(type))
note(LayoutID());
});
};
forEachValueListedOrNot(program, FunctionID(index), { Opcode::PropSet, Opcode::PropDefine, Opcode::PutSlot, Opcode::PutSlotOrAdd, Opcode::NewObject, Opcode::DefineMethod }, [&](ValueID, const Value& value) {
if (value.opcode == Opcode::NewObject) {
const Vector<Field>& fields = program.at(declaredLayoutOf(program, value.layout())).fields;
std::span<const uint32_t> listed = value.fields();
for (size_t position = 0; position < listed.size(); ++position)
add(fields[listed[position]].key, value.operand(OperandIndex::NewObject::values + position), [&](const auto& note) { note(value.layout()); });
return;
}
if (value.opcode == Opcode::DefineMethod) {
add(value.key(), value.operand(OperandIndex::DefineMethod::function), [](const auto&) { });
return;
}
bool storesInSlot = value.opcode == Opcode::PutSlot || value.opcode == Opcode::PutSlotOrAdd;
addTo(value.operand(storesInSlot ? OperandIndex::PutSlot::object : OperandIndex::PropSet::object), value.key(), value.operand(storesInSlot ? OperandIndex::PutSlot::value : OperandIndex::PropSet::value));
});
});
for (uint32_t index = 0; index < program.layouts.size(); ++index) {
const Layout& layout = program.layouts[index];
for (const Vector<ClassMember>* members : { &layout.classFlow.members, &layout.classFlow.namedMembers }) {
for (const ClassMember& member : *members) {
if (member.key && member.function && isWanted(member.function)) {
allStored.append(packedKeyOf(member.key, member.function));
allStored.append(packedHolderOf(LayoutID(index), member.function));
}
}
}
}
sortAndRemoveDuplicates(loops, allStored);
size_t numberUnderNames = std::ranges::lower_bound(allStored, namesHolder) - allStored.begin();
m_firstInHolder.fill(0u, program.layouts.size() + 2);
m_functionsInHolders.reserveInitialCapacity(allStored.size() - numberUnderNames);
for (uint64_t stored : allStored.span().subspan(numberUnderNames)) {
++m_firstInHolder[static_cast<uint32_t>((stored & ~namesHolder) >> 32) + 1];
m_functionsInHolders.append(FunctionID(static_cast<uint32_t>(stored)));
}
for (size_t holder = 1; holder < m_firstInHolder.size(); ++holder)
m_firstInHolder[holder] += m_firstInHolder[holder - 1];
allStored.shrink(numberUnderNames);
// `x.name(..)` calls what a getter under the name answers, and `x.name()(..)` what a method under it does.
allStored.appendVector(collectInParallel<uint64_t>(loops, allStored.size(), [&](unsigned position, Vector<uint64_t>& answered) {
PropertyKeyID name(static_cast<uint32_t>(allStored[position] >> 32));
FunctionID holder(static_cast<uint32_t>(allStored[position]));
const Function& function = program.at(holder);
forEachBlockEndingWith(program, holder, { TerminatorKind::Return }, [&](BlockID block) {
ValueID result = function.at(block).terminator.valueOperand();
if (!result)
return;
const Type& type = program.typeOf(function, result);
if (type.functions.size() > maxFunctionsOfStoredValue)
return;
for (FunctionID callee : type.functions) {
if (isWanted(callee))
answered.append(packedKeyOf(name, callee));
}
});
}));
sortAndRemoveDuplicates(loops, allStored);
m_functions.reserveInitialCapacity(allStored.size());
for (uint64_t stored : allStored) {
PropertyKeyID name(static_cast<uint32_t>(stored >> 32));
if (m_names.isEmpty() || m_names.last() != name) {
m_names.append(name);
m_first.append(m_functions.size());
}
m_functions.append(FunctionID(static_cast<uint32_t>(stored)));
m_isUnderSomeName.set(static_cast<uint32_t>(stored));
}
m_first.append(m_functions.size());
for (size_t position = 0; position < m_names.size(); ++position) {
for (auto [kind, first] : { std::pair { FunctionKind::Getter, &m_firstGetter }, std::pair { FunctionKind::Setter, &m_firstSetter } }) {
first->append(m_accessors.size());
for (FunctionID function : at(position)) {
if (program.at(function).kind == kind)
m_accessors.append(function);
}
}
}
m_firstGetter.append(m_accessors.size());
}
static bool readsUnderName(Opcode opcode) { return accessOf(opcode) == Access::Read && PayloadWord::key(opcode); }
static PropertyKeyID nameOfCallee(const Program& program, const Function& function, const Value& call)
{
if (call.opcode == Opcode::CallMethod)
return call.key();
if (!PayloadWord::calleeKey(call.opcode))
return { };
if (call.calleeKey())
return call.calleeKey();
if (call.opcode != Opcode::Call && call.opcode != Opcode::CallList)
return { };
const Value& callee = function.at(call.operand(0));
if (readsUnderName(callee.opcode))
return callee.key();
if (callee.opcode != Opcode::ElemGet)
return { };
ConstantKey key = constantKeyOf(program, program.typeOf(function, callee.operand(OperandIndex::ElemGet::property)));
return key.kind == ConstantKeyKind::Symbol ? key.symbol : PropertyKeyID();
}
static PropertyKeyID nameOfCallee(const Program&, const Function&, const Terminator&) { return { }; }
static bool isCall(const Value& value) { return effectRuleOf(value.opcode) == EffectRule::Call; }
static bool isCall(const Terminator& terminator) { return effectRuleOf(terminator.kind) == EffectRule::Call; }
// A read under a name that runs code nobody knows runs what a descriptor holds under `get`, and a store what one holds under `set`.
static PropertyKeyID nameOfAccessorInDescriptor(const Program& program, const Value& access)
{
if (!PayloadWord::key(access.opcode) || !access.key())
return { };
if (accessOf(access.opcode) == Access::Read)
return program.keyOf(BuiltinNames::get);
return accessOf(access.opcode) == Access::Store ? program.keyOf(BuiltinNames::set) : PropertyKeyID();
}
static PropertyKeyID nameOfAccessorInDescriptor(const Program&, const Terminator&) { return { }; }
struct AccessorsReached {
PropertyKeyID name;
FunctionKind kind { FunctionKind::Getter };
};
static AccessorsReached accessorsReachedBy(const Value& access)
{
if (!PayloadWord::key(access.opcode) || !access.key())
return { };
if (accessOf(access.opcode) == Access::Read)
return { access.key(), FunctionKind::Getter };
return accessOf(access.opcode) == Access::Store ? AccessorsReached { access.key(), FunctionKind::Setter } : AccessorsReached { };
}
static AccessorsReached accessorsReachedBy(const Terminator&) { return { }; }
static bool constructsUnknownCallee(const Program& program, const Function& function, const Value& value)
{
std::optional<unsigned> callee = OperandPosition::callee(value.opcode);
return callee && OperandPosition::newTarget(value.opcode) && !calleesOf(program, program.typeOf(function, value.operand(*callee))).listsEveryCallee();
}
static bool constructsUnknownCallee(const Program&, const Function&, const Terminator&) { return false; }
static std::span<const FunctionID> expectedCalleesOf(const Program& program, const Function& function, const Value& call)
{
std::optional<unsigned> callee = OperandPosition::callee(call.opcode);
if (!callee || !call.operand(*callee))
return { };
ExpectedType expected = function.at(call.operand(*callee)).expected();
if (!expected)
return { };
std::span<const FunctionID> functions = program.at(expected.predicted()).functions.span();
return functions.size() > maxFunctionsOfStoredValue ? std::span<const FunctionID>() : functions;
}
static std::span<const FunctionID> expectedCalleesOf(const Program&, const Function&, const Terminator&) { return { }; }
enum class EnteredAsValueBy : uint8_t { Nothing, Calls, Constructions };
static EnteredAsValueBy whatEntersAsValue(const Function& function)
{
switch (function.kind) {
case FunctionKind::Plain:
case FunctionKind::Arrow:
case FunctionKind::Method:
return EnteredAsValueBy::Calls;
case FunctionKind::BaseConstructor:
case FunctionKind::DerivedConstructor:
return EnteredAsValueBy::Constructions;
case FunctionKind::Getter:
case FunctionKind::Setter:
case FunctionKind::Initializer:
case FunctionKind::Module:
case FunctionKind::CommonJsModule:
return EnteredAsValueBy::Nothing;
}
RELEASE_ASSERT_NOT_REACHED();
}
namespace {
struct SeenCode {
BitVector isReached;
BitVector mayBeCalledAsValue;
BitVector hasSiteThatMayEnter;
BitVector isAccessorReachedUnderItsName;
bool reachesEverything { false };
bool seesWhatRuns { false };
bool reaches(FunctionID function) const { return reachesEverything || isReached.get(function.index()); }
bool mayEnter(FunctionID function) const { return !seesWhatRuns || hasSiteThatMayEnter.get(function.index()); }
};
} // anonymous namespace
// The record of a module that only compiled code evaluates has no body.
static bool isModuleBodyFunction(const Function& function) { return function.module && function.isModuleBody(); }
// A module is loaded by the entry, or by a module that names it. A closure is made by a body that runs. A call of a callee that nobody knows reaches what has been made and may stand there.
static SeenCode findWhatSeenCodeReaches(const Program& program, const CallGraph& callGraph, const FlowResults& flow, const HeatGraph& graph, const ParallelArray<CallsOfNode>& calls, const FunctionsUnderNames& names, const Vector<Vector<FunctionID>>& functionsMadeBy, const BitVector& isCalledByHost, const BitVector& hasOnlySeenCallers, const Vector<Vector<uint32_t>>& namesReadBy, const Vector<Vector<FunctionID>>& accessorsReachedFrom, const Vector<Vector<uint32_t>>& holdersReadBy, const Vector<Vector<ModuleID>>& modulesLoadedBy, const Vector<uint8_t>& constructsUnknownValue, EstimateOf estimate)
{
unsigned count = graph.numberOfFunctions();
bool isForClasses = estimate == EstimateOf::Classes;
SeenCode seen;
seen.isAccessorReachedUnderItsName = BitVector(count);
BitVector& isReached = seen.isReached;
isReached.ensureSize(calls.size());
Vector<FunctionID> entrypointOf(count);
BitVector isEntrypoint(count);
if (isForClasses) {
for (unsigned index = 0; index < count; ++index) {
const Function& function = program.functions[index];
if (function.role != FunctionRole::GenericEntrypoint || !function.hasBody())
continue;
if (const auto* record = function.creator.tryAs<CreatorRecord::Entrypoint>()) {
entrypointOf[record->target.index()] = FunctionID(index);
isEntrypoint.quickSet(index);
}
}
}
BitVector isMade(count);
BitVector isAwaited(count);
BitVector isReadAsValue(names.size() + 1);
BitVector isReadUnderUnknownKey(names.numberOfHolders());
BitVector hasMaker(count);
for (const Vector<FunctionID>& made : functionsMadeBy) {
for (FunctionID function : made)
hasMaker.quickSet(function.index());
}
Vector<uint32_t> worklist;
auto reach = [&](uint32_t node) {
if (!isReached.quickSet(node))
worklist.append(node);
};
BitVector isLoaded(program.modules.size());
BitVector hasCode(program.modules.size());
for (unsigned index = 0; index < count; ++index) {
if (program.functions[index].hasBody() && isModuleBodyFunction(program.functions[index]))
hasCode.quickSet(program.functions[index].module.index());
}
auto moduleIsLoaded = [&](FunctionID function) {
ModuleID module = program.at(function).module;
return !module || !hasCode.quickGet(module.index()) || isLoaded.quickGet(module.index());
};
auto exists = [&](FunctionID function) {
return hasMaker.quickGet(function.index()) ? isMade.quickGet(function.index()) : moduleIsLoaded(function);
};
auto isBodyOfModule = [&](FunctionID function) {
return isModuleBodyFunction(program.at(function));
};
// Text that the application makes at run time names what the application has made.
bool evaluatesText = false;
BitVector evaluatesTextIn(count);
if (flow.hasResults()) {
for (const UnseenCodeRecord& record : flow.unseenCode()) {
if (record.cause == UnseenCodeCause::EvaluatesText && record.witness.function < count)
evaluatesTextIn.quickSet(record.witness.function);
}
}
BitVector isStartedByHost(count);
for (FunctionID root : callGraph.roots()) {
if ((!isForClasses || isCalledByHost.get(root.index())) && !isEntrypoint.quickGet(root.index()) && program.at(root).hasBody() && !isBodyOfModule(root))
isStartedByHost.quickSet(root.index());
}
BitVector hasEscaped(count);
for (FunctionID function : callGraph.functionsCalledByUnknownCode()) {
if (!isBodyOfModule(function) && !hasOnlySeenCallers.get(function.index()) && !isEntrypoint.quickGet(function.index()))
hasEscaped.quickSet(function.index());
}
BitVector isUnderNameThatIsCalled(count);
BitVector isUnderNameReadAsValue(count);
auto mayStandWhereValueIsCalled = [&](FunctionID function) {
return hasEscaped.quickGet(function.index()) && (!names.isUnderSomeName(function) || isUnderNameReadAsValue.quickGet(function.index()) || seen.isAccessorReachedUnderItsName.quickGet(function.index()) || (evaluatesText && !isLibraryCode(program, program.at(function))));
};
bool constructsValue = false;
Vector<Vector<FunctionID>> functionsWaitingFor(program.modules.size());
BitVector isWaiting(count);
auto reachIfCalled = [&](FunctionID function) {
if (isReached.quickGet(function.index()))
return;
if (!isStartedByHost.quickGet(function.index()) && !isUnderNameThatIsCalled.quickGet(function.index()) && !(isReached.quickGet(graph.unknownCodeNode().index()) && mayStandWhereValueIsCalled(function)))
return;
if (exists(function))
reach(function.index());
else if (!hasMaker.quickGet(function.index()) && !isWaiting.quickSet(function.index()))
functionsWaitingFor[program.at(function).module.index()].append(function);
};
Vector<ModuleID> modulesToLoad;
auto load = [&](ModuleID first) {
modulesToLoad.append(first);
while (!modulesToLoad.isEmpty()) {
ModuleID module = modulesToLoad.takeLast();
if (isLoaded.quickSet(module.index()))
continue;
if (FunctionID body = program.at(module).body)
reach(body.index());
for (const ModuleRequest& request : program.at(module).requests)
modulesToLoad.append(request.target);
for (FunctionID waiting : std::exchange(functionsWaitingFor[module.index()], { }))
reachIfCalled(waiting);
}
};
for (const Entry& entry : program.entries)
load(entry.module);
if (program.entries.isEmpty()) {
// Nothing says where such a program starts.
for (unsigned index = 0; index < count; ++index) {
if (program.functions[index].hasBody()) {
reach(index);
isMade.quickSet(index);
}
}
}
for (size_t root : isStartedByHost)
reachIfCalled(FunctionID(root));
auto followCallsOf = [&](uint32_t node) {
for (const WeightedCall& call : calls[node]) {
if (isForClasses && call.node < count && hasMaker.quickGet(call.node) && !isMade.quickGet(call.node)) {
isAwaited.quickSet(call.node);
continue;
}
reach(call.node);
}
};
while (!worklist.isEmpty()) {
uint32_t node = worklist.takeLast();
if (node >= graph.numNodes()) {
followCallsOf(node);
continue;
}
if (node == graph.unknownCodeNode().index()) {
for (size_t function : hasEscaped)
reachIfCalled(FunctionID(function));
continue;
}
if (node >= count) {
for (FunctionID function : names.at(node - graph.nodeOfName(0).index())) {
if (hasOnlySeenCallers.get(function.index()))
continue;
isUnderNameThatIsCalled.quickSet(function.index());
reachIfCalled(function);
}
continue;
}
FunctionID function(node);
constructsValue |= !!constructsUnknownValue[node];
for (ModuleID module : modulesLoadedBy[node])
load(module);
if (FunctionID entrypoint = entrypointOf[node])
reach(entrypoint.index());
for (FunctionID made : functionsMadeBy[node]) {
if (isMade.quickSet(made.index()))
continue;
if (isAwaited.quickGet(made.index()))
reach(made.index());
else
reachIfCalled(made);
}
for (uint32_t position : namesReadBy[node]) {
if (isReadAsValue.quickSet(position))
continue;
for (FunctionID read : names.at(position)) {
isUnderNameReadAsValue.quickSet(read.index());
reachIfCalled(read);
}
}
for (FunctionID accessor : accessorsReachedFrom[node]) {
if (hasOnlySeenCallers.get(accessor.index()) || seen.isAccessorReachedUnderItsName.quickSet(accessor.index()))
continue;
isUnderNameThatIsCalled.quickSet(accessor.index());
reachIfCalled(accessor);
}
for (uint32_t holder : holdersReadBy[node]) {
if (isReadUnderUnknownKey.quickSet(holder))
continue;
for (FunctionID read : names.inHolder(holder)) {
isUnderNameReadAsValue.quickSet(read.index());
reachIfCalled(read);
}
}
followCallsOf(node);
if (isBodyOfModule(function))
load(program.at(function).module);
if (FunctionID functionAsRead = findFunctionAsRead(&program, function)) {
for (const FlowIndirectCall& call : flow.indirectCallsFrom(functionAsRead)) {
if (program.at(call.callee).hasBody())
reach(call.callee.index());
}
}
if (evaluatesTextIn.quickGet(node) && !evaluatesText) {
evaluatesText = true;
reach(graph.unknownCodeNode().index());
for (size_t escaped : hasEscaped)
reachIfCalled(FunctionID(escaped));
}
}
seen.mayBeCalledAsValue = BitVector(count);
seen.hasSiteThatMayEnter = WTF::move(isUnderNameThatIsCalled);
bool callsValue = isReached.quickGet(graph.unknownCodeNode().index());
seen.seesWhatRuns = flow.hasResults() && !program.entries.isEmpty();
for (size_t function : hasEscaped) {
if (!isReached.quickGet(function) || !mayStandWhereValueIsCalled(FunctionID(function)))
continue;
seen.mayBeCalledAsValue.quickSet(function);
EnteredAsValueBy enteredBy = whatEntersAsValue(program.functions[function]);
if ((enteredBy == EnteredAsValueBy::Calls && callsValue) || (enteredBy == EnteredAsValueBy::Constructions && constructsValue))
seen.hasSiteThatMayEnter.quickSet(function);
}
return seen;
}
// How surely each node is reached: along the surest path from the entries, the product of the weights of its calls, none over 1. A call of a name, or of a value, enters one of the functions that may stand there.
static Vector<double> estimateHowSurelyNodesAreReached(const Program& program, const FlowResults& flow, const HeatGraph& graph, const ParallelArray<CallsOfNode>& calls, const FunctionsUnderNames& names, const SeenCode& seen, const BitVector& hasOnlySeenCallers, const Vector<Vector<ModuleID>>& modulesLoadedBy)
{
unsigned count = graph.numberOfFunctions();
Vector<double> sureness(FillWith { }, calls.size(), 0.0);
Vector<std::pair<double, uint32_t>> heap;
auto enter = [&](uint32_t node, double howSurely) {
if (howSurely <= sureness[node] || (node < count && !seen.reaches(FunctionID(node))))
return;
sureness[node] = howSurely;
heap.append({ howSurely, node });
std::ranges::push_heap(heap);
};
Vector<double> surenessOfModules(FillWith { }, program.modules.size(), 0.0);
Vector<ModuleID> modulesToLoad;
auto load = [&](ModuleID first, double howSurely) {
modulesToLoad.append(first);
while (!modulesToLoad.isEmpty()) {
ModuleID module = modulesToLoad.takeLast();
if (howSurely <= surenessOfModules[module.index()])
continue;
surenessOfModules[module.index()] = howSurely;
if (FunctionID body = program.at(module).body)
enter(body.index(), howSurely);
for (const ModuleRequest& request : program.at(module).requests)
modulesToLoad.append(request.target);
}
};
Vector<FunctionID> entrypointOf(count);
for (unsigned index = 0; index < count; ++index) {
const Function& function = program.functions[index];
if (function.role != FunctionRole::GenericEntrypoint || !function.hasBody())
continue;
if (const auto* record = function.creator.tryAs<CreatorRecord::Entrypoint>())
entrypointOf[record->target.index()] = FunctionID(index);
}
for (const Entry& entry : program.entries)
load(entry.module, 1);
while (!heap.isEmpty()) {
std::ranges::pop_heap(heap);
auto [howSurely, node] = heap.takeLast();
if (howSurely < sureness[node])
continue;
if (node == graph.hostNode().index())
continue;
if (node >= graph.numNodes()) {
for (const WeightedCall& call : calls[node])
enter(call.node, howSurely);
continue;
}
if (node == graph.unknownCodeNode().index()) {
double share = howSurely / std::max<size_t>(seen.mayBeCalledAsValue.bitCount(), 1);
for (size_t function : seen.mayBeCalledAsValue)
enter(function, share);
continue;
}
if (node >= count) {
std::span<const FunctionID> functions = names.at(node - graph.nodeOfName(0).index());
size_t numberThatMayStandThere = std::ranges::count_if(functions, [&](FunctionID function) {
return seen.reaches(function) && !hasOnlySeenCallers.get(function.index());
});
for (FunctionID function : functions) {
if (!hasOnlySeenCallers.get(function.index()))
enter(function.index(), howSurely / std::max<size_t>(numberThatMayStandThere, 1));
}
continue;
}
FunctionID function(node);
if (FunctionID entrypoint = entrypointOf[node])
enter(entrypoint.index(), howSurely);
for (ModuleID module : modulesLoadedBy[node])
load(module, howSurely);
if (isModuleBodyFunction(program.at(function)))
load(program.at(function).module, howSurely);
for (const WeightedCall& call : calls[node])
enter(call.node, howSurely * std::min(call.weight, 1.0));
if (FunctionID functionAsRead = findFunctionAsRead(&program, function)) {
for (const FlowIndirectCall& call : flow.indirectCallsFrom(functionAsRead)) {
if (program.at(call.callee).hasBody())
enter(call.callee.index(), howSurely);
}
}
}
return sureness;
}
// How often a function is entered because an event came. The host enters a handler once per event. A call hands that on as surely as its block is reached where an even branch counts as taken.
// Where only the name of the callee is known, or nothing, each function that may stand there is entered as often. What is entered so hands that on through calls of known callees, and under a name to the library's functions alone.
// A value that is called is one of the application's functions: the library calls its own under their names.
static Vector<double> estimateEntriesPerEvent(const Program& program, const HeatGraph& graph, const ParallelArray<CallsOfNode>& calls, const FunctionsUnderNames& names, const BitVector& isCalledPerEvent, const SeenCode& seen, const BitVector& hasOnlySeenCallers, const Vector<double>& eventsOfHandlers)
{
unsigned count = graph.numberOfFunctions();
Vector<double> entries(FillWith { }, calls.size(), 0.0);
Vector<uint8_t> isReachedByKnownCalls(FillWith { }, calls.size(), static_cast<uint8_t>(0));
Vector<std::pair<double, uint32_t>> heap;
auto enter = [&](uint32_t node, double times, bool byKnownCalls) {
if (times < 1 || times < entries[node] || (times == entries[node] && byKnownCalls <= !!isReachedByKnownCalls[node]))
return;
entries[node] = times;
isReachedByKnownCalls[node] = byKnownCalls;
heap.append({ times, node });
std::ranges::push_heap(heap);
};
for (size_t handler : isCalledPerEvent) {
if (seen.reaches(FunctionID(handler)))
enter(handler, eventsOfHandlers[handler], true);
}
while (!heap.isEmpty()) {
std::ranges::pop_heap(heap);
auto [times, node] = heap.takeLast();
if (times < entries[node] || node == graph.hostNode().index())
continue;
if (node < count || node >= graph.numNodes()) {
for (const WeightedCall& call : calls[node])
enter(call.node, times * call.share, isReachedByKnownCalls[node]);
continue;
}
if (node == graph.unknownCodeNode().index()) {
if (!isReachedByKnownCalls[node])
continue;
for (size_t function : seen.mayBeCalledAsValue) {
if (!isLibraryCode(program, program.functions[function]))
enter(function, times, false);
}
continue;
}
for (FunctionID function : names.at(node - graph.nodeOfName(0).index())) {
if (seen.reaches(function) && !hasOnlySeenCallers.get(function.index()) && (isReachedByKnownCalls[node] || isLibraryCode(program, program.at(function))))
enter(function.index(), times, false);
}
}
return entries;
}
static WeightedCallList collectHostCalls(const Program& program, const CallGraph& callGraph, const FlowResults& flow, const HeatGraph& graph, const ParallelArray<CallsOfNode>& callsOfProgram, const BitVector& isCalledPerEvent, const Vector<uint8_t>& isCountedByProgram, const SeenCode& seen, const ParallelLoops& loops, EstimateOf estimate, const BitVector& hasOnlySeenCallers, const Vector<double>& entriesPerEvent, const Vector<double>& eventsOfHandlers)
{
Vector<FunctionID> callees;
callees.append(callGraph.roots());
callees.append(callGraph.functionsCalledByUnknownCode());
for (size_t index : isCalledPerEvent)
callees.append(FunctionID(index));
for (size_t index : seen.isAccessorReachedUnderItsName)
callees.append(FunctionID(index));
sortAndRemoveDuplicates(loops, callees);
auto comesWithEvents = [&](FunctionID callee) {
return !entriesPerEvent.isEmpty() && entriesPerEvent[callee.index()] >= 1 && callGraph.callerSet(callee) != CallerSet::Complete;
};
auto callOf = [&](FunctionID callee) {
if (isCalledPerEvent.get(callee.index()))
return WeightedCall { graph.nodeOf(callee).index(), eventsOfHandlers[callee.index()] };
bool runsAsLoopDoes = estimate == EstimateOf::Classes && callGraph.callerSet(callee) != CallerSet::Complete && seen.mayEnter(callee) && !flow.runsAtMostOnce(program, callee);
return WeightedCall { graph.nodeOf(callee).index(), std::max(runsAsLoopDoes ? frequencyConstants.iterationsPerLoop : 1.0, comesWithEvents(callee) ? entriesPerEvent[callee.index()] : 0.0) };
};
struct HostCallee {
FunctionID function;
std::optional<WeightedCall> call;
};
Vector<HostCallee> calleesWithBody = collectInParallel<HostCallee>(loops, callees.size(), [&](unsigned position, Vector<HostCallee>& found) {
FunctionID callee = callees[position];
if (!program.at(callee).hasBody() || !seen.reaches(callee) || hasOnlySeenCallers.get(callee.index()))
return;
if (isCountedByProgram[callee.index()] && !comesWithEvents(callee))
found.append({ callee, std::nullopt });
else
found.append({ callee, callOf(callee) });
});
WeightedCallList calls;
calls.reserveInitialCapacity(calleesWithBody.size());
Vector<FunctionID> calleesCountedByProgram;
for (const HostCallee& callee : calleesWithBody) {
if (callee.call)
calls.append(*callee.call);
else
calleesCountedByProgram.append(callee.function);
}
if (calleesCountedByProgram.isEmpty())
return calls;
Vector<uint8_t> isReached(FillWith { }, callsOfProgram.size(), static_cast<uint8_t>(0));
auto reach = [&](uint32_t node) {
return !AtomicRef(isReached[node]).load(std::memory_order_relaxed) && !AtomicRef(isReached[node]).exchange(1, std::memory_order_relaxed);
};
auto visitCalleesOf = [&](uint32_t node, Vector<uint32_t>& found) {
for (const WeightedCall& call : callsOfProgram[node]) {
if (reach(call.node))
found.append(call.node);
}
};
// The set of reachable nodes does not depend on the visit order.
AOT_THRESHOLD(size_t, minNodesForThreadPool, 512);
Vector<uint32_t> worklist;
auto drainWorklist = [&] {
while (!worklist.isEmpty()) {
if (worklist.size() < minNodesForThreadPool) {
visitCalleesOf(worklist.takeLast(), worklist);
continue;
}
worklist = collectInParallel<uint32_t>(loops, worklist.size(), [&](unsigned position, Vector<uint32_t>& found) {
visitCalleesOf(worklist[position], found);
});
}
};
for (const WeightedCall& call : calls) {
if (reach(call.node))
worklist.append(call.node);
}
drainWorklist();
size_t numberOfSortedCalls = calls.size();
for (FunctionID callee : calleesCountedByProgram) {
if (!reach(graph.nodeOf(callee).index()))
continue;
calls.append(callOf(callee));
worklist.append(graph.nodeOf(callee).index());
drainWorklist();
}
if (calls.size() > numberOfSortedCalls)
AOT::sortInLine(calls, { }, &WeightedCall::node);
return calls;
}
static WeightedCallList shareAmong(const Program& program, const FlowResults& flow, const HeatGraph& graph, const BitVector& isCalledPerEvent, const SeenCode& seen, std::span<const FunctionID> callees)
{
WeightedCallList calls;
for (FunctionID callee : callees) {
if (!flow.runsAtMostOnce(program, callee) && !isCalledPerEvent.get(callee.index()) && seen.reaches(callee))
calls.append(WeightedCall { graph.nodeOf(callee).index(), 1.0 });
}
for (WeightedCall& call : calls)
call.weight /= calls.size();
return calls;
}
void BodyWeights::didChange(std::span<const FunctionID> functions)
{
for (FunctionID id : functions) {
if (id.index() < m_blocks.size())
m_blocks[id.index()].clear();
}
}
HeatGraph buildHeatGraph(const Program& program, const CallGraph& callGraph, const FlowResults& flow, const EffectSummaries& effects, BuildContext& build, const BodyReferences* references, const BodyWeights* keptWeights, BodyWeights* madeWeights, HeatGraph* graphOfClasses)
{
const ParallelLoops& loops = build.parallelLoops();
unsigned count = program.functions.size();
RELEASE_ASSERT(!references || references->size() == count);
RELEASE_ASSERT(!keptWeights || keptWeights->m_blocks.size() <= count);
if (madeWeights) {
RELEASE_ASSERT(madeWeights->m_blocks.isEmpty());
madeWeights->m_blocks.grow(count);
}