-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
CodeBlock.cpp
3569 lines (3064 loc) · 135 KB
/
CodeBlock.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
/*
* Copyright (C) 2008-2020 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "CodeBlock.h"
#include "ArithProfile.h"
#include "BasicBlockLocation.h"
#include "ByValInfo.h"
#include "BytecodeDumper.h"
#include "BytecodeLivenessAnalysisInlines.h"
#include "BytecodeOperandsForCheckpoint.h"
#include "BytecodeStructs.h"
#include "CodeBlockInlines.h"
#include "CodeBlockSet.h"
#include "ControlFlowProfiler.h"
#include "DFGCapabilities.h"
#include "DFGCommon.h"
#include "DFGJITCode.h"
#include "DFGWorklist.h"
#include "EvalCodeBlock.h"
#include "FullCodeOrigin.h"
#include "FunctionCodeBlock.h"
#include "FunctionExecutableDump.h"
#include "GetPutInfo.h"
#include "InlineCallFrame.h"
#include "Instruction.h"
#include "InstructionStream.h"
#include "IsoCellSetInlines.h"
#include "JIT.h"
#include "JITMathIC.h"
#include "JSCInlines.h"
#include "JSCJSValue.h"
#include "JSLexicalEnvironment.h"
#include "JSModuleEnvironment.h"
#include "JSSet.h"
#include "JSString.h"
#include "JSTemplateObjectDescriptor.h"
#include "LLIntData.h"
#include "LLIntEntrypoint.h"
#include "LLIntExceptions.h"
#include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
#include "MetadataTable.h"
#include "ModuleProgramCodeBlock.h"
#include "ObjectAllocationProfileInlines.h"
#include "PCToCodeOriginMap.h"
#include "ProfilerDatabase.h"
#include "ProgramCodeBlock.h"
#include "ReduceWhitespace.h"
#include "SlotVisitorInlines.h"
#include "StackVisitor.h"
#include "StructureStubInfo.h"
#include "TypeLocationCache.h"
#include "TypeProfiler.h"
#include "VMInlines.h"
#include <wtf/Forward.h>
#include <wtf/SimpleStats.h>
#include <wtf/StringPrintStream.h>
#include <wtf/text/UniquedStringImpl.h>
#if ENABLE(ASSEMBLER)
#include "RegisterAtOffsetList.h"
#endif
#if ENABLE(FTL_JIT)
#include "FTLJITCode.h"
#endif
namespace JSC {
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(CodeBlockRareData);
const ClassInfo CodeBlock::s_info = {
"CodeBlock", nullptr, nullptr, nullptr,
CREATE_METHOD_TABLE(CodeBlock)
};
CString CodeBlock::inferredName() const
{
switch (codeType()) {
case GlobalCode:
return "<global>";
case EvalCode:
return "<eval>";
case FunctionCode:
return jsCast<FunctionExecutable*>(ownerExecutable())->ecmaName().utf8();
case ModuleCode:
return "<module>";
default:
CRASH();
return CString("", 0);
}
}
bool CodeBlock::hasHash() const
{
return !!m_hash;
}
bool CodeBlock::isSafeToComputeHash() const
{
return !isCompilationThread();
}
CodeBlockHash CodeBlock::hash() const
{
if (!m_hash) {
RELEASE_ASSERT(isSafeToComputeHash());
m_hash = CodeBlockHash(ownerExecutable()->source(), specializationKind());
}
return m_hash;
}
CString CodeBlock::sourceCodeForTools() const
{
if (codeType() != FunctionCode)
return ownerExecutable()->source().toUTF8();
SourceProvider* provider = source().provider();
FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
unsigned unlinkedStartOffset = unlinked->startOffset();
unsigned linkedStartOffset = executable->source().startOffset();
int delta = linkedStartOffset - unlinkedStartOffset;
unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
return toCString(
"function ",
provider->source().substring(rangeStart, rangeEnd - rangeStart).utf8());
}
CString CodeBlock::sourceCodeOnOneLine() const
{
return reduceWhitespace(sourceCodeForTools());
}
CString CodeBlock::hashAsStringIfPossible() const
{
if (hasHash() || isSafeToComputeHash())
return toCString(hash());
return "<no-hash>";
}
void CodeBlock::dumpAssumingJITType(PrintStream& out, JITType jitType) const
{
out.print(inferredName(), "#", hashAsStringIfPossible());
out.print(":[", RawPointer(this), "->");
if (!!m_alternative)
out.print(RawPointer(alternative()), "->");
out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
if (codeType() == FunctionCode)
out.print(specializationKind());
out.print(", ", instructionsSize());
if (this->jitType() == JITType::BaselineJIT && m_shouldAlwaysBeInlined)
out.print(" (ShouldAlwaysBeInlined)");
if (ownerExecutable()->neverInline())
out.print(" (NeverInline)");
if (ownerExecutable()->neverOptimize())
out.print(" (NeverOptimize)");
else if (ownerExecutable()->neverFTLOptimize())
out.print(" (NeverFTLOptimize)");
if (ownerExecutable()->didTryToEnterInLoop())
out.print(" (DidTryToEnterInLoop)");
if (ownerExecutable()->isInStrictContext())
out.print(" (StrictMode)");
if (m_didFailJITCompilation)
out.print(" (JITFail)");
if (this->jitType() == JITType::BaselineJIT && m_didFailFTLCompilation)
out.print(" (FTLFail)");
if (this->jitType() == JITType::BaselineJIT && m_hasBeenCompiledWithFTL)
out.print(" (HadFTLReplacement)");
out.print("]");
}
void CodeBlock::dump(PrintStream& out) const
{
dumpAssumingJITType(out, jitType());
}
void CodeBlock::dumpSource()
{
dumpSource(WTF::dataFile());
}
void CodeBlock::dumpSource(PrintStream& out)
{
ScriptExecutable* executable = ownerExecutable();
if (executable->isFunctionExecutable()) {
FunctionExecutable* functionExecutable = reinterpret_cast<FunctionExecutable*>(executable);
StringView source = functionExecutable->source().provider()->getRange(
functionExecutable->parametersStartOffset(),
functionExecutable->typeProfilingEndOffset(vm()) + 1); // Type profiling end offset is the character before the '}'.
out.print("function ", inferredName(), source);
return;
}
out.print(executable->source().view());
}
void CodeBlock::dumpBytecode()
{
dumpBytecode(WTF::dataFile());
}
void CodeBlock::dumpBytecode(PrintStream& out)
{
ICStatusMap statusMap;
getICStatusMap(statusMap);
BytecodeGraph graph(this, this->instructions());
CodeBlockBytecodeDumper<CodeBlock>::dumpGraph(this, instructions(), graph, out, statusMap);
}
void CodeBlock::dumpBytecode(PrintStream& out, const InstructionStream::Ref& it, const ICStatusMap& statusMap)
{
BytecodeDumper<CodeBlock>::dumpBytecode(this, out, it, statusMap);
}
void CodeBlock::dumpBytecode(PrintStream& out, unsigned bytecodeOffset, const ICStatusMap& statusMap)
{
const auto it = instructions().at(bytecodeOffset);
dumpBytecode(out, it, statusMap);
}
namespace {
class PutToScopeFireDetail final : public FireDetail {
public:
PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
: m_codeBlock(codeBlock)
, m_ident(ident)
{
}
void dump(PrintStream& out) const final
{
out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
}
private:
CodeBlock* m_codeBlock;
const Identifier& m_ident;
};
} // anonymous namespace
CodeBlock::CodeBlock(VM& vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
: JSCell(vm, structure)
, m_globalObject(other.m_globalObject)
, m_shouldAlwaysBeInlined(true)
#if ENABLE(JIT)
, m_capabilityLevelState(DFG::CapabilityLevelNotSet)
#endif
, m_didFailJITCompilation(false)
, m_didFailFTLCompilation(false)
, m_hasBeenCompiledWithFTL(false)
, m_hasLinkedOSRExit(false)
, m_isEligibleForLLIntDowngrade(false)
, m_numCalleeLocals(other.m_numCalleeLocals)
, m_numVars(other.m_numVars)
, m_numberOfArgumentsToSkip(other.m_numberOfArgumentsToSkip)
, m_hasDebuggerStatement(false)
, m_steppingMode(SteppingModeDisabled)
, m_numBreakpoints(0)
, m_bytecodeCost(other.m_bytecodeCost)
, m_scopeRegister(other.m_scopeRegister)
, m_hash(other.m_hash)
, m_unlinkedCode(other.vm(), this, other.m_unlinkedCode.get())
, m_ownerExecutable(other.vm(), this, other.m_ownerExecutable.get())
, m_vm(other.m_vm)
, m_instructionsRawPointer(other.m_instructionsRawPointer)
, m_constantRegisters(other.m_constantRegisters)
, m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
, m_functionDecls(other.m_functionDecls)
, m_functionExprs(other.m_functionExprs)
, m_osrExitCounter(0)
, m_optimizationDelayCounter(0)
, m_reoptimizationRetryCounter(0)
, m_metadata(other.m_metadata)
, m_creationTime(MonotonicTime::now())
{
ASSERT(heap()->isDeferred());
ASSERT(m_scopeRegister.isLocal());
ASSERT(source().provider());
setNumParameters(other.numParameters());
vm.heap.codeBlockSet().add(this);
}
void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
{
Base::finishCreation(vm);
finishCreationCommon(vm);
optimizeAfterWarmUp();
jitAfterWarmUp();
if (other.m_rareData) {
createRareDataIfNecessary();
m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
}
}
CodeBlock::CodeBlock(VM& vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope)
: JSCell(vm, structure)
, m_globalObject(vm, this, scope->globalObject(vm))
, m_shouldAlwaysBeInlined(true)
#if ENABLE(JIT)
, m_capabilityLevelState(DFG::CapabilityLevelNotSet)
#endif
, m_didFailJITCompilation(false)
, m_didFailFTLCompilation(false)
, m_hasBeenCompiledWithFTL(false)
, m_hasLinkedOSRExit(false)
, m_isEligibleForLLIntDowngrade(false)
, m_numCalleeLocals(unlinkedCodeBlock->numCalleeLocals())
, m_numVars(unlinkedCodeBlock->numVars())
, m_hasDebuggerStatement(false)
, m_steppingMode(SteppingModeDisabled)
, m_numBreakpoints(0)
, m_scopeRegister(unlinkedCodeBlock->scopeRegister())
, m_unlinkedCode(vm, this, unlinkedCodeBlock)
, m_ownerExecutable(vm, this, ownerExecutable)
, m_vm(&vm)
, m_instructionsRawPointer(unlinkedCodeBlock->instructions().rawPointer())
, m_osrExitCounter(0)
, m_optimizationDelayCounter(0)
, m_reoptimizationRetryCounter(0)
, m_metadata(unlinkedCodeBlock->metadata().link())
, m_creationTime(MonotonicTime::now())
{
ASSERT(heap()->isDeferred());
ASSERT(m_scopeRegister.isLocal());
ASSERT(source().provider());
setNumParameters(unlinkedCodeBlock->numParameters());
vm.heap.codeBlockSet().add(this);
}
// The main purpose of this function is to generate linked bytecode from unlinked bytecode. The process
// of linking is taking an abstract representation of bytecode and tying it to a GlobalObject and scope
// chain. For example, this process allows us to cache the depth of lexical environment reads that reach
// outside of this CodeBlock's compilation unit. It also allows us to generate particular constants that
// we can't generate during unlinked bytecode generation. This process is not allowed to generate control
// flow or introduce new locals. The reason for this is we rely on liveness analysis to be the same for
// all the CodeBlocks of an UnlinkedCodeBlock. We rely on this fact by caching the liveness analysis
// inside UnlinkedCodeBlock.
bool CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
JSScope* scope)
{
Base::finishCreation(vm);
finishCreationCommon(vm);
auto throwScope = DECLARE_THROW_SCOPE(vm);
if (m_unlinkedCode->wasCompiledWithTypeProfilerOpcodes() || m_unlinkedCode->wasCompiledWithControlFlowProfilerOpcodes())
vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(vm), ownerExecutable->typeProfilingEndOffset(vm));
ScriptExecutable* topLevelExecutable = ownerExecutable->topLevelExecutable();
setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation(), topLevelExecutable);
RETURN_IF_EXCEPTION(throwScope, false);
// We already have the cloned symbol table for the module environment since we need to instantiate
// the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(vm, unlinkedCodeBlock)) {
SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
if (m_unlinkedCode->wasCompiledWithTypeProfilerOpcodes()) {
ConcurrentJSLocker locker(clonedSymbolTable->m_lock);
clonedSymbolTable->prepareForTypeProfiling(locker);
}
replaceConstant(VirtualRegister(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset()), clonedSymbolTable);
}
bool shouldUpdateFunctionHasExecutedCache = m_unlinkedCode->wasCompiledWithTypeProfilerOpcodes() || m_unlinkedCode->wasCompiledWithControlFlowProfilerOpcodes();
m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
if (shouldUpdateFunctionHasExecutedCache)
vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
m_functionDecls[i].set(vm, this, unlinkedExecutable->link(vm, topLevelExecutable, ownerExecutable->source(), WTF::nullopt, NoIntrinsic, ownerExecutable->isInsideOrdinaryFunction()));
}
m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
if (shouldUpdateFunctionHasExecutedCache)
vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
m_functionExprs[i].set(vm, this, unlinkedExecutable->link(vm, topLevelExecutable, ownerExecutable->source(), WTF::nullopt, NoIntrinsic, ownerExecutable->isInsideOrdinaryFunction()));
}
if (unlinkedCodeBlock->hasRareData()) {
createRareDataIfNecessary();
setConstantIdentifierSetRegisters(vm, unlinkedCodeBlock->constantIdentifierSets());
RETURN_IF_EXCEPTION(throwScope, false);
if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
m_rareData->m_exceptionHandlers.resizeToFit(count);
for (size_t i = 0; i < count; i++) {
const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
#if ENABLE(JIT)
auto& instruction = *instructions().at(unlinkedHandler.target).ptr();
handler.initialize(unlinkedHandler, CodeLocationLabel<ExceptionHandlerPtrTag>(LLInt::handleCatch(instruction.width()).code()));
#else
handler.initialize(unlinkedHandler);
#endif
}
}
if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
m_rareData->m_stringSwitchJumpTables.grow(count);
for (size_t i = 0; i < count; i++) {
UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
for (; ptr != end; ++ptr) {
OffsetLocation offset;
offset.branchOffset = ptr->value.branchOffset;
m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
}
}
}
if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
m_rareData->m_switchJumpTables.grow(count);
for (size_t i = 0; i < count; i++) {
UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
destTable.branchOffsets.resizeToFit(sourceTable.branchOffsets.size());
std::copy(sourceTable.branchOffsets.begin(), sourceTable.branchOffsets.end(), destTable.branchOffsets.begin());
destTable.min = sourceTable.min;
}
}
}
// Bookkeep the strongly referenced module environments.
HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
auto link_profile = [&](const auto& /*instruction*/, auto /*bytecode*/, auto& /*metadata*/) {
m_numberOfNonArgumentValueProfiles++;
};
auto link_objectAllocationProfile = [&](const auto& /*instruction*/, auto bytecode, auto& metadata) {
metadata.m_objectAllocationProfile.initializeProfile(vm, m_globalObject.get(), this, m_globalObject->objectPrototype(), bytecode.m_inlineCapacity);
};
auto link_arrayAllocationProfile = [&](const auto& /*instruction*/, auto bytecode, auto& metadata) {
metadata.m_arrayAllocationProfile.initializeIndexingMode(bytecode.m_recommendedIndexingType);
};
#define LINK_FIELD(__field) \
WTF_LAZY_JOIN(link_, __field)(instruction, bytecode, metadata);
#define INITIALIZE_METADATA(__op) \
auto bytecode = instruction->as<__op>(); \
auto& metadata = bytecode.metadata(this); \
new (&metadata) __op::Metadata { bytecode }; \
#define CASE(__op) case __op::opcodeID
#define LINK(...) \
CASE(WTF_LAZY_FIRST(__VA_ARGS__)): { \
INITIALIZE_METADATA(WTF_LAZY_FIRST(__VA_ARGS__)) \
WTF_LAZY_HAS_REST(__VA_ARGS__)({ \
WTF_LAZY_FOR_EACH_TERM(LINK_FIELD, WTF_LAZY_REST_(__VA_ARGS__)) \
}) \
break; \
}
const InstructionStream& instructionStream = instructions();
for (const auto& instruction : instructionStream) {
OpcodeID opcodeID = instruction->opcodeID();
m_bytecodeCost += opcodeLengths[opcodeID];
switch (opcodeID) {
LINK(OpHasEnumerableIndexedProperty)
LINK(OpCallVarargs, profile)
LINK(OpTailCallVarargs, profile)
LINK(OpTailCallForwardArguments, profile)
LINK(OpConstructVarargs, profile)
LINK(OpGetByVal, profile)
LINK(OpGetPrivateName, profile)
LINK(OpGetDirectPname, profile)
LINK(OpGetByIdWithThis, profile)
LINK(OpTryGetById, profile)
LINK(OpGetByIdDirect, profile)
LINK(OpGetByValWithThis, profile)
LINK(OpGetPrototypeOf, profile)
LINK(OpGetFromArguments, profile)
LINK(OpToNumber, profile)
LINK(OpToNumeric, profile)
LINK(OpToObject, profile)
LINK(OpGetArgument, profile)
LINK(OpGetInternalField, profile)
LINK(OpToThis, profile)
LINK(OpBitand, profile)
LINK(OpBitor, profile)
LINK(OpBitnot, profile)
LINK(OpBitxor, profile)
LINK(OpLshift, profile)
LINK(OpRshift, profile)
LINK(OpGetById, profile)
LINK(OpCall, profile)
LINK(OpTailCall, profile)
LINK(OpCallEval, profile)
LINK(OpConstruct, profile)
LINK(OpInByVal)
LINK(OpPutByVal)
LINK(OpPutByValDirect)
LINK(OpPutPrivateName)
LINK(OpNewArray)
LINK(OpNewArrayWithSize)
LINK(OpNewArrayBuffer, arrayAllocationProfile)
LINK(OpNewObject, objectAllocationProfile)
LINK(OpPutById)
LINK(OpCreateThis)
LINK(OpCreatePromise)
LINK(OpCreateGenerator)
LINK(OpAdd)
LINK(OpMul)
LINK(OpDiv)
LINK(OpSub)
LINK(OpNegate)
LINK(OpInc)
LINK(OpDec)
LINK(OpJneqPtr)
LINK(OpCatch)
LINK(OpProfileControlFlow)
case op_iterator_open: {
INITIALIZE_METADATA(OpIteratorOpen)
m_numberOfNonArgumentValueProfiles += 3;
break;
}
case op_iterator_next: {
INITIALIZE_METADATA(OpIteratorNext)
m_numberOfNonArgumentValueProfiles += 3;
break;
}
case op_resolve_scope: {
INITIALIZE_METADATA(OpResolveScope)
const Identifier& ident = identifier(bytecode.m_var);
RELEASE_ASSERT(bytecode.m_resolveType != LocalClosureVar);
ResolveOp op = JSScope::abstractResolve(m_globalObject.get(), bytecode.m_localScopeDepth, scope, ident, Get, bytecode.m_resolveType, InitializationMode::NotInitialization);
RETURN_IF_EXCEPTION(throwScope, false);
metadata.m_resolveType = op.type;
metadata.m_localScopeDepth = op.depth;
if (op.lexicalEnvironment) {
if (op.type == ModuleVar) {
// Keep the linked module environment strongly referenced.
if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
addConstant(ConcurrentJSLocker(m_lock), op.lexicalEnvironment);
metadata.m_lexicalEnvironment.set(vm, this, op.lexicalEnvironment);
} else
metadata.m_symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
} else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this)) {
metadata.m_constantScope.set(vm, this, constantScope);
if (op.type == GlobalProperty || op.type == GlobalPropertyWithVarInjectionChecks)
metadata.m_globalLexicalBindingEpoch = m_globalObject->globalLexicalBindingEpoch();
} else
metadata.m_globalObject.clear();
break;
}
case op_get_from_scope: {
INITIALIZE_METADATA(OpGetFromScope)
link_profile(instruction, bytecode, metadata);
metadata.m_watchpointSet = nullptr;
ASSERT(!isInitialization(bytecode.m_getPutInfo.initializationMode()));
if (bytecode.m_getPutInfo.resolveType() == LocalClosureVar) {
metadata.m_getPutInfo = GetPutInfo(bytecode.m_getPutInfo.resolveMode(), ClosureVar, bytecode.m_getPutInfo.initializationMode(), bytecode.m_getPutInfo.ecmaMode());
break;
}
const Identifier& ident = identifier(bytecode.m_var);
ResolveOp op = JSScope::abstractResolve(m_globalObject.get(), bytecode.m_localScopeDepth, scope, ident, Get, bytecode.m_getPutInfo.resolveType(), InitializationMode::NotInitialization);
RETURN_IF_EXCEPTION(throwScope, false);
metadata.m_getPutInfo = GetPutInfo(bytecode.m_getPutInfo.resolveMode(), op.type, bytecode.m_getPutInfo.initializationMode(), bytecode.m_getPutInfo.ecmaMode());
if (op.type == ModuleVar)
metadata.m_getPutInfo = GetPutInfo(bytecode.m_getPutInfo.resolveMode(), ClosureVar, bytecode.m_getPutInfo.initializationMode(), bytecode.m_getPutInfo.ecmaMode());
if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
metadata.m_watchpointSet = op.watchpointSet;
else if (op.structure)
metadata.m_structure.set(vm, this, op.structure);
metadata.m_operand = op.operand;
break;
}
case op_put_to_scope: {
INITIALIZE_METADATA(OpPutToScope)
if (bytecode.m_getPutInfo.resolveType() == LocalClosureVar) {
// Only do watching if the property we're putting to is not anonymous.
if (bytecode.m_var != UINT_MAX) {
SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(bytecode.m_symbolTableOrScopeDepth.symbolTable()));
const Identifier& ident = identifier(bytecode.m_var);
ConcurrentJSLocker locker(symbolTable->m_lock);
auto iter = symbolTable->find(locker, ident.impl());
ASSERT(iter != symbolTable->end(locker));
iter->value.prepareToWatch();
metadata.m_watchpointSet = iter->value.watchpointSet();
} else
metadata.m_watchpointSet = nullptr;
break;
}
const Identifier& ident = identifier(bytecode.m_var);
metadata.m_watchpointSet = nullptr;
ResolveOp op = JSScope::abstractResolve(m_globalObject.get(), bytecode.m_symbolTableOrScopeDepth.scopeDepth(), scope, ident, Put, bytecode.m_getPutInfo.resolveType(), bytecode.m_getPutInfo.initializationMode());
RETURN_IF_EXCEPTION(throwScope, false);
metadata.m_getPutInfo = GetPutInfo(bytecode.m_getPutInfo.resolveMode(), op.type, bytecode.m_getPutInfo.initializationMode(), bytecode.m_getPutInfo.ecmaMode());
if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
metadata.m_watchpointSet = op.watchpointSet;
else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
if (op.watchpointSet)
op.watchpointSet->invalidate(vm, PutToScopeFireDetail(this, ident));
} else if (op.structure)
metadata.m_structure.set(vm, this, op.structure);
metadata.m_operand = op.operand;
break;
}
case op_profile_type: {
RELEASE_ASSERT(m_unlinkedCode->wasCompiledWithTypeProfilerOpcodes());
INITIALIZE_METADATA(OpProfileType)
size_t instructionOffset = instruction.offset() + instruction->size() - 1;
unsigned divotStart, divotEnd;
GlobalVariableID globalVariableID = 0;
RefPtr<TypeSet> globalTypeSet;
bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
SymbolTable* symbolTable = nullptr;
switch (bytecode.m_flag) {
case ProfileTypeBytecodeClosureVar: {
const Identifier& ident = identifier(bytecode.m_identifier);
unsigned localScopeDepth = bytecode.m_symbolTableOrScopeDepth.scopeDepth();
// Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
// we're abstractly "read"ing from a JSScope.
ResolveOp op = JSScope::abstractResolve(m_globalObject.get(), localScopeDepth, scope, ident, Get, bytecode.m_resolveType, InitializationMode::NotInitialization);
RETURN_IF_EXCEPTION(throwScope, false);
if (op.type == ClosureVar || op.type == ModuleVar)
symbolTable = op.lexicalEnvironment->symbolTable();
else if (op.type == GlobalVar)
symbolTable = m_globalObject.get()->symbolTable();
UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
if (symbolTable) {
ConcurrentJSLocker locker(symbolTable->m_lock);
// If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
symbolTable->prepareForTypeProfiling(locker);
globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
} else
globalVariableID = TypeProfilerNoGlobalIDExists;
break;
}
case ProfileTypeBytecodeLocallyResolved: {
SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(bytecode.m_symbolTableOrScopeDepth.symbolTable()));
const Identifier& ident = identifier(bytecode.m_identifier);
ConcurrentJSLocker locker(symbolTable->m_lock);
// If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
break;
}
case ProfileTypeBytecodeDoesNotHaveGlobalID:
case ProfileTypeBytecodeFunctionArgument: {
globalVariableID = TypeProfilerNoGlobalIDExists;
break;
}
case ProfileTypeBytecodeFunctionReturnStatement: {
RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
globalVariableID = TypeProfilerReturnStatement;
if (!shouldAnalyze) {
// Because a return statement can be added implicitly to return undefined at the end of a function,
// and these nodes don't emit expression ranges because they aren't in the actual source text of
// the user's program, give the type profiler some range to identify these return statements.
// Currently, the text offset that is used as identification is "f" in the function keyword
// and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset(vm);
shouldAnalyze = true;
}
break;
}
}
std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
ownerExecutable->sourceID(), divotStart, divotEnd, WTFMove(globalTypeSet), &vm);
TypeLocation* location = locationPair.first;
bool isNewLocation = locationPair.second;
if (bytecode.m_flag == ProfileTypeBytecodeFunctionReturnStatement)
location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset(vm);
if (shouldAnalyze && isNewLocation)
vm.typeProfiler()->insertNewLocation(location);
metadata.m_typeLocation = location;
break;
}
case op_debug: {
if (instruction->as<OpDebug>().m_debugHookType == DidReachDebuggerStatement)
m_hasDebuggerStatement = true;
break;
}
case op_create_rest: {
int numberOfArgumentsToSkip = instruction->as<OpCreateRest>().m_numParametersToSkip;
ASSERT_UNUSED(numberOfArgumentsToSkip, numberOfArgumentsToSkip >= 0);
// This is used when rematerializing the rest parameter during OSR exit in the FTL JIT.");
m_numberOfArgumentsToSkip = numberOfArgumentsToSkip;
break;
}
case op_loop_hint: {
if (UNLIKELY(Options::returnEarlyFromInfiniteLoopsForFuzzing()))
vm.addLoopHintExecutionCounter(instruction.ptr());
break;
}
default:
break;
}
}
#undef CASE
#undef INITIALIZE_METADATA
#undef LINK_FIELD
#undef LINK
if (m_unlinkedCode->wasCompiledWithControlFlowProfilerOpcodes())
insertBasicBlockBoundariesForControlFlowProfiler();
// Set optimization thresholds only after instructions is initialized, since these
// rely on the instruction count (and are in theory permitted to also inspect the
// instruction stream to more accurate assess the cost of tier-up).
optimizeAfterWarmUp();
jitAfterWarmUp();
// If the concurrent thread will want the code block's hash, then compute it here
// synchronously.
if (Options::alwaysComputeHash())
hash();
if (Options::dumpGeneratedBytecodes())
dumpBytecode();
if (m_metadata)
vm.heap.reportExtraMemoryAllocated(m_metadata->sizeInBytes());
return true;
}
void CodeBlock::finishCreationCommon(VM& vm)
{
m_ownerEdge.set(vm, this, ExecutableToCodeBlockEdge::create(vm, this));
}
CodeBlock::~CodeBlock()
{
VM& vm = *m_vm;
// We use unvalidatedGet because get() has a validation assertion that rejects access.
// This assertion is correct since destruction order of cells is not guaranteed, and member cells could already be destroyed.
// But for CodeBlock, we are ensuring the order: CodeBlock gets destroyed before UnlinkedCodeBlock gets destroyed.
// So, we can access member UnlinkedCodeBlock safely here. We bypass the assertion by using unvalidatedGet.
UnlinkedCodeBlock* unlinkedCodeBlock = m_unlinkedCode.unvalidatedGet();
if (UNLIKELY(Options::returnEarlyFromInfiniteLoopsForFuzzing() && JITCode::isBaselineCode(jitType()))) {
for (const auto& instruction : unlinkedCodeBlock->instructions()) {
if (instruction->is<OpLoopHint>())
vm.removeLoopHintExecutionCounter(instruction.ptr());
}
}
#if ENABLE(DFG_JIT)
// The JITCode (and its corresponding DFG::CommonData) may outlive the CodeBlock by
// a short amount of time after the CodeBlock is destructed. For example, the
// Interpreter::execute methods will ref JITCode before invoking it. This can
// result in the JITCode having a non-zero refCount when its owner CodeBlock is
// destructed.
//
// Hence, we cannot rely on DFG::CommonData destruction to clear these now invalid
// watchpoints in a timely manner. We'll ensure they are cleared here eagerly.
//
// We only need to do this for a DFG/FTL CodeBlock because only these will have a
// DFG:CommonData. Hence, the LLInt and Baseline will not have any of these watchpoints.
//
// Note also that the LLIntPrototypeLoadAdaptiveStructureWatchpoint is also related
// to the CodeBlock. However, its lifecycle is tied directly to the CodeBlock, and
// will be automatically cleared when the CodeBlock destructs.
if (JITCode::isOptimizingJIT(jitType()))
jitCode()->dfgCommon()->clearWatchpoints();
#endif
vm.heap.codeBlockSet().remove(this);
if (UNLIKELY(vm.m_perBytecodeProfiler))
vm.m_perBytecodeProfiler->notifyDestruction(this);
if (!vm.heap.isShuttingDown() && unlinkedCodeBlock->didOptimize() == TriState::Indeterminate)
unlinkedCodeBlock->setDidOptimize(TriState::False);
#if ENABLE(VERBOSE_VALUE_PROFILE)
dumpValueProfiles();
#endif
// We may be destroyed before any CodeBlocks that refer to us are destroyed.
// Consider that two CodeBlocks become unreachable at the same time. There
// is no guarantee about the order in which the CodeBlocks are destroyed.
// So, if we don't remove incoming calls, and get destroyed before the
// CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
// destructor will try to remove nodes from our (no longer valid) linked list.
unlinkIncomingCalls();
// Note that our outgoing calls will be removed from other CodeBlocks'
// m_incomingCalls linked lists through the execution of the ~CallLinkInfo
// destructors.
#if ENABLE(JIT)
if (auto* jitData = m_jitData.get()) {
for (StructureStubInfo* stubInfo : jitData->m_stubInfos) {
stubInfo->aboutToDie();
stubInfo->deref();
}
}
#endif // ENABLE(JIT)
}
void CodeBlock::setConstantIdentifierSetRegisters(VM& vm, const RefCountedArray<ConstantIdentifierSetEntry>& constants)
{
auto scope = DECLARE_THROW_SCOPE(vm);
JSGlobalObject* globalObject = m_globalObject.get();
for (const auto& entry : constants) {
const IdentifierSet& set = entry.first;
Structure* setStructure = globalObject->setStructure();
RETURN_IF_EXCEPTION(scope, void());
JSSet* jsSet = JSSet::create(globalObject, vm, setStructure, set.size());
RETURN_IF_EXCEPTION(scope, void());
for (const auto& setEntry : set) {
JSString* jsString = jsOwnedString(vm, setEntry.get());
jsSet->add(globalObject, jsString);
RETURN_IF_EXCEPTION(scope, void());
}
m_constantRegisters[entry.second].set(vm, this, jsSet);
}
}
void CodeBlock::setConstantRegisters(const RefCountedArray<WriteBarrier<Unknown>>& constants, const RefCountedArray<SourceCodeRepresentation>& constantsSourceCodeRepresentation, ScriptExecutable* topLevelExecutable)
{
VM& vm = *m_vm;
auto scope = DECLARE_THROW_SCOPE(vm);
JSGlobalObject* globalObject = m_globalObject.get();
ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
size_t count = constants.size();
{
ConcurrentJSLocker locker(m_lock);
m_constantRegisters.resizeToFit(count);
m_constantsSourceCodeRepresentation.resizeToFit(count);
}
for (size_t i = 0; i < count; i++) {
JSValue constant = constants[i].get();
SourceCodeRepresentation representation = constantsSourceCodeRepresentation[i];
m_constantsSourceCodeRepresentation[i] = representation;
switch (representation) {
case SourceCodeRepresentation::LinkTimeConstant:
constant = globalObject->linkTimeConstant(static_cast<LinkTimeConstant>(constant.asInt32AsAnyInt()));
break;
case SourceCodeRepresentation::Other:
case SourceCodeRepresentation::Integer:
case SourceCodeRepresentation::Double:
if (!constant.isEmpty()) {
if (constant.isCell()) {
JSCell* cell = constant.asCell();
if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(vm, cell)) {
if (m_unlinkedCode->wasCompiledWithTypeProfilerOpcodes()) {
ConcurrentJSLocker locker(symbolTable->m_lock);
symbolTable->prepareForTypeProfiling(locker);
}
SymbolTable* clone = symbolTable->cloneScopePart(vm);
if (wasCompiledWithDebuggingOpcodes())
clone->setRareDataCodeBlock(this);
constant = clone;
} else if (auto* descriptor = jsDynamicCast<JSTemplateObjectDescriptor*>(vm, cell)) {
auto* templateObject = topLevelExecutable->createTemplateObject(globalObject, descriptor);
RETURN_IF_EXCEPTION(scope, void());
constant = templateObject;
}
}
}
break;
}
m_constantRegisters[i].set(vm, this, constant);
}
}
void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
{
RELEASE_ASSERT(alternative);
RELEASE_ASSERT(alternative->jitCode());
m_alternative.set(vm, this, alternative);
}
void CodeBlock::setNumParameters(int newValue)
{
m_numParameters = newValue;
m_argumentValueProfiles = RefCountedArray<ValueProfile>(Options::useJIT() ? newValue : 0);
}
CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
{
#if ENABLE(FTL_JIT)
if (jitType() != JITType::DFGJIT)
return nullptr;
DFG::JITCode* jitCode = m_jitCode->dfg();
return jitCode->osrEntryBlock();
#else // ENABLE(FTL_JIT)
return 0;
#endif // ENABLE(FTL_JIT)
}
size_t CodeBlock::estimatedSize(JSCell* cell, VM& vm)
{
CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
size_t extraMemoryAllocated = 0;
if (thisObject->m_metadata)
extraMemoryAllocated += thisObject->m_metadata->sizeInBytes();
RefPtr<JITCode> jitCode = thisObject->m_jitCode;
if (jitCode && !jitCode->isShared())
extraMemoryAllocated += jitCode->size();
return Base::estimatedSize(cell, vm) + extraMemoryAllocated;
}