| Differences between
and this patch
- Source/JavaScriptCore/API/JSVirtualMachine.mm -2 / +2 lines
Lines 1-5 Source/JavaScriptCore/API/JSVirtualMachine.mm_sec1
1
/*
1
/*
2
 * Copyright (C) 2013, 2015 Apple Inc. All rights reserved.
2
 * Copyright (C) 2013-2016 Apple Inc. All rights reserved.
3
 *
3
 *
4
 * Redistribution and use in source and binary forms, with or without
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
5
 * modification, are permitted provided that the following conditions
Lines 151-157 static id getInternalObjcObject(id objec Source/JavaScriptCore/API/JSVirtualMachine.mm_sec2
151
- (bool)isOldExternalObject:(id)object
151
- (bool)isOldExternalObject:(id)object
152
{
152
{
153
    JSC::VM* vm = toJS(m_group);
153
    JSC::VM* vm = toJS(m_group);
154
    return vm->heap.slotVisitor().containsOpaqueRoot(object);
154
    return vm->heap.collectorSlotVisitor().containsOpaqueRoot(object);
155
}
155
}
156
156
157
- (void)addExternalRememberedObject:(id)object
157
- (void)addExternalRememberedObject:(id)object
- Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj -1 / +4 lines
Lines 613-618 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec1
613
		0FA7A8EB18B413C80052371D /* Reg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FA7A8E918B413C80052371D /* Reg.cpp */; };
613
		0FA7A8EB18B413C80052371D /* Reg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FA7A8E918B413C80052371D /* Reg.cpp */; };
614
		0FA7A8EC18B413C80052371D /* Reg.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FA7A8EA18B413C80052371D /* Reg.h */; settings = {ATTRIBUTES = (Private, ); }; };
614
		0FA7A8EC18B413C80052371D /* Reg.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FA7A8EA18B413C80052371D /* Reg.h */; settings = {ATTRIBUTES = (Private, ); }; };
615
		0FA7A8EE18CE4FD80052371D /* ScratchRegisterAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FA7A8ED18CE4FD80052371D /* ScratchRegisterAllocator.cpp */; };
615
		0FA7A8EE18CE4FD80052371D /* ScratchRegisterAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FA7A8ED18CE4FD80052371D /* ScratchRegisterAllocator.cpp */; };
616
		0FADDD1D1DD01EDE008275E8 /* ResumeTheWorldScope.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FADDD1C1DD01EDC008275E8 /* ResumeTheWorldScope.h */; };
616
		0FADE6731D4D23BE00768457 /* HeapUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FADE6721D4D23BC00768457 /* HeapUtil.h */; };
617
		0FADE6731D4D23BE00768457 /* HeapUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FADE6721D4D23BC00768457 /* HeapUtil.h */; };
617
		0FAF7EFD165BA91B000C8455 /* JITDisassembler.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FAF7EFA165BA919000C8455 /* JITDisassembler.cpp */; };
618
		0FAF7EFD165BA91B000C8455 /* JITDisassembler.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FAF7EFA165BA919000C8455 /* JITDisassembler.cpp */; };
618
		0FAF7EFE165BA91F000C8455 /* JITDisassembler.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FAF7EFB165BA919000C8455 /* JITDisassembler.h */; settings = {ATTRIBUTES = (Private, ); }; };
619
		0FAF7EFE165BA91F000C8455 /* JITDisassembler.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FAF7EFB165BA919000C8455 /* JITDisassembler.h */; settings = {ATTRIBUTES = (Private, ); }; };
Lines 3003-3008 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec2
3003
		0FA7A8E918B413C80052371D /* Reg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Reg.cpp; sourceTree = "<group>"; };
3004
		0FA7A8E918B413C80052371D /* Reg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Reg.cpp; sourceTree = "<group>"; };
3004
		0FA7A8EA18B413C80052371D /* Reg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Reg.h; sourceTree = "<group>"; };
3005
		0FA7A8EA18B413C80052371D /* Reg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Reg.h; sourceTree = "<group>"; };
3005
		0FA7A8ED18CE4FD80052371D /* ScratchRegisterAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScratchRegisterAllocator.cpp; sourceTree = "<group>"; };
3006
		0FA7A8ED18CE4FD80052371D /* ScratchRegisterAllocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScratchRegisterAllocator.cpp; sourceTree = "<group>"; };
3007
		0FADDD1C1DD01EDC008275E8 /* ResumeTheWorldScope.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ResumeTheWorldScope.h; sourceTree = "<group>"; };
3006
		0FADE6721D4D23BC00768457 /* HeapUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HeapUtil.h; sourceTree = "<group>"; };
3008
		0FADE6721D4D23BC00768457 /* HeapUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HeapUtil.h; sourceTree = "<group>"; };
3007
		0FAF7EFA165BA919000C8455 /* JITDisassembler.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JITDisassembler.cpp; sourceTree = "<group>"; };
3009
		0FAF7EFA165BA919000C8455 /* JITDisassembler.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JITDisassembler.cpp; sourceTree = "<group>"; };
3008
		0FAF7EFB165BA919000C8455 /* JITDisassembler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JITDisassembler.h; sourceTree = "<group>"; };
3010
		0FAF7EFB165BA919000C8455 /* JITDisassembler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JITDisassembler.h; sourceTree = "<group>"; };
Lines 5684-5689 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec3
5684
				0FA762031DB9242300B7A2FD /* MutatorState.h */,
5686
				0FA762031DB9242300B7A2FD /* MutatorState.h */,
5685
				ADDB1F6218D77DB7009B58A8 /* OpaqueRootSet.h */,
5687
				ADDB1F6218D77DB7009B58A8 /* OpaqueRootSet.h */,
5686
				0F7CF94E1DBEEE860098CC12 /* ReleaseHeapAccessScope.h */,
5688
				0F7CF94E1DBEEE860098CC12 /* ReleaseHeapAccessScope.h */,
5689
				0FADDD1C1DD01EDC008275E8 /* ResumeTheWorldScope.h */,
5687
				C225494215F7DBAA0065E898 /* SlotVisitor.cpp */,
5690
				C225494215F7DBAA0065E898 /* SlotVisitor.cpp */,
5688
				14BA78F013AAB88F005B7C2C /* SlotVisitor.h */,
5691
				14BA78F013AAB88F005B7C2C /* SlotVisitor.h */,
5689
				0FCB408515C0A3C30048932B /* SlotVisitorInlines.h */,
5692
				0FCB408515C0A3C30048932B /* SlotVisitorInlines.h */,
Lines 7915-7920 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec4
7915
				0FFB921A16D02EC50055A5DB /* DFGBasicBlockInlines.h in Headers */,
7918
				0FFB921A16D02EC50055A5DB /* DFGBasicBlockInlines.h in Headers */,
7916
				A7D89CF417A0B8CC00773AD8 /* DFGBlockInsertionSet.h in Headers */,
7919
				A7D89CF417A0B8CC00773AD8 /* DFGBlockInsertionSet.h in Headers */,
7917
				0F2BBD961C5FF3F50023EF23 /* B3SparseCollection.h in Headers */,
7920
				0F2BBD961C5FF3F50023EF23 /* B3SparseCollection.h in Headers */,
7921
				0FADDD1D1DD01EDE008275E8 /* ResumeTheWorldScope.h in Headers */,
7918
				DC3D2B0A1D34316200BA918C /* HeapCell.h in Headers */,
7922
				DC3D2B0A1D34316200BA918C /* HeapCell.h in Headers */,
7919
				0FC3CCFC19ADA410006AC72A /* DFGBlockMap.h in Headers */,
7923
				0FC3CCFC19ADA410006AC72A /* DFGBlockMap.h in Headers */,
7920
				0FC3CCFD19ADA410006AC72A /* DFGBlockMapInlines.h in Headers */,
7924
				0FC3CCFD19ADA410006AC72A /* DFGBlockMapInlines.h in Headers */,
Lines 10076-10082 Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec5
10076
				0FF4275715914A20004CB9FF /* LinkBuffer.cpp in Sources */,
10080
				0FF4275715914A20004CB9FF /* LinkBuffer.cpp in Sources */,
10077
				A7E2EA6C0FB460CF00601F06 /* LiteralParser.cpp in Sources */,
10081
				A7E2EA6C0FB460CF00601F06 /* LiteralParser.cpp in Sources */,
10078
				A5A1A0951D8CB341004C2EB8 /* DebuggerParseData.cpp in Sources */,
10082
				A5A1A0951D8CB341004C2EB8 /* DebuggerParseData.cpp in Sources */,
10079
				53FF7F9D1DC00DB100A26CCC /* WasmFormat.cpp in Sources */,
10080
				FE3913541B794F6E00EDAF71 /* LiveObjectList.cpp in Sources */,
10083
				FE3913541B794F6E00EDAF71 /* LiveObjectList.cpp in Sources */,
10081
				FE20CE9D15F04A9500DF3430 /* LLIntCLoop.cpp in Sources */,
10084
				FE20CE9D15F04A9500DF3430 /* LLIntCLoop.cpp in Sources */,
10082
				0F4680D214BBD16500BFE272 /* LLIntData.cpp in Sources */,
10085
				0F4680D214BBD16500BFE272 /* LLIntData.cpp in Sources */,
- Source/JavaScriptCore/dfg/DFGPlan.cpp -4 / +22 lines
Lines 610-625 CompilationKey Plan::key() Source/JavaScriptCore/dfg/DFGPlan.cpp_sec1
610
    return CompilationKey(codeBlock->alternative(), mode);
610
    return CompilationKey(codeBlock->alternative(), mode);
611
}
611
}
612
612
613
void Plan::rememberCodeBlocks()
613
void Plan::markCodeBlocks(SlotVisitor& slotVisitor)
614
{
614
{
615
    if (!isKnownToBeLiveDuringGC())
616
        return;
617
    
618
    // Compilation writes lots of values to a CodeBlock without performing
619
    // an explicit barrier. So, we need to be pessimistic and assume that
620
    // all our CodeBlocks must be visited during GC.
621
622
    slotVisitor.appendUnbarrieredReadOnlyPointer(codeBlock);
623
    slotVisitor.appendUnbarrieredReadOnlyPointer(codeBlock->alternative());
624
    if (profiledDFGCodeBlock)
625
        slotVisitor.appendUnbarrieredReadOnlyPointer(profiledDFGCodeBlock);
626
}
627
628
void Plan::rememberCodeBlocks(VM& vm)
629
{
630
    if (!isKnownToBeLiveDuringGC())
631
        return;
632
    
615
    // Compilation writes lots of values to a CodeBlock without performing
633
    // Compilation writes lots of values to a CodeBlock without performing
616
    // an explicit barrier. So, we need to be pessimistic and assume that
634
    // an explicit barrier. So, we need to be pessimistic and assume that
617
    // all our CodeBlocks must be visited during GC.
635
    // all our CodeBlocks must be visited during GC.
618
636
619
    Heap::heap(codeBlock)->writeBarrier(codeBlock);
637
    vm.heap.writeBarrier(codeBlock);
620
    Heap::heap(codeBlock)->writeBarrier(codeBlock->alternative());
638
    vm.heap.writeBarrier(codeBlock->alternative());
621
    if (profiledDFGCodeBlock)
639
    if (profiledDFGCodeBlock)
622
        Heap::heap(profiledDFGCodeBlock)->writeBarrier(profiledDFGCodeBlock);
640
        vm.heap.writeBarrier(profiledDFGCodeBlock);
623
}
641
}
624
642
625
void Plan::checkLivenessAndVisitChildren(SlotVisitor& visitor)
643
void Plan::checkLivenessAndVisitChildren(SlotVisitor& visitor)
- Source/JavaScriptCore/dfg/DFGPlan.h -1 / +2 lines
Lines 69-75 struct Plan : public ThreadSafeRefCounte Source/JavaScriptCore/dfg/DFGPlan.h_sec1
69
    
69
    
70
    CompilationKey key();
70
    CompilationKey key();
71
    
71
    
72
    void rememberCodeBlocks();
72
    void markCodeBlocks(SlotVisitor&);
73
    void rememberCodeBlocks(VM&);
73
    void checkLivenessAndVisitChildren(SlotVisitor&);
74
    void checkLivenessAndVisitChildren(SlotVisitor&);
74
    bool isKnownToBeLiveDuringGC();
75
    bool isKnownToBeLiveDuringGC();
75
    void cancel();
76
    void cancel();
- Source/JavaScriptCore/dfg/DFGWorklist.cpp -4 / +38 lines
Lines 26-33 Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec1
26
#include "config.h"
26
#include "config.h"
27
#include "DFGWorklist.h"
27
#include "DFGWorklist.h"
28
28
29
#if ENABLE(DFG_JIT)
30
31
#include "CodeBlock.h"
29
#include "CodeBlock.h"
32
#include "DFGLongLivedState.h"
30
#include "DFGLongLivedState.h"
33
#include "DFGSafepoint.h"
31
#include "DFGSafepoint.h"
Lines 38-43 Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec2
38
36
39
namespace JSC { namespace DFG {
37
namespace JSC { namespace DFG {
40
38
39
#if ENABLE(DFG_JIT)
40
41
class Worklist::ThreadBody : public AutomaticThread {
41
class Worklist::ThreadBody : public AutomaticThread {
42
public:
42
public:
43
    ThreadBody(const LockHolder& locker, Worklist& worklist, ThreadData& data, Box<Lock> lock, RefPtr<AutomaticThreadCondition> condition, int relativePriority)
43
    ThreadBody(const LockHolder& locker, Worklist& worklist, ThreadData& data, Box<Lock> lock, RefPtr<AutomaticThreadCondition> condition, int relativePriority)
Lines 349-354 void Worklist::completeAllPlansForVM(VM& Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec3
349
    completeAllReadyPlansForVM(vm);
349
    completeAllReadyPlansForVM(vm);
350
}
350
}
351
351
352
void Worklist::markCodeBlocks(VM& vm, SlotVisitor& slotVisitor)
353
{
354
    LockHolder locker(*m_lock);
355
    for (PlanMap::iterator iter = m_plans.begin(); iter != m_plans.end(); ++iter) {
356
        Plan* plan = iter->value.get();
357
        if (plan->vm != &vm)
358
            continue;
359
        plan->markCodeBlocks(slotVisitor);
360
    }
361
}
362
352
void Worklist::rememberCodeBlocks(VM& vm)
363
void Worklist::rememberCodeBlocks(VM& vm)
353
{
364
{
354
    LockHolder locker(*m_lock);
365
    LockHolder locker(*m_lock);
Lines 356-362 void Worklist::rememberCodeBlocks(VM& vm Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec4
356
        Plan* plan = iter->value.get();
367
        Plan* plan = iter->value.get();
357
        if (plan->vm != &vm)
368
        if (plan->vm != &vm)
358
            continue;
369
            continue;
359
        plan->rememberCodeBlocks();
370
        plan->rememberCodeBlocks(vm);
360
    }
371
    }
361
}
372
}
362
373
Lines 553-558 void completeAllPlansForVM(VM& vm) Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec5
553
    }
564
    }
554
}
565
}
555
566
567
void markCodeBlocks(VM& vm, SlotVisitor& slotVisitor)
568
{
569
    for (unsigned i = DFG::numberOfWorklists(); i--;) {
570
        if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i))
571
            worklist->markCodeBlocks(vm, slotVisitor);
572
    }
573
}
574
556
void rememberCodeBlocks(VM& vm)
575
void rememberCodeBlocks(VM& vm)
557
{
576
{
558
    for (unsigned i = DFG::numberOfWorklists(); i--;) {
577
    for (unsigned i = DFG::numberOfWorklists(); i--;) {
Lines 561-567 void rememberCodeBlocks(VM& vm) Source/JavaScriptCore/dfg/DFGWorklist.cpp_sec6
561
    }
580
    }
562
}
581
}
563
582
564
} } // namespace JSC::DFG
583
#else // ENABLE(DFG_JIT)
584
585
void completeAllPlansForVM(VM&)
586
{
587
}
588
589
void markCodeBlocks(VM&, SlotVisitor&)
590
{
591
}
592
593
void rememberCodeBlocks(VM&)
594
{
595
}
565
596
566
#endif // ENABLE(DFG_JIT)
597
#endif // ENABLE(DFG_JIT)
567
598
599
} } // namespace JSC::DFG
600
601
- Source/JavaScriptCore/dfg/DFGWorklist.h -3 / +6 lines
Lines 25-32 Source/JavaScriptCore/dfg/DFGWorklist.h_sec1
25
25
26
#pragma once
26
#pragma once
27
27
28
#if ENABLE(DFG_JIT)
29
30
#include "DFGPlan.h"
28
#include "DFGPlan.h"
31
#include "DFGThreadData.h"
29
#include "DFGThreadData.h"
32
#include <wtf/AutomaticThread.h>
30
#include <wtf/AutomaticThread.h>
Lines 42-47 class SlotVisitor; Source/JavaScriptCore/dfg/DFGWorklist.h_sec2
42
40
43
namespace DFG {
41
namespace DFG {
44
42
43
#if ENABLE(DFG_JIT)
44
45
class Worklist : public RefCounted<Worklist> {
45
class Worklist : public RefCounted<Worklist> {
46
public:
46
public:
47
    enum State { NotKnown, Compiling, Compiled };
47
    enum State { NotKnown, Compiling, Compiled };
Lines 57-62 public: Source/JavaScriptCore/dfg/DFGWorklist.h_sec3
57
    // worklist->completeAllReadyPlansForVM(vm);
57
    // worklist->completeAllReadyPlansForVM(vm);
58
    void completeAllPlansForVM(VM&);
58
    void completeAllPlansForVM(VM&);
59
59
60
    void markCodeBlocks(VM&, SlotVisitor&);
60
    void rememberCodeBlocks(VM&);
61
    void rememberCodeBlocks(VM&);
61
62
62
    void waitUntilAllPlansForVMAreReady(VM&);
63
    void waitUntilAllPlansForVMAreReady(VM&);
Lines 163-171 inline Worklist& existingWorklistForInde Source/JavaScriptCore/dfg/DFGWorklist.h_sec4
163
    return *result;
164
    return *result;
164
}
165
}
165
166
167
#endif // ENABLE(DFG_JIT)
168
166
void completeAllPlansForVM(VM&);
169
void completeAllPlansForVM(VM&);
170
void markCodeBlocks(VM&, SlotVisitor&);
167
void rememberCodeBlocks(VM&);
171
void rememberCodeBlocks(VM&);
168
172
169
} } // namespace JSC::DFG
173
} } // namespace JSC::DFG
170
174
171
#endif // ENABLE(DFG_JIT)
- Source/JavaScriptCore/heap/CellState.h -9 / +3 lines
Lines 37-53 enum class CellState : uint8_t { Source/JavaScriptCore/heap/CellState.h_sec1
37
    // SlotVisitors are done.
37
    // SlotVisitors are done.
38
    AnthraciteOrBlack = 0,
38
    AnthraciteOrBlack = 0,
39
    
39
    
40
    // The object is in eden. During GC, this means that the object has not been marked yet.
40
    // The object is going to be is in eden. During GC, this means that the object has not been marked yet.
41
    NewWhite = 1,
41
    NewWhite = 1,
42
42
43
    // The object is grey - i.e. it will be scanned - and this is the first time in this GC that we are
43
    // The object is grey - i.e. it will be scanned.
44
    // going to scan it. If this is an eden GC, this also means that the object is in eden.
44
    Grey = 2,
45
    NewGrey = 2,
46
47
    // The object is grey - i.e. it will be scanned - but it either belongs to old gen (if this is eden
48
    // GC) or it is grey a second time in this current GC (because a concurrent store barrier requested
49
    // re-greying).
50
    OldGrey = 3
51
};
45
};
52
46
53
static const unsigned blackThreshold = 0; // x <= blackThreshold means x is AnthraciteOrBlack.
47
static const unsigned blackThreshold = 0; // x <= blackThreshold means x is AnthraciteOrBlack.
- Source/JavaScriptCore/heap/GCSegmentedArray.h -1 / +4 lines
Lines 1-5 Source/JavaScriptCore/heap/GCSegmentedArray.h_sec1
1
/*
1
/*
2
 * Copyright (C) 2014 Apple Inc. All rights reserved.
2
 * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
3
 *
3
 *
4
 * Redistribution and use in source and binary forms, with or without
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
5
 * modification, are permitted provided that the following conditions
Lines 26-31 Source/JavaScriptCore/heap/GCSegmentedArray.h_sec2
26
#pragma once
26
#pragma once
27
27
28
#include <wtf/DoublyLinkedList.h>
28
#include <wtf/DoublyLinkedList.h>
29
#include <wtf/ListDump.h>
30
#include <wtf/PrintStream.h>
29
#include <wtf/Vector.h>
31
#include <wtf/Vector.h>
30
32
31
namespace JSC {
33
namespace JSC {
Lines 162-164 private: Source/JavaScriptCore/heap/GCSegmentedArray.h_sec3
162
};
164
};
163
165
164
} // namespace JSC
166
} // namespace JSC
167
- Source/JavaScriptCore/heap/Heap.cpp -293 / +242 lines
Lines 78-83 using namespace std; Source/JavaScriptCore/heap/Heap.cpp_sec1
78
78
79
namespace JSC {
79
namespace JSC {
80
80
81
class Heap::ResumeTheWorldScope {
82
public:
83
    ResumeTheWorldScope(Heap& heap)
84
        : m_heap(heap)
85
    {
86
        if (!Options::useConcurrentGC())
87
            return;
88
        
89
        if (Options::logGC())
90
            dataLog((MonotonicTime::now() - m_heap.m_stopTime).milliseconds(), " ms...]\n");
91
        
92
        m_heap.resumeTheWorld();
93
    }
94
    
95
    ~ResumeTheWorldScope()
96
    {
97
        if (!Options::useConcurrentGC())
98
            return;
99
        
100
        if (Options::logGC())
101
            m_heap.stopTheWorld();
102
103
        dataLog("[Increment: ");
104
    }
105
    
106
private:
107
    Heap& m_heap;
108
};
109
81
namespace {
110
namespace {
82
111
83
static const size_t largeHeapSize = 32 * MB; // About 1.5X the average webpage.
112
static const size_t largeHeapSize = 32 * MB; // About 1.5X the average webpage.
Lines 244-250 Heap::Heap(VM* vm, HeapType heapType) Source/JavaScriptCore/heap/Heap.cpp_sec2
244
    , m_extraMemorySize(0)
273
    , m_extraMemorySize(0)
245
    , m_deprecatedExtraMemorySize(0)
274
    , m_deprecatedExtraMemorySize(0)
246
    , m_machineThreads(this)
275
    , m_machineThreads(this)
247
    , m_slotVisitor(*this)
276
    , m_collectorSlotVisitor(std::make_unique<SlotVisitor>(*this))
277
    , m_mutatorMarkStack(std::make_unique<MarkStackArray>())
248
    , m_handleSet(vm)
278
    , m_handleSet(vm)
249
    , m_codeBlocks(std::make_unique<CodeBlockSet>())
279
    , m_codeBlocks(std::make_unique<CodeBlockSet>())
250
    , m_jitStubRoutines(std::make_unique<JITStubRoutineSet>())
280
    , m_jitStubRoutines(std::make_unique<JITStubRoutineSet>())
Lines 266-271 Heap::Heap(VM* vm, HeapType heapType) Source/JavaScriptCore/heap/Heap.cpp_sec3
266
#if USE(FOUNDATION)
296
#if USE(FOUNDATION)
267
    , m_delayedReleaseRecursionCount(0)
297
    , m_delayedReleaseRecursionCount(0)
268
#endif
298
#endif
299
    , m_sharedCollectorMarkStack(std::make_unique<MarkStackArray>())
300
    , m_sharedMutatorMarkStack(std::make_unique<MarkStackArray>())
269
    , m_helperClient(&heapHelperPool())
301
    , m_helperClient(&heapHelperPool())
270
    , m_threadLock(Box<Lock>::create())
302
    , m_threadLock(Box<Lock>::create())
271
    , m_threadCondition(AutomaticThreadCondition::create())
303
    , m_threadCondition(AutomaticThreadCondition::create())
Lines 416-427 void Heap::addReference(JSCell* cell, Ar Source/JavaScriptCore/heap/Heap.cpp_sec4
416
448
417
void Heap::harvestWeakReferences()
449
void Heap::harvestWeakReferences()
418
{
450
{
419
    m_slotVisitor.harvestWeakReferences();
451
    m_collectorSlotVisitor->harvestWeakReferences();
420
}
452
}
421
453
422
void Heap::finalizeUnconditionalFinalizers()
454
void Heap::finalizeUnconditionalFinalizers()
423
{
455
{
424
    m_slotVisitor.finalizeUnconditionalFinalizers();
456
    m_collectorSlotVisitor->finalizeUnconditionalFinalizers();
425
}
457
}
426
458
427
void Heap::willStartIterating()
459
void Heap::willStartIterating()
Lines 439-554 void Heap::completeAllJITPlans() Source/JavaScriptCore/heap/Heap.cpp_sec5
439
#if ENABLE(JIT)
471
#if ENABLE(JIT)
440
    JITWorklist::instance()->completeAllForVM(*m_vm);
472
    JITWorklist::instance()->completeAllForVM(*m_vm);
441
#endif // ENABLE(JIT)
473
#endif // ENABLE(JIT)
442
#if ENABLE(DFG_JIT)
443
    DFG::completeAllPlansForVM(*m_vm);
474
    DFG::completeAllPlansForVM(*m_vm);
444
#endif
445
}
475
}
446
476
447
void Heap::markRoots(double gcStartTime)
477
void Heap::markToFixpoint(double gcStartTime)
448
{
478
{
449
    TimingScope markRootsTimingScope(*this, "Heap::markRoots");
479
    TimingScope markToFixpointTimingScope(*this, "Heap::markToFixpoint");
450
    
480
    
451
    HeapRootVisitor heapRootVisitor(m_slotVisitor);
481
    HeapRootVisitor heapRootVisitor(*m_collectorSlotVisitor);
452
    
482
    
453
    {
483
    if (m_collectionScope == CollectionScope::Full) {
454
        TimingScope preConvergenceTimingScope(*this, "Heap::markRoots before convergence");
484
        m_opaqueRoots.clear();
485
        m_collectorSlotVisitor->clearMarkStacks();
486
        m_mutatorMarkStack->clear();
487
    }
455
488
456
#if ENABLE(DFG_JIT)
489
    beginMarking();
457
        DFG::rememberCodeBlocks(*m_vm);
458
#endif
459
490
460
#if ENABLE(SAMPLING_PROFILER)
491
    m_parallelMarkersShouldExit = false;
461
        if (SamplingProfiler* samplingProfiler = m_vm->samplingProfiler()) {
462
            // Note that we need to own the lock from now until we're done
463
            // marking the SamplingProfiler's data because once we verify the
464
            // SamplingProfiler's stack traces, we don't want it to accumulate
465
            // more stack traces before we get the chance to mark it.
466
            // This lock is released inside visitSamplingProfiler().
467
            samplingProfiler->getLock().lock();
468
            samplingProfiler->processUnverifiedStackTraces();
469
        }
470
#endif // ENABLE(SAMPLING_PROFILER)
471
492
472
        if (m_collectionScope == CollectionScope::Full) {
493
    m_helperClient.setFunction(
473
            m_opaqueRoots.clear();
494
        [this] () {
474
            m_slotVisitor.clearMarkStack();
495
            SlotVisitor* slotVisitor;
475
        }
496
            {
476
497
                LockHolder locker(m_parallelSlotVisitorLock);
477
        beginMarking();
498
                if (m_availableParallelSlotVisitors.isEmpty()) {
478
499
                    std::unique_ptr<SlotVisitor> newVisitor =
479
        m_parallelMarkersShouldExit = false;
500
                        std::make_unique<SlotVisitor>(*this);
480
501
                    slotVisitor = newVisitor.get();
481
        m_helperClient.setFunction(
502
                    m_parallelSlotVisitors.append(WTFMove(newVisitor));
482
            [this] () {
503
                } else
483
                SlotVisitor* slotVisitor;
504
                    slotVisitor = m_availableParallelSlotVisitors.takeLast();
484
                {
505
            }
485
                    LockHolder locker(m_parallelSlotVisitorLock);
486
                    if (m_availableParallelSlotVisitors.isEmpty()) {
487
                        std::unique_ptr<SlotVisitor> newVisitor =
488
                            std::make_unique<SlotVisitor>(*this);
489
                        slotVisitor = newVisitor.get();
490
                        m_parallelSlotVisitors.append(WTFMove(newVisitor));
491
                    } else
492
                        slotVisitor = m_availableParallelSlotVisitors.takeLast();
493
                }
494
506
495
                WTF::registerGCThread(GCThreadType::Helper);
507
            WTF::registerGCThread(GCThreadType::Helper);
496
508
497
                {
509
            {
498
                    ParallelModeEnabler parallelModeEnabler(*slotVisitor);
510
                ParallelModeEnabler parallelModeEnabler(*slotVisitor);
499
                    slotVisitor->didStartMarking();
511
                slotVisitor->didStartMarking();
500
                    slotVisitor->drainFromShared(SlotVisitor::SlaveDrain);
512
                slotVisitor->drainFromShared(SlotVisitor::SlaveDrain);
501
                }
513
            }
502
514
503
                {
515
            {
504
                    LockHolder locker(m_parallelSlotVisitorLock);
516
                LockHolder locker(m_parallelSlotVisitorLock);
505
                    m_availableParallelSlotVisitors.append(slotVisitor);
517
                m_availableParallelSlotVisitors.append(slotVisitor);
506
                }
518
            }
507
            });
519
        });
508
520
509
        m_slotVisitor.didStartMarking();
521
    m_collectorSlotVisitor->didStartMarking();
510
    }
511
    
512
    {
513
        SuperSamplerScope superSamplerScope(false);
514
        TimingScope convergenceTimingScope(*this, "Heap::markRoots convergence");
515
        ParallelModeEnabler enabler(m_slotVisitor);
516
        
517
        m_slotVisitor.donateAndDrain();
518
522
523
    Seconds concurrentTime;
524
    double stoppedOverConcurrentRatio = 0.1;
525
    const double ratioStep = 1.3;
526
    MonotonicTime initialTime = MonotonicTime::now();
527
    MonotonicTime topOfLoopTime = initialTime;
528
    while (true) {
529
        MonotonicTime timeToResume = topOfLoopTime + concurrentTime * stoppedOverConcurrentRatio;
530
        stoppedOverConcurrentRatio *= ratioStep;
519
        {
531
        {
520
            TimingScope preConvergenceTimingScope(*this, "Heap::markRoots conservative scan");
532
            TimingScope preConvergenceTimingScope(*this, "Heap::markToFixpoint conservative scan");
521
            ConservativeRoots conservativeRoots(*this);
533
            ConservativeRoots conservativeRoots(*this);
522
            SuperSamplerScope superSamplerScope(false);
534
            SuperSamplerScope superSamplerScope(false);
523
            gatherStackRoots(conservativeRoots);
535
            gatherStackRoots(conservativeRoots);
524
            gatherJSStackRoots(conservativeRoots);
536
            gatherJSStackRoots(conservativeRoots);
525
            gatherScratchBufferRoots(conservativeRoots);
537
            gatherScratchBufferRoots(conservativeRoots);
526
            visitConservativeRoots(conservativeRoots);
538
            visitConservativeRoots(conservativeRoots);
539
        }
540
            
541
        // Now we visit roots that don't get barriered, so each fixpoint iteration just revisits
542
        // all of them.
543
#if JSC_OBJC_API_ENABLED
544
        scanExternalRememberedSet(*m_vm, *m_collectorSlotVisitor);
545
#endif
546
            
547
        if (m_vm->smallStrings.needsToBeVisited(*m_collectionScope))
548
            m_vm->smallStrings.visitStrongReferences(*m_collectorSlotVisitor);
549
            
550
        for (auto& pair : m_protectedValues)
551
            heapRootVisitor.visit(&pair.key);
552
            
553
        if (m_markListSet && m_markListSet->size())
554
            MarkedArgumentBuffer::markLists(heapRootVisitor, *m_markListSet);
527
            
555
            
528
            // We want to do this to conservatively ensure that we rescan any code blocks that are
556
        if (m_vm->exception())
529
            // running right now. However, we need to be sure to do it *after* we mark the code block
557
            heapRootVisitor.visit(m_vm->addressOfException());
530
            // so that we know for sure if it really needs a barrier.
558
        if (m_vm->lastException())
531
            m_codeBlocks->writeBarrierCurrentlyExecuting(this);
559
            heapRootVisitor.visit(m_vm->addressOfLastException());
532
        }
560
            
533
561
        m_handleSet.visitStrongHandles(heapRootVisitor);
534
        visitExternalRememberedSet();
562
        m_handleStack.visit(heapRootVisitor);
535
        visitSmallStrings();
563
536
        visitProtectedObjects(heapRootVisitor);
564
#if ENABLE(SAMPLING_PROFILER)
537
        visitArgumentBuffers(heapRootVisitor);
565
        if (SamplingProfiler* samplingProfiler = m_vm->samplingProfiler()) {
538
        visitException(heapRootVisitor);
566
            LockHolder locker(samplingProfiler->getLock());
539
        visitStrongHandles(heapRootVisitor);
567
            samplingProfiler->processUnverifiedStackTraces();
540
        visitHandleStack(heapRootVisitor);
568
            samplingProfiler->visit(*m_collectorSlotVisitor);
541
        visitSamplingProfiler();
569
            if (Options::logGC() == GCLogging::Verbose)
542
        visitShadowChicken();
570
                dataLog("Sampling Profiler data:\n", *m_collectorSlotVisitor);
543
        traceCodeBlocksAndJITStubRoutines();
571
        }
544
        m_slotVisitor.drainFromShared(SlotVisitor::MasterDrain);
572
#endif // ENABLE(SAMPLING_PROFILER)
545
    }
573
                
546
    
574
        m_vm->shadowChicken().visitChildren(*m_collectorSlotVisitor);
547
    TimingScope postConvergenceTimingScope(*this, "Heap::markRoots after convergence");
575
                
548
576
        m_jitStubRoutines->traceMarkedStubRoutines(*m_collectorSlotVisitor);
549
    // Weak references must be marked last because their liveness depends on
577
550
    // the liveness of the rest of the object graph.
578
        m_collectorSlotVisitor->mergeOpaqueRootsIfNecessary();
551
    visitWeakHandles(heapRootVisitor);
579
        for (auto& parallelVisitor : m_parallelSlotVisitors)
580
            parallelVisitor->mergeOpaqueRootsIfNecessary();
581
582
        m_objectSpace.visitWeakSets(heapRootVisitor);
583
        harvestWeakReferences();
584
        visitCompilerWorklistWeakReferences();
585
        DFG::markCodeBlocks(*m_vm, *m_collectorSlotVisitor);
586
        bool shouldTerminate = m_collectorSlotVisitor->isEmpty() && m_mutatorMarkStack->isEmpty();
587
        
588
        // We want to do this to conservatively ensure that we rescan any code blocks that are
589
        // running right now. However, we need to be sure to do it *after* we mark the code block
590
        // so that we know for sure if it really needs a barrier. Also, this has to happen after the
591
        // fixpoint check - otherwise we might loop forever. Incidentally, we also want to do this
592
        // at the end of GC so that anything at the end of the last GC gets barriered in the next
593
        // GC.
594
        m_codeBlocks->writeBarrierCurrentlyExecuting(this);
595
        DFG::rememberCodeBlocks(*m_vm);
596
        
597
        if (shouldTerminate)
598
            break;
599
        
600
        // The SlotVisitor's mark stacks are accessed by the collector thread (i.e. this thread)
601
        // without locks. That's why we double-buffer.
602
        m_mutatorMarkStack->transferTo(m_collectorSlotVisitor->mutatorMarkStack());
603
        
604
        if (Options::logGC() == GCLogging::Verbose)
605
            dataLog("Live Weak Handles:\n", *m_collectorSlotVisitor);
606
607
        {
608
            TimingScope traceTimingScope(*this, "Heap::markToFixpoint tracing");
609
            ParallelModeEnabler enabler(*m_collectorSlotVisitor);
610
            m_collectorSlotVisitor->donateAndDrain(timeToResume);
611
            SlotVisitor::SharedDrainResult drainResult =
612
                m_collectorSlotVisitor->drainFromShared(SlotVisitor::MasterDrain, timeToResume);
613
            if (drainResult != SlotVisitor::SharedDrainResult::Done) {
614
                ResumeTheWorldScope resumeTheWorldScope(*this);
615
                m_collectorSlotVisitor->donateAndDrain();
616
                m_collectorSlotVisitor->drainFromShared(SlotVisitor::MasterDrain);
617
            }
618
        }
619
        
620
        MonotonicTime timeOfStop = MonotonicTime::now();
621
        concurrentTime = timeOfStop - timeToResume;
622
        topOfLoopTime = timeOfStop;
623
    }
552
624
553
    {
625
    {
554
        std::lock_guard<Lock> lock(m_markingMutex);
626
        std::lock_guard<Lock> lock(m_markingMutex);
Lines 562-568 void Heap::markRoots(double gcStartTime) Source/JavaScriptCore/heap/Heap.cpp_sec6
562
634
563
void Heap::gatherStackRoots(ConservativeRoots& roots)
635
void Heap::gatherStackRoots(ConservativeRoots& roots)
564
{
636
{
565
    m_jitStubRoutines->clearMarks();
566
    m_machineThreads.gatherConservativeRoots(roots, *m_jitStubRoutines, *m_codeBlocks);
637
    m_machineThreads.gatherConservativeRoots(roots, *m_jitStubRoutines, *m_codeBlocks);
567
}
638
}
568
639
Lines 589-594 void Heap::beginMarking() Source/JavaScriptCore/heap/Heap.cpp_sec7
589
    TimingScope timingScope(*this, "Heap::beginMarking");
660
    TimingScope timingScope(*this, "Heap::beginMarking");
590
    if (m_collectionScope == CollectionScope::Full)
661
    if (m_collectionScope == CollectionScope::Full)
591
        m_codeBlocks->clearMarksForFullCollection();
662
        m_codeBlocks->clearMarksForFullCollection();
663
    m_jitStubRoutines->clearMarks();
592
    
664
    
593
    {
665
    {
594
        TimingScope clearMarksTimingScope(*this, "m_objectSpace.beginMarking");
666
        TimingScope clearMarksTimingScope(*this, "m_objectSpace.beginMarking");
Lines 596-637 void Heap::beginMarking() Source/JavaScriptCore/heap/Heap.cpp_sec8
596
    }
668
    }
597
}
669
}
598
670
599
void Heap::visitExternalRememberedSet()
600
{
601
#if JSC_OBJC_API_ENABLED
602
    scanExternalRememberedSet(*m_vm, m_slotVisitor);
603
#endif
604
}
605
606
void Heap::visitSmallStrings()
607
{
608
    if (!m_vm->smallStrings.needsToBeVisited(*m_collectionScope))
609
        return;
610
611
    m_vm->smallStrings.visitStrongReferences(m_slotVisitor);
612
    if (Options::logGC() == GCLogging::Verbose)
613
        dataLog("Small strings:\n", m_slotVisitor);
614
    m_slotVisitor.donateAndDrain();
615
}
616
617
void Heap::visitConservativeRoots(ConservativeRoots& roots)
671
void Heap::visitConservativeRoots(ConservativeRoots& roots)
618
{
672
{
619
    m_slotVisitor.append(roots);
673
    m_collectorSlotVisitor->append(roots);
620
674
621
    if (Options::logGC() == GCLogging::Verbose)
675
    if (Options::logGC() == GCLogging::Verbose)
622
        dataLog("Conservative Roots:\n", m_slotVisitor);
676
        dataLog("Conservative Roots:\n", *m_collectorSlotVisitor);
623
624
    m_slotVisitor.donateAndDrain();
625
}
677
}
626
678
627
void Heap::visitCompilerWorklistWeakReferences()
679
void Heap::visitCompilerWorklistWeakReferences()
628
{
680
{
629
#if ENABLE(DFG_JIT)
681
#if ENABLE(DFG_JIT)
630
    for (unsigned i = DFG::numberOfWorklists(); i--;)
682
    for (unsigned i = DFG::numberOfWorklists(); i--;)
631
        DFG::existingWorklistForIndex(i).visitWeakReferences(m_slotVisitor);
683
        DFG::existingWorklistForIndex(i).visitWeakReferences(*m_collectorSlotVisitor);
632
684
633
    if (Options::logGC() == GCLogging::Verbose)
685
    if (Options::logGC() == GCLogging::Verbose)
634
        dataLog("DFG Worklists:\n", m_slotVisitor);
686
        dataLog("DFG Worklists:\n", *m_collectorSlotVisitor);
635
#endif
687
#endif
636
}
688
}
637
689
Lines 704-825 void Heap::removeDeadHeapSnapshotNodes(H Source/JavaScriptCore/heap/Heap.cpp_sec9
704
    }
756
    }
705
}
757
}
706
758
707
void Heap::visitProtectedObjects(HeapRootVisitor& heapRootVisitor)
708
{
709
    for (auto& pair : m_protectedValues)
710
        heapRootVisitor.visit(&pair.key);
711
712
    if (Options::logGC() == GCLogging::Verbose)
713
        dataLog("Protected Objects:\n", m_slotVisitor);
714
715
    m_slotVisitor.donateAndDrain();
716
}
717
718
void Heap::visitArgumentBuffers(HeapRootVisitor& visitor)
719
{
720
    if (!m_markListSet || !m_markListSet->size())
721
        return;
722
723
    MarkedArgumentBuffer::markLists(visitor, *m_markListSet);
724
725
    if (Options::logGC() == GCLogging::Verbose)
726
        dataLog("Argument Buffers:\n", m_slotVisitor);
727
728
    m_slotVisitor.donateAndDrain();
729
}
730
731
void Heap::visitException(HeapRootVisitor& visitor)
732
{
733
    if (!m_vm->exception() && !m_vm->lastException())
734
        return;
735
736
    visitor.visit(m_vm->addressOfException());
737
    visitor.visit(m_vm->addressOfLastException());
738
739
    if (Options::logGC() == GCLogging::Verbose)
740
        dataLog("Exceptions:\n", m_slotVisitor);
741
742
    m_slotVisitor.donateAndDrain();
743
}
744
745
void Heap::visitStrongHandles(HeapRootVisitor& visitor)
746
{
747
    m_handleSet.visitStrongHandles(visitor);
748
749
    if (Options::logGC() == GCLogging::Verbose)
750
        dataLog("Strong Handles:\n", m_slotVisitor);
751
752
    m_slotVisitor.donateAndDrain();
753
}
754
755
void Heap::visitHandleStack(HeapRootVisitor& visitor)
756
{
757
    m_handleStack.visit(visitor);
758
759
    if (Options::logGC() == GCLogging::Verbose)
760
        dataLog("Handle Stack:\n", m_slotVisitor);
761
762
    m_slotVisitor.donateAndDrain();
763
}
764
765
void Heap::visitSamplingProfiler()
766
{
767
#if ENABLE(SAMPLING_PROFILER)
768
    if (SamplingProfiler* samplingProfiler = m_vm->samplingProfiler()) {
769
        ASSERT(samplingProfiler->getLock().isLocked());
770
        samplingProfiler->visit(m_slotVisitor);
771
        if (Options::logGC() == GCLogging::Verbose)
772
            dataLog("Sampling Profiler data:\n", m_slotVisitor);
773
774
        m_slotVisitor.donateAndDrain();
775
        samplingProfiler->getLock().unlock();
776
    }
777
#endif // ENABLE(SAMPLING_PROFILER)
778
}
779
780
void Heap::visitShadowChicken()
781
{
782
    m_vm->shadowChicken().visitChildren(m_slotVisitor);
783
}
784
785
void Heap::traceCodeBlocksAndJITStubRoutines()
786
{
787
    m_jitStubRoutines->traceMarkedStubRoutines(m_slotVisitor);
788
789
    if (Options::logGC() == GCLogging::Verbose)
790
        dataLog("Code Blocks and JIT Stub Routines:\n", m_slotVisitor);
791
792
    m_slotVisitor.donateAndDrain();
793
}
794
795
void Heap::visitWeakHandles(HeapRootVisitor& visitor)
796
{
797
    TimingScope timingScope(*this, "Heap::visitWeakHandles");
798
    while (true) {
799
        {
800
            TimingScope timingScope(*this, "m_objectSpace.visitWeakSets");
801
            m_objectSpace.visitWeakSets(visitor);
802
        }
803
        harvestWeakReferences();
804
        visitCompilerWorklistWeakReferences();
805
        if (m_slotVisitor.isEmpty())
806
            break;
807
808
        if (Options::logGC() == GCLogging::Verbose)
809
            dataLog("Live Weak Handles:\n", m_slotVisitor);
810
811
        {
812
            ParallelModeEnabler enabler(m_slotVisitor);
813
            m_slotVisitor.donateAndDrain();
814
            m_slotVisitor.drainFromShared(SlotVisitor::MasterDrain);
815
        }
816
    }
817
}
818
819
void Heap::updateObjectCounts(double gcStartTime)
759
void Heap::updateObjectCounts(double gcStartTime)
820
{
760
{
821
    if (Options::logGC() == GCLogging::Verbose) {
761
    if (Options::logGC() == GCLogging::Verbose) {
822
        size_t visitCount = m_slotVisitor.visitCount();
762
        size_t visitCount = m_collectorSlotVisitor->visitCount();
823
        visitCount += threadVisitCount();
763
        visitCount += threadVisitCount();
824
        dataLogF("\nNumber of live Objects after GC %lu, took %.6f secs\n", static_cast<unsigned long>(visitCount), WTF::monotonicallyIncreasingTime() - gcStartTime);
764
        dataLogF("\nNumber of live Objects after GC %lu, took %.6f secs\n", static_cast<unsigned long>(visitCount), WTF::monotonicallyIncreasingTime() - gcStartTime);
825
    }
765
    }
Lines 827-845 void Heap::updateObjectCounts(double gcS Source/JavaScriptCore/heap/Heap.cpp_sec10
827
    if (m_collectionScope == CollectionScope::Full)
767
    if (m_collectionScope == CollectionScope::Full)
828
        m_totalBytesVisited = 0;
768
        m_totalBytesVisited = 0;
829
769
830
    m_totalBytesVisitedThisCycle = m_slotVisitor.bytesVisited() + threadBytesVisited();
770
    m_totalBytesVisitedThisCycle =
771
        m_collectorSlotVisitor->bytesVisited() +
772
        threadBytesVisited();
831
    
773
    
832
    m_totalBytesVisited += m_totalBytesVisitedThisCycle;
774
    m_totalBytesVisited += m_totalBytesVisitedThisCycle;
833
}
775
}
834
776
835
void Heap::endMarking()
777
void Heap::endMarking()
836
{
778
{
837
    m_slotVisitor.reset();
779
    m_collectorSlotVisitor->reset();
838
780
839
    for (auto& parallelVisitor : m_parallelSlotVisitors)
781
    for (auto& parallelVisitor : m_parallelSlotVisitors)
840
        parallelVisitor->reset();
782
        parallelVisitor->reset();
841
783
842
    ASSERT(m_sharedMarkStack.isEmpty());
784
    RELEASE_ASSERT(m_sharedCollectorMarkStack->isEmpty());
785
    RELEASE_ASSERT(m_sharedMutatorMarkStack->isEmpty());
843
    m_weakReferenceHarvesters.removeAll();
786
    m_weakReferenceHarvesters.removeAll();
844
    
787
    
845
    m_objectSpace.endMarking();
788
    m_objectSpace.endMarking();
Lines 977-990 void Heap::addToRememberedSet(const JSCe Source/JavaScriptCore/heap/Heap.cpp_sec11
977
{
920
{
978
    ASSERT(cell);
921
    ASSERT(cell);
979
    ASSERT(!Options::useConcurrentJIT() || !isCompilationThread());
922
    ASSERT(!Options::useConcurrentJIT() || !isCompilationThread());
980
    ASSERT(cell->cellState() == CellState::AnthraciteOrBlack);
923
    if (!Heap::isMarkedConcurrently(cell)) {
981
    // Indicate that this object is grey and that it's one of the following:
924
        // During a full collection a store into an unmarked object that had surivived past
982
    // - A re-greyed object during a concurrent collection.
925
        // collections will manifest as a store to an unmarked black object. If the object gets
983
    // - An old remembered object.
926
        // marked at some time after this then it will go down the normal marking path. We can
984
    // "OldGrey" doesn't tell us which of these things is true, but we usually treat the two cases the
927
        // safely ignore these stores.
985
    // same.
928
        return;
986
    cell->setCellState(CellState::OldGrey);
929
    }
987
    m_slotVisitor.appendToMarkStack(const_cast<JSCell*>(cell));
930
    // It could be that the object was *just* marked. This means that the collector may set the
931
    // state to Grey and then to AnthraciteOrBlack at any time. It's OK for us to race with the
932
    // collector here. If we win then this is accurate because the object _will_ get scanned again.
933
    // If we lose then someone else will barrier the object again. That would be unfortunate but not
934
    // the end of the world.
935
    cell->setCellState(CellState::Grey);
936
    m_mutatorMarkStack->append(cell);
988
}
937
}
989
938
990
void Heap::collectAllGarbage()
939
void Heap::collectAllGarbage()
Lines 1083-1111 void Heap::collectInThread() Source/JavaScriptCore/heap/Heap.cpp_sec12
1083
    
1032
    
1084
    stopTheWorld();
1033
    stopTheWorld();
1085
1034
1086
    double before = 0;
1035
    MonotonicTime before;
1087
    if (Options::logGC()) {
1036
    if (Options::logGC()) {
1088
        dataLog("[GC: ", capacity() / 1024, " kb ");
1037
        dataLog("[GC: ", capacity() / 1024, " kb ");
1089
        before = currentTimeMS();
1038
        before = MonotonicTime::now();
1090
    }
1039
    }
1091
    
1040
    
1092
    double gcStartTime;
1041
    double gcStartTime;
1093
    
1042
    
1094
    if (vm()->typeProfiler()) {
1095
        DeferGCForAWhile awhile(*this);
1096
        vm()->typeProfilerLog()->processLogEntries(ASCIILiteral("GC"));
1097
    }
1098
    
1099
#if ENABLE(JIT)
1100
    {
1101
        DeferGCForAWhile awhile(*this);
1102
        if (JITWorklist::instance()->completeAllForVM(*m_vm))
1103
            setGCDidJIT();
1104
    }
1105
#endif // ENABLE(JIT)
1106
    
1107
    vm()->shadowChicken().update(*vm(), vm()->topCallFrame);
1108
    
1109
    ASSERT(m_isSafeToCollect);
1043
    ASSERT(m_isSafeToCollect);
1110
    if (m_collectionScope) {
1044
    if (m_collectionScope) {
1111
        dataLog("Collection scope already set during GC: ", m_collectionScope, "\n");
1045
        dataLog("Collection scope already set during GC: ", m_collectionScope, "\n");
Lines 1125-1139 void Heap::collectInThread() Source/JavaScriptCore/heap/Heap.cpp_sec13
1125
        m_verifier->gatherLiveObjects(HeapVerifier::Phase::BeforeMarking);
1059
        m_verifier->gatherLiveObjects(HeapVerifier::Phase::BeforeMarking);
1126
    }
1060
    }
1127
        
1061
        
1128
    flushOldStructureIDTables();
1129
    stopAllocation();
1130
    prepareForMarking();
1062
    prepareForMarking();
1131
    flushWriteBarrierBuffer();
1132
        
1063
        
1133
    if (HasOwnPropertyCache* cache = vm()->hasOwnPropertyCache())
1064
    if (HasOwnPropertyCache* cache = vm()->hasOwnPropertyCache())
1134
        cache->clear();
1065
        cache->clear();
1135
        
1066
        
1136
    markRoots(gcStartTime);
1067
    markToFixpoint(gcStartTime);
1137
        
1068
        
1138
    if (m_verifier) {
1069
    if (m_verifier) {
1139
        m_verifier->gatherLiveObjects(HeapVerifier::Phase::AfterMarking);
1070
        m_verifier->gatherLiveObjects(HeapVerifier::Phase::AfterMarking);
Lines 1170-1177 void Heap::collectInThread() Source/JavaScriptCore/heap/Heap.cpp_sec14
1170
    }
1101
    }
1171
    
1102
    
1172
    if (Options::logGC()) {
1103
    if (Options::logGC()) {
1173
        double after = currentTimeMS();
1104
        MonotonicTime after = MonotonicTime::now();
1174
        dataLog(after - before, " ms]\n");
1105
        dataLog((after - m_stopTime).milliseconds(), " ms, cycle ", (after - before).milliseconds(), " ms]\n");
1175
    }
1106
    }
1176
    
1107
    
1177
    {
1108
    {
Lines 1193-1202 void Heap::stopTheWorld() Source/JavaScriptCore/heap/Heap.cpp_sec15
1193
    stopTheMutator();
1124
    stopTheMutator();
1194
    suspendCompilerThreads();
1125
    suspendCompilerThreads();
1195
    m_collectorBelievesThatTheWorldIsStopped = true;
1126
    m_collectorBelievesThatTheWorldIsStopped = true;
1127
1128
    if (vm()->typeProfiler()) {
1129
        DeferGCForAWhile awhile(*this);
1130
        vm()->typeProfilerLog()->processLogEntries(ASCIILiteral("GC"));
1131
    }
1132
    
1133
#if ENABLE(JIT)
1134
    {
1135
        DeferGCForAWhile awhile(*this);
1136
        if (JITWorklist::instance()->completeAllForVM(*m_vm))
1137
            setGCDidJIT();
1138
    }
1139
#endif // ENABLE(JIT)
1140
    
1141
    vm()->shadowChicken().update(*vm(), vm()->topCallFrame);
1142
    
1143
    flushWriteBarrierBuffer();
1144
    m_structureIDTable.flushOldTables();
1145
    m_objectSpace.stopAllocating();
1146
    
1147
    m_stopTime = MonotonicTime::now();
1196
}
1148
}
1197
1149
1198
void Heap::resumeTheWorld()
1150
void Heap::resumeTheWorld()
1199
{
1151
{
1152
    // Calling resumeAllocating does the Right Thing depending on whether this is the end of a
1153
    // collection cycle or this is just a concurrent phase within a collection cycle:
1154
    // - At end of collection cycle: it's a no-op because prepareForAllocation already cleared the
1155
    //   last active block.
1156
    // - During collection cycle: it reinstates the last active block.
1157
    m_objectSpace.resumeAllocating();
1158
    
1200
    RELEASE_ASSERT(m_collectorBelievesThatTheWorldIsStopped);
1159
    RELEASE_ASSERT(m_collectorBelievesThatTheWorldIsStopped);
1201
    m_collectorBelievesThatTheWorldIsStopped = false;
1160
    m_collectorBelievesThatTheWorldIsStopped = false;
1202
    resumeCompilerThreads();
1161
    resumeCompilerThreads();
Lines 1466-1475 void Heap::notifyThreadStopping(const Lo Source/JavaScriptCore/heap/Heap.cpp_sec16
1466
1425
1467
void Heap::finalize()
1426
void Heap::finalize()
1468
{
1427
{
1469
    HelpingGCScope helpingGCScope(*this);
1428
    {
1470
    deleteUnmarkedCompiledCode();
1429
        HelpingGCScope helpingGCScope(*this);
1471
    deleteSourceProviderCaches();
1430
        deleteUnmarkedCompiledCode();
1472
    sweepLargeAllocations();
1431
        deleteSourceProviderCaches();
1432
        sweepLargeAllocations();
1433
    }
1434
    
1435
    if (Options::collectContinuously())
1436
        collectAsync();
1473
}
1437
}
1474
1438
1475
Heap::Ticket Heap::requestCollection(Optional<CollectionScope> scope)
1439
Heap::Ticket Heap::requestCollection(Optional<CollectionScope> scope)
Lines 1549-1571 void Heap::willStartCollection(Optional< Source/JavaScriptCore/heap/Heap.cpp_sec17
1549
        observer->willGarbageCollect();
1513
        observer->willGarbageCollect();
1550
}
1514
}
1551
1515
1552
void Heap::flushOldStructureIDTables()
1553
{
1554
    m_structureIDTable.flushOldTables();
1555
}
1556
1557
void Heap::flushWriteBarrierBuffer()
1516
void Heap::flushWriteBarrierBuffer()
1558
{
1517
{
1559
    if (m_collectionScope == CollectionScope::Eden) {
1518
    m_writeBarrierBuffer.flush(*this);
1560
        m_writeBarrierBuffer.flush(*this);
1561
        return;
1562
    }
1563
    m_writeBarrierBuffer.reset();
1564
}
1565
1566
void Heap::stopAllocation()
1567
{
1568
    m_objectSpace.stopAllocating();
1569
}
1519
}
1570
1520
1571
void Heap::prepareForMarking()
1521
void Heap::prepareForMarking()
Lines 1949-1955 bool Heap::canCollect() Source/JavaScriptCore/heap/Heap.cpp_sec18
1949
        return false;
1899
        return false;
1950
    if (!m_isSafeToCollect)
1900
    if (!m_isSafeToCollect)
1951
        return false;
1901
        return false;
1952
    if (collectionScope() || mutatorState() == MutatorState::HelpingGC)
1902
    if (mutatorState() == MutatorState::HelpingGC)
1953
        return false;
1903
        return false;
1954
    return true;
1904
    return true;
1955
}
1905
}
Lines 1971-1982 bool Heap::isCurrentThreadBusy() Source/JavaScriptCore/heap/Heap.cpp_sec19
1971
    return mayBeGCThread() || mutatorState() != MutatorState::Running;
1921
    return mayBeGCThread() || mutatorState() != MutatorState::Running;
1972
}
1922
}
1973
1923
1974
void Heap::reportExtraMemoryVisited(CellState oldState, size_t size)
1924
void Heap::reportExtraMemoryVisited(size_t size)
1975
{
1925
{
1976
    // We don't want to double-count the extra memory that was reported in previous collections.
1977
    if (collectionScope() == CollectionScope::Eden && oldState == CellState::OldGrey)
1978
        return;
1979
1980
    size_t* counter = &m_extraMemorySize;
1926
    size_t* counter = &m_extraMemorySize;
1981
    
1927
    
1982
    for (;;) {
1928
    for (;;) {
Lines 1987-1998 void Heap::reportExtraMemoryVisited(Cell Source/JavaScriptCore/heap/Heap.cpp_sec20
1987
}
1933
}
1988
1934
1989
#if ENABLE(RESOURCE_USAGE)
1935
#if ENABLE(RESOURCE_USAGE)
1990
void Heap::reportExternalMemoryVisited(CellState oldState, size_t size)
1936
void Heap::reportExternalMemoryVisited(size_t size)
1991
{
1937
{
1992
    // We don't want to double-count the external memory that was reported in previous collections.
1993
    if (collectionScope() == CollectionScope::Eden && oldState == CellState::OldGrey)
1994
        return;
1995
1996
    size_t* counter = &m_externalMemorySize;
1938
    size_t* counter = &m_externalMemorySize;
1997
1939
1998
    for (;;) {
1940
    for (;;) {
Lines 2086-2089 void Heap::setRunLoop(CFRunLoopRef runLo Source/JavaScriptCore/heap/Heap.cpp_sec21
2086
}
2028
}
2087
#endif // USE(CF)
2029
#endif // USE(CF)
2088
2030
2031
void Heap::notifyIsSafeToCollect()
2032
{
2033
    m_isSafeToCollect = true;
2034
    if (Options::collectContinuously())
2035
        collectAsync();
2036
}
2037
2089
} // namespace JSC
2038
} // namespace JSC
- Source/JavaScriptCore/heap/Heap.h -21 / +18 lines
Lines 22-27 Source/JavaScriptCore/heap/Heap.h_sec1
22
#pragma once
22
#pragma once
23
23
24
#include "ArrayBuffer.h"
24
#include "ArrayBuffer.h"
25
#include "CellState.h"
25
#include "CollectionScope.h"
26
#include "CollectionScope.h"
26
#include "GCIncomingRefCountedSet.h"
27
#include "GCIncomingRefCountedSet.h"
27
#include "HandleSet.h"
28
#include "HandleSet.h"
Lines 35-41 Source/JavaScriptCore/heap/Heap.h_sec2
35
#include "MarkedSpace.h"
36
#include "MarkedSpace.h"
36
#include "MutatorState.h"
37
#include "MutatorState.h"
37
#include "Options.h"
38
#include "Options.h"
38
#include "SlotVisitor.h"
39
#include "StructureIDTable.h"
39
#include "StructureIDTable.h"
40
#include "TinyBloomFilter.h"
40
#include "TinyBloomFilter.h"
41
#include "UnconditionalFinalizer.h"
41
#include "UnconditionalFinalizer.h"
Lines 70-76 class JITStubRoutineSet; Source/JavaScriptCore/heap/Heap.h_sec3
70
class JSCell;
70
class JSCell;
71
class JSValue;
71
class JSValue;
72
class LLIntOffsetsExtractor;
72
class LLIntOffsetsExtractor;
73
class MarkStackArray;
73
class MarkedArgumentBuffer;
74
class MarkedArgumentBuffer;
75
class SlotVisitor;
74
class StopIfNecessaryTimer;
76
class StopIfNecessaryTimer;
75
class VM;
77
class VM;
76
78
Lines 129-135 public: Source/JavaScriptCore/heap/Heap.h_sec4
129
    MarkedSpace& objectSpace() { return m_objectSpace; }
131
    MarkedSpace& objectSpace() { return m_objectSpace; }
130
    MachineThreads& machineThreads() { return m_machineThreads; }
132
    MachineThreads& machineThreads() { return m_machineThreads; }
131
133
132
    const SlotVisitor& slotVisitor() const { return m_slotVisitor; }
134
    SlotVisitor& collectorSlotVisitor() { return *m_collectorSlotVisitor; }
135
    MarkStackArray& mutatorMarkStack() { return *m_mutatorMarkStack; }
133
136
134
    JS_EXPORT_PRIVATE GCActivityCallback* fullActivityCallback();
137
    JS_EXPORT_PRIVATE GCActivityCallback* fullActivityCallback();
135
    JS_EXPORT_PRIVATE GCActivityCallback* edenActivityCallback();
138
    JS_EXPORT_PRIVATE GCActivityCallback* edenActivityCallback();
Lines 168-174 public: Source/JavaScriptCore/heap/Heap.h_sec5
168
    JS_EXPORT_PRIVATE void addFinalizer(JSCell*, Finalizer);
171
    JS_EXPORT_PRIVATE void addFinalizer(JSCell*, Finalizer);
169
    void addExecutable(ExecutableBase*);
172
    void addExecutable(ExecutableBase*);
170
173
171
    void notifyIsSafeToCollect() { m_isSafeToCollect = true; }
174
    void notifyIsSafeToCollect();
172
    bool isSafeToCollect() const { return m_isSafeToCollect; }
175
    bool isSafeToCollect() const { return m_isSafeToCollect; }
173
176
174
    JS_EXPORT_PRIVATE bool isHeapSnapshotting() const;
177
    JS_EXPORT_PRIVATE bool isHeapSnapshotting() const;
Lines 203-213 public: Source/JavaScriptCore/heap/Heap.h_sec6
203
    // call both of these functions: Calling only one may trigger catastropic
206
    // call both of these functions: Calling only one may trigger catastropic
204
    // memory growth.
207
    // memory growth.
205
    void reportExtraMemoryAllocated(size_t);
208
    void reportExtraMemoryAllocated(size_t);
206
    JS_EXPORT_PRIVATE void reportExtraMemoryVisited(CellState oldState, size_t);
209
    JS_EXPORT_PRIVATE void reportExtraMemoryVisited(size_t);
207
210
208
#if ENABLE(RESOURCE_USAGE)
211
#if ENABLE(RESOURCE_USAGE)
209
    // Use this API to report the subset of extra memory that lives outside this process.
212
    // Use this API to report the subset of extra memory that lives outside this process.
210
    JS_EXPORT_PRIVATE void reportExternalMemoryVisited(CellState oldState, size_t);
213
    JS_EXPORT_PRIVATE void reportExternalMemoryVisited(size_t);
211
    size_t externalMemorySize() { return m_externalMemorySize; }
214
    size_t externalMemorySize() { return m_externalMemorySize; }
212
#endif
215
#endif
213
216
Lines 391-396 private: Source/JavaScriptCore/heap/Heap.h_sec7
391
    void stopTheWorld();
394
    void stopTheWorld();
392
    void resumeTheWorld();
395
    void resumeTheWorld();
393
    
396
    
397
    class ResumeTheWorldScope;
398
    friend class ResumeTheWorldScope;
399
    
394
    void stopTheMutator();
400
    void stopTheMutator();
395
    void resumeTheMutator();
401
    void resumeTheMutator();
396
    
402
    
Lines 422-451 private: Source/JavaScriptCore/heap/Heap.h_sec8
422
    
428
    
423
    void suspendCompilerThreads();
429
    void suspendCompilerThreads();
424
    void willStartCollection(Optional<CollectionScope>);
430
    void willStartCollection(Optional<CollectionScope>);
425
    void flushOldStructureIDTables();
426
    void flushWriteBarrierBuffer();
431
    void flushWriteBarrierBuffer();
427
    void stopAllocation();
428
    void prepareForMarking();
432
    void prepareForMarking();
429
    
433
    
430
    void markRoots(double gcStartTime);
434
    void markToFixpoint(double gcStartTime);
431
    void gatherStackRoots(ConservativeRoots&);
435
    void gatherStackRoots(ConservativeRoots&);
432
    void gatherJSStackRoots(ConservativeRoots&);
436
    void gatherJSStackRoots(ConservativeRoots&);
433
    void gatherScratchBufferRoots(ConservativeRoots&);
437
    void gatherScratchBufferRoots(ConservativeRoots&);
434
    void beginMarking();
438
    void beginMarking();
435
    void visitExternalRememberedSet();
436
    void visitSmallStrings();
437
    void visitConservativeRoots(ConservativeRoots&);
439
    void visitConservativeRoots(ConservativeRoots&);
438
    void visitCompilerWorklistWeakReferences();
440
    void visitCompilerWorklistWeakReferences();
439
    void removeDeadCompilerWorklistEntries();
441
    void removeDeadCompilerWorklistEntries();
440
    void visitProtectedObjects(HeapRootVisitor&);
442
    void markToFixpoint(HeapRootVisitor&);
441
    void visitArgumentBuffers(HeapRootVisitor&);
442
    void visitException(HeapRootVisitor&);
443
    void visitStrongHandles(HeapRootVisitor&);
444
    void visitHandleStack(HeapRootVisitor&);
445
    void visitSamplingProfiler();
446
    void visitShadowChicken();
447
    void traceCodeBlocksAndJITStubRoutines();
448
    void visitWeakHandles(HeapRootVisitor&);
449
    void updateObjectCounts(double gcStartTime);
443
    void updateObjectCounts(double gcStartTime);
450
    void endMarking();
444
    void endMarking();
451
445
Lines 517-523 private: Source/JavaScriptCore/heap/Heap.h_sec9
517
511
518
    MachineThreads m_machineThreads;
512
    MachineThreads m_machineThreads;
519
    
513
    
520
    SlotVisitor m_slotVisitor;
514
    std::unique_ptr<SlotVisitor> m_collectorSlotVisitor;
515
    std::unique_ptr<MarkStackArray> m_mutatorMarkStack;
521
516
522
    // We pool the slot visitors used by parallel marking threads. It's useful to be able to
517
    // We pool the slot visitors used by parallel marking threads. It's useful to be able to
523
    // enumerate over them, and it's useful to have them cache some small amount of memory from
518
    // enumerate over them, and it's useful to have them cache some small amount of memory from
Lines 571-577 private: Source/JavaScriptCore/heap/Heap.h_sec10
571
566
572
    Lock m_markingMutex;
567
    Lock m_markingMutex;
573
    Condition m_markingConditionVariable;
568
    Condition m_markingConditionVariable;
574
    MarkStackArray m_sharedMarkStack;
569
    std::unique_ptr<MarkStackArray> m_sharedCollectorMarkStack;
570
    std::unique_ptr<MarkStackArray> m_sharedMutatorMarkStack;
575
    unsigned m_numberOfActiveParallelMarkers { 0 };
571
    unsigned m_numberOfActiveParallelMarkers { 0 };
576
    unsigned m_numberOfWaitingParallelMarkers { 0 };
572
    unsigned m_numberOfWaitingParallelMarkers { 0 };
577
    bool m_parallelMarkersShouldExit { false };
573
    bool m_parallelMarkersShouldExit { false };
Lines 599-604 private: Source/JavaScriptCore/heap/Heap.h_sec11
599
    static const unsigned mutatorWaitingBit = 1u << 5u; // Allows the mutator to use this as a condition variable.
595
    static const unsigned mutatorWaitingBit = 1u << 5u; // Allows the mutator to use this as a condition variable.
600
    Atomic<unsigned> m_worldState;
596
    Atomic<unsigned> m_worldState;
601
    bool m_collectorBelievesThatTheWorldIsStopped { false };
597
    bool m_collectorBelievesThatTheWorldIsStopped { false };
598
    MonotonicTime m_stopTime;
602
    
599
    
603
    Deque<Optional<CollectionScope>> m_requests;
600
    Deque<Optional<CollectionScope>> m_requests;
604
    Ticket m_lastServedTicket { 0 };
601
    Ticket m_lastServedTicket { 0 };
- Source/JavaScriptCore/heap/MarkStack.cpp -1 / +29 lines
Lines 1-5 Source/JavaScriptCore/heap/MarkStack.cpp_sec1
1
/*
1
/*
2
 * Copyright (C) 2009, 2011, 2015 Apple Inc. All rights reserved.
2
 * Copyright (C) 2009-2016 Apple Inc. All rights reserved.
3
 *
3
 *
4
 * Redistribution and use in source and binary forms, with or without
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
5
 * modification, are permitted provided that the following conditions
Lines 36-41 MarkStackArray::MarkStackArray() Source/JavaScriptCore/heap/MarkStack.cpp_sec2
36
{
36
{
37
}
37
}
38
38
39
void MarkStackArray::transferTo(MarkStackArray& other)
40
{
41
    RELEASE_ASSERT(this != &other);
42
    
43
    // Remove our head and the head of the other list.
44
    GCArraySegment<const JSCell*>* myHead = m_segments.removeHead();
45
    GCArraySegment<const JSCell*>* otherHead = other.m_segments.removeHead();
46
    m_numberOfSegments--;
47
    other.m_numberOfSegments--;
48
    
49
    other.m_segments.append(m_segments);
50
    
51
    other.m_numberOfSegments += m_numberOfSegments;
52
    m_numberOfSegments = 0;
53
    
54
    // Put the original heads back in their places.
55
    m_segments.push(myHead);
56
    other.m_segments.push(otherHead);
57
    m_numberOfSegments++;
58
    other.m_numberOfSegments++;
59
    
60
    while (!isEmpty()) {
61
        refill();
62
        while (canRemoveLast())
63
            other.append(removeLast());
64
    }
65
}
66
39
void MarkStackArray::donateSomeCellsTo(MarkStackArray& other)
67
void MarkStackArray::donateSomeCellsTo(MarkStackArray& other)
40
{
68
{
41
    // Try to donate about 1 / 2 of our cells. To reduce copying costs,
69
    // Try to donate about 1 / 2 of our cells. To reduce copying costs,
- Source/JavaScriptCore/heap/MarkStack.h -3 / +4 lines
Lines 1-5 Source/JavaScriptCore/heap/MarkStack.h_sec1
1
/*
1
/*
2
 * Copyright (C) 2009, 2011 Apple Inc. All rights reserved.
2
 * Copyright (C) 2009-2016 Apple Inc. All rights reserved.
3
 *
3
 *
4
 * Redistribution and use in source and binary forms, with or without
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
5
 * modification, are permitted provided that the following conditions
Lines 35-42 class MarkStackArray : public GCSegmente Source/JavaScriptCore/heap/MarkStack.h_sec2
35
public:
35
public:
36
    MarkStackArray();
36
    MarkStackArray();
37
37
38
    void donateSomeCellsTo(MarkStackArray& other);
38
    void transferTo(MarkStackArray&);
39
    void stealSomeCellsFrom(MarkStackArray& other, size_t idleThreadCount);
39
    void donateSomeCellsTo(MarkStackArray&);
40
    void stealSomeCellsFrom(MarkStackArray&, size_t idleThreadCount);
40
};
41
};
41
42
42
} // namespace JSC
43
} // namespace JSC
- Source/JavaScriptCore/heap/MarkedAllocator.cpp -1 lines
Lines 137-143 void* MarkedAllocator::allocateIn(Marked Source/JavaScriptCore/heap/MarkedAllocator.cpp_sec1
137
void* MarkedAllocator::tryAllocateIn(MarkedBlock::Handle* block)
137
void* MarkedAllocator::tryAllocateIn(MarkedBlock::Handle* block)
138
{
138
{
139
    ASSERT(block);
139
    ASSERT(block);
140
    ASSERT(!block->hasAnyNewlyAllocated());
141
    ASSERT(!block->isFreeListed());
140
    ASSERT(!block->isFreeListed());
142
    
141
    
143
    FreeList freeList = block->sweep(MarkedBlock::Handle::SweepToFreeList);
142
    FreeList freeList = block->sweep(MarkedBlock::Handle::SweepToFreeList);
- Source/JavaScriptCore/heap/MarkedBlock.cpp -20 / +22 lines
Lines 82-87 MarkedBlock::MarkedBlock(VM& vm, Handle& Source/JavaScriptCore/heap/MarkedBlock.cpp_sec1
82
    , m_handle(handle)
82
    , m_handle(handle)
83
    , m_vm(&vm)
83
    , m_vm(&vm)
84
{
84
{
85
    if (false)
86
        dataLog(RawPointer(this), ": Allocated.\n");
85
}
87
}
86
88
87
template<MarkedBlock::Handle::EmptyMode emptyMode, MarkedBlock::Handle::SweepMode sweepMode, DestructionMode destructionMode, MarkedBlock::Handle::ScribbleMode scribbleMode, MarkedBlock::Handle::NewlyAllocatedMode newlyAllocatedMode, MarkedBlock::Handle::MarksMode marksMode>
89
template<MarkedBlock::Handle::EmptyMode emptyMode, MarkedBlock::Handle::SweepMode sweepMode, DestructionMode destructionMode, MarkedBlock::Handle::ScribbleMode scribbleMode, MarkedBlock::Handle::NewlyAllocatedMode newlyAllocatedMode, MarkedBlock::Handle::MarksMode marksMode>
Lines 241-264 void MarkedBlock::Handle::setIsFreeListe Source/JavaScriptCore/heap/MarkedBlock.cpp_sec2
241
    m_isFreeListed = true;
243
    m_isFreeListed = true;
242
}
244
}
243
245
244
class SetNewlyAllocatedFunctor : public MarkedBlock::VoidFunctor {
245
public:
246
    SetNewlyAllocatedFunctor(MarkedBlock::Handle* block)
247
        : m_block(block)
248
    {
249
    }
250
251
    IterationStatus operator()(HeapCell* cell, HeapCell::Kind) const
252
    {
253
        ASSERT(MarkedBlock::blockFor(cell) == &m_block->block());
254
        m_block->setNewlyAllocated(cell);
255
        return IterationStatus::Continue;
256
    }
257
258
private:
259
    MarkedBlock::Handle* m_block;
260
};
261
262
void MarkedBlock::Handle::stopAllocating(const FreeList& freeList)
246
void MarkedBlock::Handle::stopAllocating(const FreeList& freeList)
263
{
247
{
264
    if (false)
248
    if (false)
Lines 266-277 void MarkedBlock::Handle::stopAllocating Source/JavaScriptCore/heap/MarkedBlock.cpp_sec3
266
    ASSERT(!allocator()->isAllocated(this));
250
    ASSERT(!allocator()->isAllocated(this));
267
251
268
    if (!isFreeListed()) {
252
    if (!isFreeListed()) {
253
        if (false)
254
            dataLog("There ain't no newly allocated.\n");
269
        // This means that we either didn't use this block at all for allocation since last GC,
255
        // This means that we either didn't use this block at all for allocation since last GC,
270
        // or someone had already done stopAllocating() before.
256
        // or someone had already done stopAllocating() before.
271
        ASSERT(freeList.allocationWillFail());
257
        ASSERT(freeList.allocationWillFail());
272
        return;
258
        return;
273
    }
259
    }
274
    
260
    
261
    if (false)
262
        dataLog("Free list: ", freeList, "\n");
263
    
275
    // Roll back to a coherent state for Heap introspection. Cells newly
264
    // Roll back to a coherent state for Heap introspection. Cells newly
276
    // allocated from our free list are not currently marked, so we need another
265
    // allocated from our free list are not currently marked, so we need another
277
    // way to tell what's live vs dead. 
266
    // way to tell what's live vs dead. 
Lines 279-290 void MarkedBlock::Handle::stopAllocating Source/JavaScriptCore/heap/MarkedBlock.cpp_sec4
279
    m_newlyAllocated.clearAll();
268
    m_newlyAllocated.clearAll();
280
    m_newlyAllocatedVersion = heap()->objectSpace().newlyAllocatedVersion();
269
    m_newlyAllocatedVersion = heap()->objectSpace().newlyAllocatedVersion();
281
270
282
    SetNewlyAllocatedFunctor functor(this);
271
    forEachCell(
283
    forEachCell(functor);
272
        [&] (HeapCell* cell, HeapCell::Kind) -> IterationStatus {
273
            setNewlyAllocated(cell);
274
            return IterationStatus::Continue;
275
        });
284
276
285
    forEachFreeCell(
277
    forEachFreeCell(
286
        freeList,
278
        freeList,
287
        [&] (HeapCell* cell) {
279
        [&] (HeapCell* cell) {
280
            if (false)
281
                dataLog("Free cell: ", RawPointer(cell), "\n");
288
            if (m_attributes.destruction == NeedsDestruction)
282
            if (m_attributes.destruction == NeedsDestruction)
289
                cell->zap();
283
                cell->zap();
290
            clearNewlyAllocated(cell);
284
            clearNewlyAllocated(cell);
Lines 307-316 void MarkedBlock::Handle::lastChanceToFi Source/JavaScriptCore/heap/MarkedBlock.cpp_sec5
307
301
308
FreeList MarkedBlock::Handle::resumeAllocating()
302
FreeList MarkedBlock::Handle::resumeAllocating()
309
{
303
{
304
    if (false)
305
        dataLog(RawPointer(this), ": MarkedBlock::Handle::resumeAllocating!\n");
310
    ASSERT(!allocator()->isAllocated(this));
306
    ASSERT(!allocator()->isAllocated(this));
311
    ASSERT(!isFreeListed());
307
    ASSERT(!isFreeListed());
312
308
313
    if (!hasAnyNewlyAllocated()) {
309
    if (!hasAnyNewlyAllocated()) {
310
        if (false)
311
            dataLog("There ain't no newly allocated.\n");
314
        // This means we had already exhausted the block when we stopped allocation.
312
        // This means we had already exhausted the block when we stopped allocation.
315
        return FreeList();
313
        return FreeList();
316
    }
314
    }
Lines 354-359 void MarkedBlock::aboutToMarkSlow(HeapVe Source/JavaScriptCore/heap/MarkedBlock.cpp_sec6
354
    
352
    
355
    if (handle().allocator()->isAllocated(&handle())
353
    if (handle().allocator()->isAllocated(&handle())
356
        || !marksConveyLivenessDuringMarking(markingVersion)) {
354
        || !marksConveyLivenessDuringMarking(markingVersion)) {
355
        if (false)
356
            dataLog(RawPointer(this), ": Clearing marks without doing anything else.\n");
357
        // We already know that the block is full and is already recognized as such, or that the
357
        // We already know that the block is full and is already recognized as such, or that the
358
        // block did not survive the previous GC. So, we can clear mark bits the old fashioned
358
        // block did not survive the previous GC. So, we can clear mark bits the old fashioned
359
        // way. Note that it's possible for such a block to have newlyAllocated with an up-to-
359
        // way. Note that it's possible for such a block to have newlyAllocated with an up-to-
Lines 362-367 void MarkedBlock::aboutToMarkSlow(HeapVe Source/JavaScriptCore/heap/MarkedBlock.cpp_sec7
362
        // we created a newlyAllocated.
362
        // we created a newlyAllocated.
363
        m_marks.clearAll();
363
        m_marks.clearAll();
364
    } else {
364
    } else {
365
        if (false)
366
            dataLog(RawPointer(this), ": Doing things.\n");
365
        HeapVersion newlyAllocatedVersion = space()->newlyAllocatedVersion();
367
        HeapVersion newlyAllocatedVersion = space()->newlyAllocatedVersion();
366
        if (handle().m_newlyAllocatedVersion == newlyAllocatedVersion) {
368
        if (handle().m_newlyAllocatedVersion == newlyAllocatedVersion) {
367
            // Merge the contents of marked into newlyAllocated. If we get the full set of bits
369
            // Merge the contents of marked into newlyAllocated. If we get the full set of bits
- Source/JavaScriptCore/heap/MarkedSpace.cpp -1 lines
Lines 412-418 void MarkedSpace::prepareForMarking() Source/JavaScriptCore/heap/MarkedSpace.cpp_sec1
412
412
413
void MarkedSpace::resumeAllocating()
413
void MarkedSpace::resumeAllocating()
414
{
414
{
415
    ASSERT(isIterating());
416
    forEachAllocator(
415
    forEachAllocator(
417
        [&] (MarkedAllocator& allocator) -> IterationStatus {
416
        [&] (MarkedAllocator& allocator) -> IterationStatus {
418
            allocator.resumeAllocating();
417
            allocator.resumeAllocating();
- Source/JavaScriptCore/heap/ResumeTheWorldScope.h +24 lines
Line 0 Source/JavaScriptCore/heap/ResumeTheWorldScope.h_sec1
1
/*
2
 * Copyright (C) 2016 Apple Inc. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
- Source/JavaScriptCore/heap/SlotVisitor.cpp -57 / +76 lines
Lines 75-83 static void validate(JSCell* cell) Source/JavaScriptCore/heap/SlotVisitor.cpp_sec1
75
#endif
75
#endif
76
76
77
SlotVisitor::SlotVisitor(Heap& heap)
77
SlotVisitor::SlotVisitor(Heap& heap)
78
    : m_stack()
78
    : m_bytesVisited(0)
79
    , m_bytesVisited(0)
80
    , m_bytesCopied(0)
81
    , m_visitCount(0)
79
    , m_visitCount(0)
82
    , m_isInParallelMode(false)
80
    , m_isInParallelMode(false)
83
    , m_markingVersion(MarkedSpace::initialVersion)
81
    , m_markingVersion(MarkedSpace::initialVersion)
Lines 91-97 SlotVisitor::SlotVisitor(Heap& heap) Source/JavaScriptCore/heap/SlotVisitor.cpp_sec2
91
89
92
SlotVisitor::~SlotVisitor()
90
SlotVisitor::~SlotVisitor()
93
{
91
{
94
    clearMarkStack();
92
    clearMarkStacks();
95
}
93
}
96
94
97
void SlotVisitor::didStartMarking()
95
void SlotVisitor::didStartMarking()
Lines 109-124 void SlotVisitor::didStartMarking() Source/JavaScriptCore/heap/SlotVisitor.cpp_sec3
109
107
110
void SlotVisitor::reset()
108
void SlotVisitor::reset()
111
{
109
{
110
    RELEASE_ASSERT(!m_opaqueRoots.size());
112
    m_bytesVisited = 0;
111
    m_bytesVisited = 0;
113
    m_bytesCopied = 0;
114
    m_visitCount = 0;
112
    m_visitCount = 0;
115
    m_heapSnapshotBuilder = nullptr;
113
    m_heapSnapshotBuilder = nullptr;
116
    ASSERT(!m_currentCell);
114
    RELEASE_ASSERT(!m_currentCell);
117
}
115
}
118
116
119
void SlotVisitor::clearMarkStack()
117
void SlotVisitor::clearMarkStacks()
120
{
118
{
121
    m_stack.clear();
119
    m_collectorStack.clear();
120
    m_mutatorStack.clear();
122
}
121
}
123
122
124
void SlotVisitor::append(ConservativeRoots& conservativeRoots)
123
void SlotVisitor::append(ConservativeRoots& conservativeRoots)
Lines 148-154 void SlotVisitor::appendJSCellOrAuxiliar Source/JavaScriptCore/heap/SlotVisitor.cpp_sec4
148
            return;
147
            return;
149
        }
148
        }
150
        
149
        
151
        jsCell->setCellState(CellState::NewGrey);
150
        jsCell->setCellState(CellState::Grey);
152
151
153
        appendToMarkStack(jsCell);
152
        appendToMarkStack(jsCell);
154
        return;
153
        return;
Lines 210-216 ALWAYS_INLINE void SlotVisitor::setMarke Source/JavaScriptCore/heap/SlotVisitor.cpp_sec5
210
    // Indicate that the object is grey and that:
209
    // Indicate that the object is grey and that:
211
    // In case of concurrent GC: it's the first time it is grey in this GC cycle.
210
    // In case of concurrent GC: it's the first time it is grey in this GC cycle.
212
    // In case of eden collection: it's a new object that became grey rather than an old remembered object.
211
    // In case of eden collection: it's a new object that became grey rather than an old remembered object.
213
    cell->setCellState(CellState::NewGrey);
212
    cell->setCellState(CellState::Grey);
214
    
213
    
215
    appendToMarkStack(container, cell);
214
    appendToMarkStack(container, cell);
216
}
215
}
Lines 228-243 ALWAYS_INLINE void SlotVisitor::appendTo Source/JavaScriptCore/heap/SlotVisitor.cpp_sec6
228
{
227
{
229
    ASSERT(Heap::isMarkedConcurrently(cell));
228
    ASSERT(Heap::isMarkedConcurrently(cell));
230
    ASSERT(!cell->isZapped());
229
    ASSERT(!cell->isZapped());
231
    ASSERT(cell->cellState() == CellState::NewGrey || cell->cellState() == CellState::OldGrey);
230
    ASSERT(cell->cellState() == CellState::Grey);
232
    
231
    
233
    container.noteMarked();
232
    container.noteMarked();
234
    
233
    
235
    // FIXME: These "just work" because the GC resets these fields before doing anything else. But
236
    // that won't be the case when we do concurrent GC.
237
    m_visitCount++;
234
    m_visitCount++;
238
    m_bytesVisited += container.cellSize();
235
    m_bytesVisited += container.cellSize();
239
    
236
    
240
    m_stack.append(cell);
237
    m_collectorStack.append(cell);
238
}
239
240
void SlotVisitor::appendToMutatorMarkStack(const JSCell* cell)
241
{
242
    m_mutatorStack.append(cell);
241
}
243
}
242
244
243
void SlotVisitor::markAuxiliary(const void* base)
245
void SlotVisitor::markAuxiliary(const void* base)
Lines 294-305 ALWAYS_INLINE void SlotVisitor::visitChi Source/JavaScriptCore/heap/SlotVisitor.cpp_sec7
294
    
296
    
295
    SetCurrentCellScope currentCellScope(*this, cell);
297
    SetCurrentCellScope currentCellScope(*this, cell);
296
    
298
    
297
    m_oldCellState = cell->cellState();
299
    // Funny story: it's possible for the object to be black already, if we barrier the object at
298
    
300
    // about the same time that it's marked. That's fine. It's a gnarly and super-rare race. It's
299
    // There is no race here - the cell state cannot change right now. Grey objects can only be
301
    // not clear to me that it would be correct or profitable to bail here if the object is already
300
    // visited by one marking thread. Neither the barrier nor marking will change the state of an
302
    // black.
301
    // object that is already grey.
302
    ASSERT(m_oldCellState == CellState::OldGrey || m_oldCellState == CellState::NewGrey);
303
    
303
    
304
    cell->setCellState(CellState::AnthraciteOrBlack);
304
    cell->setCellState(CellState::AnthraciteOrBlack);
305
    
305
    
Lines 326-348 ALWAYS_INLINE void SlotVisitor::visitChi Source/JavaScriptCore/heap/SlotVisitor.cpp_sec8
326
    }
326
    }
327
    
327
    
328
    if (UNLIKELY(m_heapSnapshotBuilder)) {
328
    if (UNLIKELY(m_heapSnapshotBuilder)) {
329
        if (m_oldCellState == CellState::NewGrey)
329
        if (!m_isVisitingMutatorStack)
330
            m_heapSnapshotBuilder->appendNode(const_cast<JSCell*>(cell));
330
            m_heapSnapshotBuilder->appendNode(const_cast<JSCell*>(cell));
331
    }
331
    }
332
}
332
}
333
333
334
void SlotVisitor::donateKnownParallel()
334
void SlotVisitor::donateKnownParallel(MarkStackArray& from, MarkStackArray& to)
335
{
335
{
336
    // NOTE: Because we re-try often, we can afford to be conservative, and
336
    // NOTE: Because we re-try often, we can afford to be conservative, and
337
    // assume that donating is not profitable.
337
    // assume that donating is not profitable.
338
338
339
    // Avoid locking when a thread reaches a dead end in the object graph.
339
    // Avoid locking when a thread reaches a dead end in the object graph.
340
    if (m_stack.size() < 2)
340
    if (from.size() < 2)
341
        return;
341
        return;
342
342
343
    // If there's already some shared work queued up, be conservative and assume
343
    // If there's already some shared work queued up, be conservative and assume
344
    // that donating more is not profitable.
344
    // that donating more is not profitable.
345
    if (m_heap.m_sharedMarkStack.size())
345
    if (to.size())
346
        return;
346
        return;
347
347
348
    // If we're contending on the lock, be conservative and assume that another
348
    // If we're contending on the lock, be conservative and assume that another
Lines 352-377 void SlotVisitor::donateKnownParallel() Source/JavaScriptCore/heap/SlotVisitor.cpp_sec9
352
        return;
352
        return;
353
353
354
    // Otherwise, assume that a thread will go idle soon, and donate.
354
    // Otherwise, assume that a thread will go idle soon, and donate.
355
    m_stack.donateSomeCellsTo(m_heap.m_sharedMarkStack);
355
    from.donateSomeCellsTo(to);
356
356
357
    m_heap.m_markingConditionVariable.notifyAll();
357
    m_heap.m_markingConditionVariable.notifyAll();
358
}
358
}
359
359
360
void SlotVisitor::drain()
360
void SlotVisitor::donateKnownParallel()
361
{
362
    donateKnownParallel(m_collectorStack, *m_heap.m_sharedCollectorMarkStack);
363
    donateKnownParallel(m_mutatorStack, *m_heap.m_sharedMutatorMarkStack);
364
}
365
366
void SlotVisitor::drain(MonotonicTime timeout)
361
{
367
{
362
    ASSERT(m_isInParallelMode);
368
    ASSERT(m_isInParallelMode);
363
   
369
   
364
    while (!m_stack.isEmpty()) {
370
    while ((!m_collectorStack.isEmpty() || !m_mutatorStack.isEmpty()) && !hasElapsed(timeout)) {
365
        m_stack.refill();
371
        if (!m_collectorStack.isEmpty()) {
366
        for (unsigned countdown = Options::minimumNumberOfScansBetweenRebalance(); m_stack.canRemoveLast() && countdown--;)
372
            m_collectorStack.refill();
367
            visitChildren(m_stack.removeLast());
373
            m_isVisitingMutatorStack = false;
374
            for (unsigned countdown = Options::minimumNumberOfScansBetweenRebalance(); m_collectorStack.canRemoveLast() && countdown--;)
375
                visitChildren(m_collectorStack.removeLast());
376
        } else if (!m_mutatorStack.isEmpty()) {
377
            m_mutatorStack.refill();
378
            // We know for sure that we are visiting objects because of the barrier, not because of
379
            // marking. Marking will visit an object exactly once. The barrier will visit it
380
            // possibly many times, and always after it was already marked.
381
            m_isVisitingMutatorStack = true;
382
            for (unsigned countdown = Options::minimumNumberOfScansBetweenRebalance(); m_mutatorStack.canRemoveLast() && countdown--;)
383
                visitChildren(m_mutatorStack.removeLast());
384
        }
368
        donateKnownParallel();
385
        donateKnownParallel();
369
    }
386
    }
370
    
387
    
371
    mergeOpaqueRootsIfNecessary();
388
    mergeOpaqueRootsIfNecessary();
372
}
389
}
373
390
374
void SlotVisitor::drainFromShared(SharedDrainMode sharedDrainMode)
391
SlotVisitor::SharedDrainResult SlotVisitor::drainFromShared(SharedDrainMode sharedDrainMode, MonotonicTime timeout)
375
{
392
{
376
    ASSERT(m_isInParallelMode);
393
    ASSERT(m_isInParallelMode);
377
    
394
    
Lines 394-439 void SlotVisitor::drainFromShared(Shared Source/JavaScriptCore/heap/SlotVisitor.cpp_sec10
394
                while (true) {
411
                while (true) {
395
                    // Did we reach termination?
412
                    // Did we reach termination?
396
                    if (!m_heap.m_numberOfActiveParallelMarkers
413
                    if (!m_heap.m_numberOfActiveParallelMarkers
397
                        && m_heap.m_sharedMarkStack.isEmpty()) {
414
                        && m_heap.m_sharedCollectorMarkStack->isEmpty()
415
                        && m_heap.m_sharedMutatorMarkStack->isEmpty()) {
398
                        // Let any sleeping slaves know it's time for them to return;
416
                        // Let any sleeping slaves know it's time for them to return;
399
                        m_heap.m_markingConditionVariable.notifyAll();
417
                        m_heap.m_markingConditionVariable.notifyAll();
400
                        return;
418
                        return SharedDrainResult::Done;
401
                    }
419
                    }
402
                    
420
                    
421
                    if (hasElapsed(timeout))
422
                        return SharedDrainResult::TimedOut;
423
                    
403
                    // Is there work to be done?
424
                    // Is there work to be done?
404
                    if (!m_heap.m_sharedMarkStack.isEmpty())
425
                    if (!m_heap.m_sharedCollectorMarkStack->isEmpty()
426
                        || !m_heap.m_sharedMutatorMarkStack->isEmpty())
405
                        break;
427
                        break;
406
                    
428
                    
407
                    // Otherwise wait.
429
                    // Otherwise wait.
408
                    m_heap.m_markingConditionVariable.wait(lock);
430
                    m_heap.m_markingConditionVariable.waitUntil(lock, timeout);
409
                }
431
                }
410
            } else {
432
            } else {
411
                ASSERT(sharedDrainMode == SlaveDrain);
433
                ASSERT(sharedDrainMode == SlaveDrain);
412
                
434
                
413
                // Did we detect termination? If so, let the master know.
435
                // Did we detect termination? If so, let the master know.
414
                if (!m_heap.m_numberOfActiveParallelMarkers
436
                if (!m_heap.m_numberOfActiveParallelMarkers
415
                    && m_heap.m_sharedMarkStack.isEmpty())
437
                    && m_heap.m_sharedCollectorMarkStack->isEmpty()
438
                    && m_heap.m_sharedMutatorMarkStack->isEmpty())
416
                    m_heap.m_markingConditionVariable.notifyAll();
439
                    m_heap.m_markingConditionVariable.notifyAll();
417
440
418
                m_heap.m_markingConditionVariable.wait(
441
                m_heap.m_markingConditionVariable.waitUntil(
419
                    lock,
442
                    lock, timeout,
420
                    [this] {
443
                    [this] {
421
                        return !m_heap.m_sharedMarkStack.isEmpty()
444
                        return !m_heap.m_sharedCollectorMarkStack->isEmpty()
445
                            || !m_heap.m_sharedMutatorMarkStack->isEmpty()
422
                            || m_heap.m_parallelMarkersShouldExit;
446
                            || m_heap.m_parallelMarkersShouldExit;
423
                    });
447
                    });
424
                
448
                
425
                // Is the current phase done? If so, return from this function.
449
                // Is the current phase done? If so, return from this function.
426
                if (m_heap.m_parallelMarkersShouldExit)
450
                if (m_heap.m_parallelMarkersShouldExit)
427
                    return;
451
                    return SharedDrainResult::Done;
452
453
                if (hasElapsed(timeout))
454
                    return SharedDrainResult::TimedOut;
428
            }
455
            }
429
456
430
            m_stack.stealSomeCellsFrom(
457
            m_collectorStack.stealSomeCellsFrom(
431
                m_heap.m_sharedMarkStack, m_heap.m_numberOfWaitingParallelMarkers);
458
                *m_heap.m_sharedCollectorMarkStack, m_heap.m_numberOfWaitingParallelMarkers);
459
            m_mutatorStack.stealSomeCellsFrom(
460
                *m_heap.m_sharedMutatorMarkStack, m_heap.m_numberOfWaitingParallelMarkers);
432
            m_heap.m_numberOfActiveParallelMarkers++;
461
            m_heap.m_numberOfActiveParallelMarkers++;
433
            m_heap.m_numberOfWaitingParallelMarkers--;
462
            m_heap.m_numberOfWaitingParallelMarkers--;
434
        }
463
        }
435
        
464
        
436
        drain();
465
        drain(timeout);
437
    }
466
    }
438
}
467
}
439
468
Lines 453-459 void SlotVisitor::addOpaqueRoot(void* ro Source/JavaScriptCore/heap/SlotVisitor.cpp_sec11
453
bool SlotVisitor::containsOpaqueRoot(void* root) const
482
bool SlotVisitor::containsOpaqueRoot(void* root) const
454
{
483
{
455
    ASSERT(!m_isInParallelMode);
484
    ASSERT(!m_isInParallelMode);
456
    ASSERT(m_opaqueRoots.isEmpty());
457
    return m_heap.m_opaqueRoots.contains(root);
485
    return m_heap.m_opaqueRoots.contains(root);
458
}
486
}
459
487
Lines 467-479 TriState SlotVisitor::containsOpaqueRoot Source/JavaScriptCore/heap/SlotVisitor.cpp_sec12
467
    return MixedTriState;
495
    return MixedTriState;
468
}
496
}
469
497
470
int SlotVisitor::opaqueRootCount()
471
{
472
    ASSERT(!m_isInParallelMode);
473
    ASSERT(m_opaqueRoots.isEmpty());
474
    return m_heap.m_opaqueRoots.size();
475
}
476
477
void SlotVisitor::mergeOpaqueRootsIfNecessary()
498
void SlotVisitor::mergeOpaqueRootsIfNecessary()
478
{
499
{
479
    if (m_opaqueRoots.isEmpty())
500
    if (m_opaqueRoots.isEmpty())
Lines 497-511 void SlotVisitor::donate() Source/JavaScriptCore/heap/SlotVisitor.cpp_sec13
497
    donateKnownParallel();
518
    donateKnownParallel();
498
}
519
}
499
520
500
void SlotVisitor::donateAndDrain()
521
void SlotVisitor::donateAndDrain(MonotonicTime timeout)
501
{
522
{
502
    donate();
523
    donate();
503
    drain();
524
    drain(timeout);
504
}
525
}
505
526
506
void SlotVisitor::mergeOpaqueRoots()
527
void SlotVisitor::mergeOpaqueRoots()
507
{
528
{
508
    ASSERT(!m_opaqueRoots.isEmpty()); // Should only be called when opaque roots are non-empty.
509
    {
529
    {
510
        std::lock_guard<Lock> lock(m_heap.m_opaqueRootsMutex);
530
        std::lock_guard<Lock> lock(m_heap.m_opaqueRootsMutex);
511
        for (auto* root : m_opaqueRoots)
531
        for (auto* root : m_opaqueRoots)
Lines 526-535 void SlotVisitor::finalizeUnconditionalF Source/JavaScriptCore/heap/SlotVisitor.cpp_sec14
526
        m_heap.m_unconditionalFinalizers.removeNext()->finalizeUnconditionally();
546
        m_heap.m_unconditionalFinalizers.removeNext()->finalizeUnconditionally();
527
}
547
}
528
548
529
void SlotVisitor::dump(PrintStream&) const
549
void SlotVisitor::dump(PrintStream& out) const
530
{
550
{
531
    for (const JSCell* cell : markStack())
551
    out.print("Collector: [", pointerListDump(collectorMarkStack()), "], Mutator: [", pointerListDump(mutatorMarkStack()), "]");
532
        dataLog(*cell, "\n");
533
}
552
}
534
553
535
} // namespace JSC
554
} // namespace JSC
- Source/JavaScriptCore/heap/SlotVisitor.h -14 / +20 lines
Lines 29-34 Source/JavaScriptCore/heap/SlotVisitor.h_sec1
29
#include "HandleTypes.h"
29
#include "HandleTypes.h"
30
#include "MarkStack.h"
30
#include "MarkStack.h"
31
#include "OpaqueRootSet.h"
31
#include "OpaqueRootSet.h"
32
#include <wtf/MonotonicTime.h>
32
33
33
namespace JSC {
34
namespace JSC {
34
35
Lines 57-65 public: Source/JavaScriptCore/heap/SlotVisitor.h_sec2
57
    SlotVisitor(Heap&);
58
    SlotVisitor(Heap&);
58
    ~SlotVisitor();
59
    ~SlotVisitor();
59
60
60
    MarkStackArray& markStack() { return m_stack; }
61
    MarkStackArray& collectorMarkStack() { return m_collectorStack; }
61
    const MarkStackArray& markStack() const { return m_stack; }
62
    MarkStackArray& mutatorMarkStack() { return m_mutatorStack; }
62
63
    const MarkStackArray& collectorMarkStack() const { return m_collectorStack; }
64
    const MarkStackArray& mutatorMarkStack() const { return m_mutatorStack; }
65
    
63
    VM& vm();
66
    VM& vm();
64
    const VM& vm() const;
67
    const VM& vm() const;
65
    Heap* heap() const;
68
    Heap* heap() const;
Lines 84-107 public: Source/JavaScriptCore/heap/SlotVisitor.h_sec3
84
    JS_EXPORT_PRIVATE void addOpaqueRoot(void*);
87
    JS_EXPORT_PRIVATE void addOpaqueRoot(void*);
85
    JS_EXPORT_PRIVATE bool containsOpaqueRoot(void*) const;
88
    JS_EXPORT_PRIVATE bool containsOpaqueRoot(void*) const;
86
    TriState containsOpaqueRootTriState(void*) const;
89
    TriState containsOpaqueRootTriState(void*) const;
87
    int opaqueRootCount();
88
90
89
    bool isEmpty() { return m_stack.isEmpty(); }
91
    bool isEmpty() { return m_collectorStack.isEmpty() && m_mutatorStack.isEmpty(); }
90
92
91
    void didStartMarking();
93
    void didStartMarking();
92
    void reset();
94
    void reset();
93
    void clearMarkStack();
95
    void clearMarkStacks();
94
96
95
    size_t bytesVisited() const { return m_bytesVisited; }
97
    size_t bytesVisited() const { return m_bytesVisited; }
96
    size_t bytesCopied() const { return m_bytesCopied; }
97
    size_t visitCount() const { return m_visitCount; }
98
    size_t visitCount() const { return m_visitCount; }
98
99
99
    void donate();
100
    void donate();
100
    void drain();
101
    void drain(MonotonicTime timeout = MonotonicTime::infinity());
101
    void donateAndDrain();
102
    void donateAndDrain(MonotonicTime timeout = MonotonicTime::infinity());
102
    
103
    
103
    enum SharedDrainMode { SlaveDrain, MasterDrain };
104
    enum SharedDrainMode { SlaveDrain, MasterDrain };
104
    void drainFromShared(SharedDrainMode);
105
    enum class SharedDrainResult { Done, TimedOut };
106
    SharedDrainResult drainFromShared(SharedDrainMode, MonotonicTime timeout = MonotonicTime::infinity());
105
107
106
    void harvestWeakReferences();
108
    void harvestWeakReferences();
107
    void finalizeUnconditionalFinalizers();
109
    void finalizeUnconditionalFinalizers();
Lines 124-129 public: Source/JavaScriptCore/heap/SlotVisitor.h_sec4
124
    
126
    
125
    HeapVersion markingVersion() const { return m_markingVersion; }
127
    HeapVersion markingVersion() const { return m_markingVersion; }
126
128
129
    void mergeOpaqueRootsIfNecessary();
130
127
private:
131
private:
128
    friend class ParallelModeEnabler;
132
    friend class ParallelModeEnabler;
129
    
133
    
Lines 141-161 private: Source/JavaScriptCore/heap/SlotVisitor.h_sec5
141
    template<typename ContainerType>
145
    template<typename ContainerType>
142
    void appendToMarkStack(ContainerType&, JSCell*);
146
    void appendToMarkStack(ContainerType&, JSCell*);
143
    
147
    
148
    void appendToMutatorMarkStack(const JSCell*);
149
    
144
    void noteLiveAuxiliaryCell(HeapCell*);
150
    void noteLiveAuxiliaryCell(HeapCell*);
145
    
151
    
146
    JS_EXPORT_PRIVATE void mergeOpaqueRoots();
152
    JS_EXPORT_PRIVATE void mergeOpaqueRoots();
147
    void mergeOpaqueRootsIfNecessary();
148
    void mergeOpaqueRootsIfProfitable();
153
    void mergeOpaqueRootsIfProfitable();
149
154
150
    void visitChildren(const JSCell*);
155
    void visitChildren(const JSCell*);
151
    
156
    
152
    void donateKnownParallel();
157
    void donateKnownParallel();
158
    void donateKnownParallel(MarkStackArray& from, MarkStackArray& to);
153
159
154
    MarkStackArray m_stack;
160
    MarkStackArray m_collectorStack;
161
    MarkStackArray m_mutatorStack;
155
    OpaqueRootSet m_opaqueRoots; // Handle-owning data structures not visible to the garbage collector.
162
    OpaqueRootSet m_opaqueRoots; // Handle-owning data structures not visible to the garbage collector.
156
    
163
    
157
    size_t m_bytesVisited;
164
    size_t m_bytesVisited;
158
    size_t m_bytesCopied;
159
    size_t m_visitCount;
165
    size_t m_visitCount;
160
    bool m_isInParallelMode;
166
    bool m_isInParallelMode;
161
    
167
    
Lines 165-171 private: Source/JavaScriptCore/heap/SlotVisitor.h_sec6
165
171
166
    HeapSnapshotBuilder* m_heapSnapshotBuilder { nullptr };
172
    HeapSnapshotBuilder* m_heapSnapshotBuilder { nullptr };
167
    JSCell* m_currentCell { nullptr };
173
    JSCell* m_currentCell { nullptr };
168
    CellState m_oldCellState;
174
    bool m_isVisitingMutatorStack { false };
169
175
170
public:
176
public:
171
#if !ASSERT_DISABLED
177
#if !ASSERT_DISABLED
- Source/JavaScriptCore/heap/SlotVisitorInlines.h -2 / +4 lines
Lines 105-117 inline void SlotVisitor::addUnconditiona Source/JavaScriptCore/heap/SlotVisitorInlines.h_sec1
105
105
106
inline void SlotVisitor::reportExtraMemoryVisited(size_t size)
106
inline void SlotVisitor::reportExtraMemoryVisited(size_t size)
107
{
107
{
108
    heap()->reportExtraMemoryVisited(m_oldCellState, size);
108
    if (!m_isVisitingMutatorStack)
109
        heap()->reportExtraMemoryVisited(size);
109
}
110
}
110
111
111
#if ENABLE(RESOURCE_USAGE)
112
#if ENABLE(RESOURCE_USAGE)
112
inline void SlotVisitor::reportExternalMemoryVisited(size_t size)
113
inline void SlotVisitor::reportExternalMemoryVisited(size_t size)
113
{
114
{
114
    heap()->reportExternalMemoryVisited(m_oldCellState, size);
115
    if (!m_isVisitingMutatorStack)
116
        heap()->reportExternalMemoryVisited(size);
115
}
117
}
116
#endif
118
#endif
117
119
- Source/JavaScriptCore/runtime/JSCell.h +10 lines
Lines 167-172 public: Source/JavaScriptCore/runtime/JSCell.h_sec1
167
    CellState cellState() const { return m_cellState; }
167
    CellState cellState() const { return m_cellState; }
168
    
168
    
169
    void setCellState(CellState data) const { const_cast<JSCell*>(this)->m_cellState = data; }
169
    void setCellState(CellState data) const { const_cast<JSCell*>(this)->m_cellState = data; }
170
    
171
    bool atomicCompareExchangeCellStateWeakRelaxed(CellState oldState, CellState newState)
172
    {
173
        return WTF::atomicCompareExchangeWeakRelaxed(&m_cellState, oldState, newState);
174
    }
175
176
    CellState atomicCompareExchangeCellStateStrong(CellState oldState, CellState newState)
177
    {
178
        return WTF::atomicCompareExchangeStrong(&m_cellState, oldState, newState);
179
    }
170
180
171
    static ptrdiff_t structureIDOffset()
181
    static ptrdiff_t structureIDOffset()
172
    {
182
    {
- Source/JavaScriptCore/runtime/JSCellInlines.h -4 / +7 lines
Lines 201-211 inline void JSCell::setStructure(VM& vm, Source/JavaScriptCore/runtime/JSCellInlines.h_sec1
201
    ASSERT(!this->structure()
201
    ASSERT(!this->structure()
202
        || this->structure()->transitionWatchpointSetHasBeenInvalidated()
202
        || this->structure()->transitionWatchpointSetHasBeenInvalidated()
203
        || Heap::heap(this)->structureIDTable().get(structure->id()) == structure);
203
        || Heap::heap(this)->structureIDTable().get(structure->id()) == structure);
204
    vm.heap.writeBarrier(this, structure);
205
    m_structureID = structure->id();
204
    m_structureID = structure->id();
206
    m_flags = structure->typeInfo().inlineTypeFlags();
205
    m_flags = structure->typeInfo().inlineTypeFlags();
207
    m_type = structure->typeInfo().type();
206
    m_type = structure->typeInfo().type();
208
    m_indexingType = structure->indexingType();
207
    m_indexingType = structure->indexingType();
208
    vm.heap.writeBarrier(this, structure);
209
}
209
}
210
210
211
inline const MethodTable* JSCell::methodTable() const
211
inline const MethodTable* JSCell::methodTable() const
Lines 284-292 inline void JSCell::callDestructor(VM& v Source/JavaScriptCore/runtime/JSCellInlines.h_sec2
284
    if (isZapped())
284
    if (isZapped())
285
        return;
285
        return;
286
    ASSERT(structureID());
286
    ASSERT(structureID());
287
    if (inlineTypeFlags() & StructureIsImmortal)
287
    if (inlineTypeFlags() & StructureIsImmortal) {
288
        structure(vm)->classInfo()->methodTable.destroy(this);
288
        Structure* structure = this->structure(vm);
289
    else
289
        const ClassInfo* classInfo = structure->classInfo();
290
        MethodTable::DestroyFunctionPtr destroy = classInfo->methodTable.destroy;
291
        destroy(this);
292
    } else
290
        jsCast<JSDestructibleObject*>(this)->classInfo()->methodTable.destroy(this);
293
        jsCast<JSDestructibleObject*>(this)->classInfo()->methodTable.destroy(this);
291
    zap();
294
    zap();
292
}
295
}
- Source/JavaScriptCore/runtime/Options.h +2 lines
Lines 184-189 typedef const char* optionString; Source/JavaScriptCore/runtime/Options.h_sec1
184
    v(bool, verboseSanitizeStack, false, Normal, nullptr) \
184
    v(bool, verboseSanitizeStack, false, Normal, nullptr) \
185
    v(bool, useGenerationalGC, true, Normal, nullptr) \
185
    v(bool, useGenerationalGC, true, Normal, nullptr) \
186
    v(bool, useConcurrentBarriers, true, Normal, nullptr) \
186
    v(bool, useConcurrentBarriers, true, Normal, nullptr) \
187
    v(bool, useConcurrentGC, false, Normal, nullptr) \
188
    v(bool, collectContinuously, false, Normal, nullptr) \
187
    v(bool, forceFencedBarrier, false, Normal, nullptr) \
189
    v(bool, forceFencedBarrier, false, Normal, nullptr) \
188
    v(bool, scribbleFreeCells, false, Normal, nullptr) \
190
    v(bool, scribbleFreeCells, false, Normal, nullptr) \
189
    v(double, sizeClassProgression, 1.4, Normal, nullptr) \
191
    v(double, sizeClassProgression, 1.4, Normal, nullptr) \
- Source/WTF/wtf/ListDump.h -2 / +3 lines
Lines 177-186 ListDumpInContext<T, U> listDumpInContex Source/WTF/wtf/ListDump.h_sec1
177
} // namespace WTF
177
} // namespace WTF
178
178
179
using WTF::listDump;
179
using WTF::listDump;
180
using WTF::sortedListDump;
180
using WTF::listDumpInContext;
181
using WTF::mapDump;
181
using WTF::mapDump;
182
using WTF::pointerListDump;
183
using WTF::sortedListDump;
182
using WTF::sortedMapDump;
184
using WTF::sortedMapDump;
183
using WTF::listDumpInContext;
184
185
185
#endif // ListDump_h
186
#endif // ListDump_h
186
187
- Source/WTF/wtf/TimeWithDynamicClockType.cpp +14 lines
Lines 29-34 Source/WTF/wtf/TimeWithDynamicClockType.cpp_sec1
29
#include "Condition.h"
29
#include "Condition.h"
30
#include "Lock.h"
30
#include "Lock.h"
31
#include "PrintStream.h"
31
#include "PrintStream.h"
32
#include <cfloat>
33
#include <cmath>
34
#include <wtf/DataLog.h>
32
35
33
namespace WTF {
36
namespace WTF {
34
37
Lines 128-133 void sleep(const TimeWithDynamicClockTyp Source/WTF/wtf/TimeWithDynamicClockType.cpp_sec2
128
    fakeCondition.waitUntil(fakeLock, time);
131
    fakeCondition.waitUntil(fakeLock, time);
129
}
132
}
130
133
134
bool hasElapsed(const TimeWithDynamicClockType& time)
135
{
136
    // Avoid doing now().
137
    if (!(time > time.withSameClockAndRawSeconds(0)))
138
        return true;
139
    if (std::isinf(time.secondsSinceEpoch().value()))
140
        return false;
141
    
142
    return time <= time.nowWithSameClock();
143
}
144
131
} // namespace WTF
145
} // namespace WTF
132
146
133
147
- Source/WTF/wtf/TimeWithDynamicClockType.h +4 lines
Lines 134-141 private: Source/WTF/wtf/TimeWithDynamicClockType.h_sec1
134
134
135
WTF_EXPORT_PRIVATE void sleep(const TimeWithDynamicClockType&);
135
WTF_EXPORT_PRIVATE void sleep(const TimeWithDynamicClockType&);
136
136
137
WTF_EXPORT_PRIVATE bool hasElapsed(const TimeWithDynamicClockType&);
138
137
} // namespace WTF
139
} // namespace WTF
138
140
139
using WTF::TimeWithDynamicClockType;
141
using WTF::TimeWithDynamicClockType;
142
using WTF::hasElapsed;
143
using WTF::sleep;
140
144
141
#endif // WTF_TimeWithDynamicClockType_h
145
#endif // WTF_TimeWithDynamicClockType_h

Return to Bug 164454