1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/base/atomicops.h"
8 #include "src/code-stubs.h"
9 #include "src/compilation-cache.h"
10 #include "src/cpu-profiler.h"
11 #include "src/deoptimizer.h"
12 #include "src/execution.h"
13 #include "src/gdb-jit.h"
14 #include "src/global-handles.h"
15 #include "src/heap-profiler.h"
16 #include "src/ic-inl.h"
17 #include "src/incremental-marking.h"
18 #include "src/mark-compact.h"
19 #include "src/objects-visiting.h"
20 #include "src/objects-visiting-inl.h"
21 #include "src/spaces-inl.h"
22 #include "src/stub-cache.h"
23 #include "src/sweeper-thread.h"
29 const char* Marking::kWhiteBitPattern = "00";
30 const char* Marking::kBlackBitPattern = "10";
31 const char* Marking::kGreyBitPattern = "11";
32 const char* Marking::kImpossibleBitPattern = "01";
35 // -------------------------------------------------------------------------
36 // MarkCompactCollector
38 MarkCompactCollector::MarkCompactCollector(Heap* heap) : // NOLINT
42 sweep_precisely_(false),
43 reduce_memory_footprint_(false),
44 abort_incremental_marking_(false),
45 marking_parity_(ODD_MARKING_PARITY),
47 was_marked_incrementally_(false),
48 sweeping_pending_(false),
49 pending_sweeper_jobs_semaphore_(0),
50 sequential_sweeping_(false),
52 migration_slots_buffer_(NULL),
55 have_code_to_deoptimize_(false) { }
58 class VerifyMarkingVisitor: public ObjectVisitor {
60 explicit VerifyMarkingVisitor(Heap* heap) : heap_(heap) {}
62 void VisitPointers(Object** start, Object** end) {
63 for (Object** current = start; current < end; current++) {
64 if ((*current)->IsHeapObject()) {
65 HeapObject* object = HeapObject::cast(*current);
66 CHECK(heap_->mark_compact_collector()->IsMarked(object));
71 void VisitEmbeddedPointer(RelocInfo* rinfo) {
72 ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
73 if (!rinfo->host()->IsWeakObject(rinfo->target_object())) {
74 Object* p = rinfo->target_object();
79 void VisitCell(RelocInfo* rinfo) {
80 Code* code = rinfo->host();
81 ASSERT(rinfo->rmode() == RelocInfo::CELL);
82 if (!code->IsWeakObject(rinfo->target_cell())) {
83 ObjectVisitor::VisitCell(rinfo);
92 static void VerifyMarking(Heap* heap, Address bottom, Address top) {
93 VerifyMarkingVisitor visitor(heap);
95 Address next_object_must_be_here_or_later = bottom;
97 for (Address current = bottom;
99 current += kPointerSize) {
100 object = HeapObject::FromAddress(current);
101 if (MarkCompactCollector::IsMarked(object)) {
102 CHECK(current >= next_object_must_be_here_or_later);
103 object->Iterate(&visitor);
104 next_object_must_be_here_or_later = current + object->Size();
110 static void VerifyMarking(NewSpace* space) {
111 Address end = space->top();
112 NewSpacePageIterator it(space->bottom(), end);
113 // The bottom position is at the start of its page. Allows us to use
114 // page->area_start() as start of range on all pages.
115 CHECK_EQ(space->bottom(),
116 NewSpacePage::FromAddress(space->bottom())->area_start());
117 while (it.has_next()) {
118 NewSpacePage* page = it.next();
119 Address limit = it.has_next() ? page->area_end() : end;
120 CHECK(limit == end || !page->Contains(end));
121 VerifyMarking(space->heap(), page->area_start(), limit);
126 static void VerifyMarking(PagedSpace* space) {
127 PageIterator it(space);
129 while (it.has_next()) {
131 VerifyMarking(space->heap(), p->area_start(), p->area_end());
136 static void VerifyMarking(Heap* heap) {
137 VerifyMarking(heap->old_pointer_space());
138 VerifyMarking(heap->old_data_space());
139 VerifyMarking(heap->code_space());
140 VerifyMarking(heap->cell_space());
141 VerifyMarking(heap->property_cell_space());
142 VerifyMarking(heap->map_space());
143 VerifyMarking(heap->new_space());
145 VerifyMarkingVisitor visitor(heap);
147 LargeObjectIterator it(heap->lo_space());
148 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
149 if (MarkCompactCollector::IsMarked(obj)) {
150 obj->Iterate(&visitor);
154 heap->IterateStrongRoots(&visitor, VISIT_ONLY_STRONG);
158 class VerifyEvacuationVisitor: public ObjectVisitor {
160 void VisitPointers(Object** start, Object** end) {
161 for (Object** current = start; current < end; current++) {
162 if ((*current)->IsHeapObject()) {
163 HeapObject* object = HeapObject::cast(*current);
164 CHECK(!MarkCompactCollector::IsOnEvacuationCandidate(object));
171 static void VerifyEvacuation(Address bottom, Address top) {
172 VerifyEvacuationVisitor visitor;
174 Address next_object_must_be_here_or_later = bottom;
176 for (Address current = bottom;
178 current += kPointerSize) {
179 object = HeapObject::FromAddress(current);
180 if (MarkCompactCollector::IsMarked(object)) {
181 CHECK(current >= next_object_must_be_here_or_later);
182 object->Iterate(&visitor);
183 next_object_must_be_here_or_later = current + object->Size();
189 static void VerifyEvacuation(NewSpace* space) {
190 NewSpacePageIterator it(space->bottom(), space->top());
191 VerifyEvacuationVisitor visitor;
193 while (it.has_next()) {
194 NewSpacePage* page = it.next();
195 Address current = page->area_start();
196 Address limit = it.has_next() ? page->area_end() : space->top();
197 CHECK(limit == space->top() || !page->Contains(space->top()));
198 while (current < limit) {
199 HeapObject* object = HeapObject::FromAddress(current);
200 object->Iterate(&visitor);
201 current += object->Size();
207 static void VerifyEvacuation(PagedSpace* space) {
208 // TODO(hpayer): Bring back VerifyEvacuation for parallel-concurrently
210 if ((FLAG_concurrent_sweeping || FLAG_parallel_sweeping) &&
211 space->was_swept_conservatively()) return;
212 PageIterator it(space);
214 while (it.has_next()) {
216 if (p->IsEvacuationCandidate()) continue;
217 VerifyEvacuation(p->area_start(), p->area_end());
222 static void VerifyEvacuation(Heap* heap) {
223 VerifyEvacuation(heap->old_pointer_space());
224 VerifyEvacuation(heap->old_data_space());
225 VerifyEvacuation(heap->code_space());
226 VerifyEvacuation(heap->cell_space());
227 VerifyEvacuation(heap->property_cell_space());
228 VerifyEvacuation(heap->map_space());
229 VerifyEvacuation(heap->new_space());
231 VerifyEvacuationVisitor visitor;
232 heap->IterateStrongRoots(&visitor, VISIT_ALL);
234 #endif // VERIFY_HEAP
238 class VerifyNativeContextSeparationVisitor: public ObjectVisitor {
240 VerifyNativeContextSeparationVisitor() : current_native_context_(NULL) {}
242 void VisitPointers(Object** start, Object** end) {
243 for (Object** current = start; current < end; current++) {
244 if ((*current)->IsHeapObject()) {
245 HeapObject* object = HeapObject::cast(*current);
246 if (object->IsString()) continue;
247 switch (object->map()->instance_type()) {
248 case JS_FUNCTION_TYPE:
249 CheckContext(JSFunction::cast(object)->context());
251 case JS_GLOBAL_PROXY_TYPE:
252 CheckContext(JSGlobalProxy::cast(object)->native_context());
254 case JS_GLOBAL_OBJECT_TYPE:
255 case JS_BUILTINS_OBJECT_TYPE:
256 CheckContext(GlobalObject::cast(object)->native_context());
262 VisitPointer(HeapObject::RawField(object, JSObject::kMapOffset));
265 VisitPointer(HeapObject::RawField(object, Map::kPrototypeOffset));
266 VisitPointer(HeapObject::RawField(object, Map::kConstructorOffset));
268 case FIXED_ARRAY_TYPE:
269 if (object->IsContext()) {
270 CheckContext(object);
272 FixedArray* array = FixedArray::cast(object);
273 int length = array->length();
274 // Set array length to zero to prevent cycles while iterating
275 // over array bodies, this is easier than intrusive marking.
276 array->set_length(0);
278 FIXED_ARRAY_TYPE, FixedArray::SizeFor(length), this);
279 array->set_length(length);
285 case TYPE_FEEDBACK_INFO_TYPE:
286 object->Iterate(this);
288 case DECLARED_ACCESSOR_INFO_TYPE:
289 case EXECUTABLE_ACCESSOR_INFO_TYPE:
290 case BYTE_ARRAY_TYPE:
291 case CALL_HANDLER_INFO_TYPE:
293 case FIXED_DOUBLE_ARRAY_TYPE:
294 case HEAP_NUMBER_TYPE:
295 case INTERCEPTOR_INFO_TYPE:
298 case SHARED_FUNCTION_INFO_TYPE:
308 void CheckContext(Object* context) {
309 if (!context->IsContext()) return;
310 Context* native_context = Context::cast(context)->native_context();
311 if (current_native_context_ == NULL) {
312 current_native_context_ = native_context;
314 CHECK_EQ(current_native_context_, native_context);
318 Context* current_native_context_;
322 static void VerifyNativeContextSeparation(Heap* heap) {
323 HeapObjectIterator it(heap->code_space());
325 for (Object* object = it.Next(); object != NULL; object = it.Next()) {
326 VerifyNativeContextSeparationVisitor visitor;
327 Code::cast(object)->CodeIterateBody(&visitor);
333 void MarkCompactCollector::SetUp() {
334 free_list_old_data_space_.Reset(new FreeList(heap_->old_data_space()));
335 free_list_old_pointer_space_.Reset(new FreeList(heap_->old_pointer_space()));
339 void MarkCompactCollector::TearDown() {
344 void MarkCompactCollector::AddEvacuationCandidate(Page* p) {
345 p->MarkEvacuationCandidate();
346 evacuation_candidates_.Add(p);
350 static void TraceFragmentation(PagedSpace* space) {
351 int number_of_pages = space->CountTotalPages();
352 intptr_t reserved = (number_of_pages * space->AreaSize());
353 intptr_t free = reserved - space->SizeOfObjects();
354 PrintF("[%s]: %d pages, %d (%.1f%%) free\n",
355 AllocationSpaceName(space->identity()),
357 static_cast<int>(free),
358 static_cast<double>(free) * 100 / reserved);
362 bool MarkCompactCollector::StartCompaction(CompactionMode mode) {
364 ASSERT(evacuation_candidates_.length() == 0);
366 #ifdef ENABLE_GDB_JIT_INTERFACE
367 // If GDBJIT interface is active disable compaction.
368 if (FLAG_gdbjit) return false;
371 CollectEvacuationCandidates(heap()->old_pointer_space());
372 CollectEvacuationCandidates(heap()->old_data_space());
374 if (FLAG_compact_code_space &&
375 (mode == NON_INCREMENTAL_COMPACTION ||
376 FLAG_incremental_code_compaction)) {
377 CollectEvacuationCandidates(heap()->code_space());
378 } else if (FLAG_trace_fragmentation) {
379 TraceFragmentation(heap()->code_space());
382 if (FLAG_trace_fragmentation) {
383 TraceFragmentation(heap()->map_space());
384 TraceFragmentation(heap()->cell_space());
385 TraceFragmentation(heap()->property_cell_space());
388 heap()->old_pointer_space()->EvictEvacuationCandidatesFromFreeLists();
389 heap()->old_data_space()->EvictEvacuationCandidatesFromFreeLists();
390 heap()->code_space()->EvictEvacuationCandidatesFromFreeLists();
392 compacting_ = evacuation_candidates_.length() > 0;
399 void MarkCompactCollector::CollectGarbage() {
400 // Make sure that Prepare() has been called. The individual steps below will
401 // update the state as they proceed.
402 ASSERT(state_ == PREPARE_GC);
405 ASSERT(heap_->incremental_marking()->IsStopped());
407 if (FLAG_collect_maps) ClearNonLiveReferences();
409 ClearWeakCollections();
412 if (FLAG_verify_heap) {
413 VerifyMarking(heap_);
420 if (FLAG_verify_native_context_separation) {
421 VerifyNativeContextSeparation(heap_);
426 if (heap()->weak_embedded_objects_verification_enabled()) {
427 VerifyWeakEmbeddedObjectsInCode();
429 if (FLAG_collect_maps && FLAG_omit_map_checks_for_leaf_maps) {
430 VerifyOmittedMapChecks();
436 if (marking_parity_ == EVEN_MARKING_PARITY) {
437 marking_parity_ = ODD_MARKING_PARITY;
439 ASSERT(marking_parity_ == ODD_MARKING_PARITY);
440 marking_parity_ = EVEN_MARKING_PARITY;
448 void MarkCompactCollector::VerifyMarkbitsAreClean(PagedSpace* space) {
449 PageIterator it(space);
451 while (it.has_next()) {
453 CHECK(p->markbits()->IsClean());
454 CHECK_EQ(0, p->LiveBytes());
459 void MarkCompactCollector::VerifyMarkbitsAreClean(NewSpace* space) {
460 NewSpacePageIterator it(space->bottom(), space->top());
462 while (it.has_next()) {
463 NewSpacePage* p = it.next();
464 CHECK(p->markbits()->IsClean());
465 CHECK_EQ(0, p->LiveBytes());
470 void MarkCompactCollector::VerifyMarkbitsAreClean() {
471 VerifyMarkbitsAreClean(heap_->old_pointer_space());
472 VerifyMarkbitsAreClean(heap_->old_data_space());
473 VerifyMarkbitsAreClean(heap_->code_space());
474 VerifyMarkbitsAreClean(heap_->cell_space());
475 VerifyMarkbitsAreClean(heap_->property_cell_space());
476 VerifyMarkbitsAreClean(heap_->map_space());
477 VerifyMarkbitsAreClean(heap_->new_space());
479 LargeObjectIterator it(heap_->lo_space());
480 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
481 MarkBit mark_bit = Marking::MarkBitFrom(obj);
482 CHECK(Marking::IsWhite(mark_bit));
483 CHECK_EQ(0, Page::FromAddress(obj->address())->LiveBytes());
488 void MarkCompactCollector::VerifyWeakEmbeddedObjectsInCode() {
489 HeapObjectIterator code_iterator(heap()->code_space());
490 for (HeapObject* obj = code_iterator.Next();
492 obj = code_iterator.Next()) {
493 Code* code = Code::cast(obj);
494 if (!code->is_optimized_code() && !code->is_weak_stub()) continue;
495 if (WillBeDeoptimized(code)) continue;
496 code->VerifyEmbeddedObjectsDependency();
501 void MarkCompactCollector::VerifyOmittedMapChecks() {
502 HeapObjectIterator iterator(heap()->map_space());
503 for (HeapObject* obj = iterator.Next();
505 obj = iterator.Next()) {
506 Map* map = Map::cast(obj);
507 map->VerifyOmittedMapChecks();
510 #endif // VERIFY_HEAP
513 static void ClearMarkbitsInPagedSpace(PagedSpace* space) {
514 PageIterator it(space);
516 while (it.has_next()) {
517 Bitmap::Clear(it.next());
522 static void ClearMarkbitsInNewSpace(NewSpace* space) {
523 NewSpacePageIterator it(space->ToSpaceStart(), space->ToSpaceEnd());
525 while (it.has_next()) {
526 Bitmap::Clear(it.next());
531 void MarkCompactCollector::ClearMarkbits() {
532 ClearMarkbitsInPagedSpace(heap_->code_space());
533 ClearMarkbitsInPagedSpace(heap_->map_space());
534 ClearMarkbitsInPagedSpace(heap_->old_pointer_space());
535 ClearMarkbitsInPagedSpace(heap_->old_data_space());
536 ClearMarkbitsInPagedSpace(heap_->cell_space());
537 ClearMarkbitsInPagedSpace(heap_->property_cell_space());
538 ClearMarkbitsInNewSpace(heap_->new_space());
540 LargeObjectIterator it(heap_->lo_space());
541 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
542 MarkBit mark_bit = Marking::MarkBitFrom(obj);
544 mark_bit.Next().Clear();
545 Page::FromAddress(obj->address())->ResetProgressBar();
546 Page::FromAddress(obj->address())->ResetLiveBytes();
551 class MarkCompactCollector::SweeperTask : public v8::Task {
553 SweeperTask(Heap* heap, PagedSpace* space)
554 : heap_(heap), space_(space) {}
556 virtual ~SweeperTask() {}
559 // v8::Task overrides.
560 virtual void Run() V8_OVERRIDE {
561 heap_->mark_compact_collector()->SweepInParallel(space_);
562 heap_->mark_compact_collector()->pending_sweeper_jobs_semaphore_.Signal();
568 DISALLOW_COPY_AND_ASSIGN(SweeperTask);
572 void MarkCompactCollector::StartSweeperThreads() {
573 ASSERT(free_list_old_pointer_space_.get()->IsEmpty());
574 ASSERT(free_list_old_data_space_.get()->IsEmpty());
575 sweeping_pending_ = true;
576 for (int i = 0; i < isolate()->num_sweeper_threads(); i++) {
577 isolate()->sweeper_threads()[i]->StartSweeping();
579 if (FLAG_job_based_sweeping) {
580 V8::GetCurrentPlatform()->CallOnBackgroundThread(
581 new SweeperTask(heap(), heap()->old_data_space()),
582 v8::Platform::kShortRunningTask);
583 V8::GetCurrentPlatform()->CallOnBackgroundThread(
584 new SweeperTask(heap(), heap()->old_pointer_space()),
585 v8::Platform::kShortRunningTask);
590 void MarkCompactCollector::WaitUntilSweepingCompleted() {
591 ASSERT(sweeping_pending_ == true);
592 for (int i = 0; i < isolate()->num_sweeper_threads(); i++) {
593 isolate()->sweeper_threads()[i]->WaitForSweeperThread();
595 if (FLAG_job_based_sweeping) {
596 // Wait twice for both jobs.
597 pending_sweeper_jobs_semaphore_.Wait();
598 pending_sweeper_jobs_semaphore_.Wait();
600 ParallelSweepSpacesComplete();
601 sweeping_pending_ = false;
602 RefillFreeList(heap()->paged_space(OLD_DATA_SPACE));
603 RefillFreeList(heap()->paged_space(OLD_POINTER_SPACE));
604 heap()->paged_space(OLD_DATA_SPACE)->ResetUnsweptFreeBytes();
605 heap()->paged_space(OLD_POINTER_SPACE)->ResetUnsweptFreeBytes();
609 bool MarkCompactCollector::IsSweepingCompleted() {
610 for (int i = 0; i < isolate()->num_sweeper_threads(); i++) {
611 if (!isolate()->sweeper_threads()[i]->SweepingCompleted()) {
615 if (FLAG_job_based_sweeping) {
616 if (!pending_sweeper_jobs_semaphore_.WaitFor(TimeDelta::FromSeconds(0))) {
619 pending_sweeper_jobs_semaphore_.Signal();
625 void MarkCompactCollector::RefillFreeList(PagedSpace* space) {
628 if (space == heap()->old_pointer_space()) {
629 free_list = free_list_old_pointer_space_.get();
630 } else if (space == heap()->old_data_space()) {
631 free_list = free_list_old_data_space_.get();
633 // Any PagedSpace might invoke RefillFreeLists, so we need to make sure
634 // to only refill them for old data and pointer spaces.
638 intptr_t freed_bytes = space->free_list()->Concatenate(free_list);
639 space->AddToAccountingStats(freed_bytes);
640 space->DecrementUnsweptFreeBytes(freed_bytes);
644 bool MarkCompactCollector::AreSweeperThreadsActivated() {
645 return isolate()->sweeper_threads() != NULL || FLAG_job_based_sweeping;
649 bool MarkCompactCollector::IsConcurrentSweepingInProgress() {
650 return sweeping_pending_;
654 void Marking::TransferMark(Address old_start, Address new_start) {
655 // This is only used when resizing an object.
656 ASSERT(MemoryChunk::FromAddress(old_start) ==
657 MemoryChunk::FromAddress(new_start));
659 if (!heap_->incremental_marking()->IsMarking()) return;
661 // If the mark doesn't move, we don't check the color of the object.
662 // It doesn't matter whether the object is black, since it hasn't changed
663 // size, so the adjustment to the live data count will be zero anyway.
664 if (old_start == new_start) return;
666 MarkBit new_mark_bit = MarkBitFrom(new_start);
667 MarkBit old_mark_bit = MarkBitFrom(old_start);
670 ObjectColor old_color = Color(old_mark_bit);
673 if (Marking::IsBlack(old_mark_bit)) {
674 old_mark_bit.Clear();
675 ASSERT(IsWhite(old_mark_bit));
676 Marking::MarkBlack(new_mark_bit);
678 } else if (Marking::IsGrey(old_mark_bit)) {
679 old_mark_bit.Clear();
680 old_mark_bit.Next().Clear();
681 ASSERT(IsWhite(old_mark_bit));
682 heap_->incremental_marking()->WhiteToGreyAndPush(
683 HeapObject::FromAddress(new_start), new_mark_bit);
684 heap_->incremental_marking()->RestartIfNotMarking();
688 ObjectColor new_color = Color(new_mark_bit);
689 ASSERT(new_color == old_color);
694 const char* AllocationSpaceName(AllocationSpace space) {
696 case NEW_SPACE: return "NEW_SPACE";
697 case OLD_POINTER_SPACE: return "OLD_POINTER_SPACE";
698 case OLD_DATA_SPACE: return "OLD_DATA_SPACE";
699 case CODE_SPACE: return "CODE_SPACE";
700 case MAP_SPACE: return "MAP_SPACE";
701 case CELL_SPACE: return "CELL_SPACE";
702 case PROPERTY_CELL_SPACE:
703 return "PROPERTY_CELL_SPACE";
704 case LO_SPACE: return "LO_SPACE";
713 // Returns zero for pages that have so little fragmentation that it is not
714 // worth defragmenting them. Otherwise a positive integer that gives an
715 // estimate of fragmentation on an arbitrary scale.
716 static int FreeListFragmentation(PagedSpace* space, Page* p) {
717 // If page was not swept then there are no free list items on it.
718 if (!p->WasSwept()) {
719 if (FLAG_trace_fragmentation) {
720 PrintF("%p [%s]: %d bytes live (unswept)\n",
721 reinterpret_cast<void*>(p),
722 AllocationSpaceName(space->identity()),
728 PagedSpace::SizeStats sizes;
729 space->ObtainFreeListStatistics(p, &sizes);
732 intptr_t ratio_threshold;
733 intptr_t area_size = space->AreaSize();
734 if (space->identity() == CODE_SPACE) {
735 ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 /
737 ratio_threshold = 10;
739 ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 /
741 ratio_threshold = 15;
744 if (FLAG_trace_fragmentation) {
745 PrintF("%p [%s]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
746 reinterpret_cast<void*>(p),
747 AllocationSpaceName(space->identity()),
748 static_cast<int>(sizes.small_size_),
749 static_cast<double>(sizes.small_size_ * 100) /
751 static_cast<int>(sizes.medium_size_),
752 static_cast<double>(sizes.medium_size_ * 100) /
754 static_cast<int>(sizes.large_size_),
755 static_cast<double>(sizes.large_size_ * 100) /
757 static_cast<int>(sizes.huge_size_),
758 static_cast<double>(sizes.huge_size_ * 100) /
760 (ratio > ratio_threshold) ? "[fragmented]" : "");
763 if (FLAG_always_compact && sizes.Total() != area_size) {
767 if (ratio <= ratio_threshold) return 0; // Not fragmented.
769 return static_cast<int>(ratio - ratio_threshold);
773 void MarkCompactCollector::CollectEvacuationCandidates(PagedSpace* space) {
774 ASSERT(space->identity() == OLD_POINTER_SPACE ||
775 space->identity() == OLD_DATA_SPACE ||
776 space->identity() == CODE_SPACE);
778 static const int kMaxMaxEvacuationCandidates = 1000;
779 int number_of_pages = space->CountTotalPages();
780 int max_evacuation_candidates =
781 static_cast<int>(std::sqrt(number_of_pages / 2.0) + 1);
783 if (FLAG_stress_compaction || FLAG_always_compact) {
784 max_evacuation_candidates = kMaxMaxEvacuationCandidates;
789 Candidate() : fragmentation_(0), page_(NULL) { }
790 Candidate(int f, Page* p) : fragmentation_(f), page_(p) { }
792 int fragmentation() { return fragmentation_; }
793 Page* page() { return page_; }
800 enum CompactionMode {
802 REDUCE_MEMORY_FOOTPRINT
805 CompactionMode mode = COMPACT_FREE_LISTS;
807 intptr_t reserved = number_of_pages * space->AreaSize();
808 intptr_t over_reserved = reserved - space->SizeOfObjects();
809 static const intptr_t kFreenessThreshold = 50;
811 if (reduce_memory_footprint_ && over_reserved >= space->AreaSize()) {
812 // If reduction of memory footprint was requested, we are aggressive
813 // about choosing pages to free. We expect that half-empty pages
814 // are easier to compact so slightly bump the limit.
815 mode = REDUCE_MEMORY_FOOTPRINT;
816 max_evacuation_candidates += 2;
820 if (over_reserved > reserved / 3 && over_reserved >= 2 * space->AreaSize()) {
821 // If over-usage is very high (more than a third of the space), we
822 // try to free all mostly empty pages. We expect that almost empty
823 // pages are even easier to compact so bump the limit even more.
824 mode = REDUCE_MEMORY_FOOTPRINT;
825 max_evacuation_candidates *= 2;
828 if (FLAG_trace_fragmentation && mode == REDUCE_MEMORY_FOOTPRINT) {
829 PrintF("Estimated over reserved memory: %.1f / %.1f MB (threshold %d), "
830 "evacuation candidate limit: %d\n",
831 static_cast<double>(over_reserved) / MB,
832 static_cast<double>(reserved) / MB,
833 static_cast<int>(kFreenessThreshold),
834 max_evacuation_candidates);
837 intptr_t estimated_release = 0;
839 Candidate candidates[kMaxMaxEvacuationCandidates];
841 max_evacuation_candidates =
842 Min(kMaxMaxEvacuationCandidates, max_evacuation_candidates);
845 int fragmentation = 0;
846 Candidate* least = NULL;
848 PageIterator it(space);
849 if (it.has_next()) it.next(); // Never compact the first page.
851 while (it.has_next()) {
853 p->ClearEvacuationCandidate();
855 if (FLAG_stress_compaction) {
856 unsigned int counter = space->heap()->ms_count();
857 uintptr_t page_number = reinterpret_cast<uintptr_t>(p) >> kPageSizeBits;
858 if ((counter & 1) == (page_number & 1)) fragmentation = 1;
859 } else if (mode == REDUCE_MEMORY_FOOTPRINT) {
860 // Don't try to release too many pages.
861 if (estimated_release >= over_reserved) {
865 intptr_t free_bytes = 0;
867 if (!p->WasSwept()) {
868 free_bytes = (p->area_size() - p->LiveBytes());
870 PagedSpace::SizeStats sizes;
871 space->ObtainFreeListStatistics(p, &sizes);
872 free_bytes = sizes.Total();
875 int free_pct = static_cast<int>(free_bytes * 100) / p->area_size();
877 if (free_pct >= kFreenessThreshold) {
878 estimated_release += free_bytes;
879 fragmentation = free_pct;
884 if (FLAG_trace_fragmentation) {
885 PrintF("%p [%s]: %d (%.2f%%) free %s\n",
886 reinterpret_cast<void*>(p),
887 AllocationSpaceName(space->identity()),
888 static_cast<int>(free_bytes),
889 static_cast<double>(free_bytes * 100) / p->area_size(),
890 (fragmentation > 0) ? "[fragmented]" : "");
893 fragmentation = FreeListFragmentation(space, p);
896 if (fragmentation != 0) {
897 if (count < max_evacuation_candidates) {
898 candidates[count++] = Candidate(fragmentation, p);
901 for (int i = 0; i < max_evacuation_candidates; i++) {
903 candidates[i].fragmentation() < least->fragmentation()) {
904 least = candidates + i;
908 if (least->fragmentation() < fragmentation) {
909 *least = Candidate(fragmentation, p);
916 for (int i = 0; i < count; i++) {
917 AddEvacuationCandidate(candidates[i].page());
920 if (count > 0 && FLAG_trace_fragmentation) {
921 PrintF("Collected %d evacuation candidates for space %s\n",
923 AllocationSpaceName(space->identity()));
928 void MarkCompactCollector::AbortCompaction() {
930 int npages = evacuation_candidates_.length();
931 for (int i = 0; i < npages; i++) {
932 Page* p = evacuation_candidates_[i];
933 slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
934 p->ClearEvacuationCandidate();
935 p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
938 evacuation_candidates_.Rewind(0);
939 invalidated_code_.Rewind(0);
941 ASSERT_EQ(0, evacuation_candidates_.length());
945 void MarkCompactCollector::Prepare(GCTracer* tracer) {
946 was_marked_incrementally_ = heap()->incremental_marking()->IsMarking();
948 // Rather than passing the tracer around we stash it in a static member
953 ASSERT(state_ == IDLE);
957 ASSERT(!FLAG_never_compact || !FLAG_always_compact);
959 if (IsConcurrentSweepingInProgress()) {
960 // Instead of waiting we could also abort the sweeper threads here.
961 WaitUntilSweepingCompleted();
964 // Clear marking bits if incremental marking is aborted.
965 if (was_marked_incrementally_ && abort_incremental_marking_) {
966 heap()->incremental_marking()->Abort();
969 was_marked_incrementally_ = false;
972 // Don't start compaction if we are in the middle of incremental
973 // marking cycle. We did not collect any slots.
974 if (!FLAG_never_compact && !was_marked_incrementally_) {
975 StartCompaction(NON_INCREMENTAL_COMPACTION);
978 PagedSpaces spaces(heap());
979 for (PagedSpace* space = spaces.next();
981 space = spaces.next()) {
982 space->PrepareForMarkCompact();
986 if (!was_marked_incrementally_ && FLAG_verify_heap) {
987 VerifyMarkbitsAreClean();
993 void MarkCompactCollector::Finish() {
995 ASSERT(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS);
998 // The stub cache is not traversed during GC; clear the cache to
999 // force lazy re-initialization of it. This must be done after the
1000 // GC, because it relies on the new address of certain old space
1001 // objects (empty string, illegal builtin).
1002 isolate()->stub_cache()->Clear();
1004 if (have_code_to_deoptimize_) {
1005 // Some code objects were marked for deoptimization during the GC.
1006 Deoptimizer::DeoptimizeMarkedCode(isolate());
1007 have_code_to_deoptimize_ = false;
1012 // -------------------------------------------------------------------------
1013 // Phase 1: tracing and marking live objects.
1014 // before: all objects are in normal state.
1015 // after: a live object's map pointer is marked as '00'.
1017 // Marking all live objects in the heap as part of mark-sweep or mark-compact
1018 // collection. Before marking, all objects are in their normal state. After
1019 // marking, live objects' map pointers are marked indicating that the object
1020 // has been found reachable.
1022 // The marking algorithm is a (mostly) depth-first (because of possible stack
1023 // overflow) traversal of the graph of objects reachable from the roots. It
1024 // uses an explicit stack of pointers rather than recursion. The young
1025 // generation's inactive ('from') space is used as a marking stack. The
1026 // objects in the marking stack are the ones that have been reached and marked
1027 // but their children have not yet been visited.
1029 // The marking stack can overflow during traversal. In that case, we set an
1030 // overflow flag. When the overflow flag is set, we continue marking objects
1031 // reachable from the objects on the marking stack, but no longer push them on
1032 // the marking stack. Instead, we mark them as both marked and overflowed.
1033 // When the stack is in the overflowed state, objects marked as overflowed
1034 // have been reached and marked but their children have not been visited yet.
1035 // After emptying the marking stack, we clear the overflow flag and traverse
1036 // the heap looking for objects marked as overflowed, push them on the stack,
1037 // and continue with marking. This process repeats until all reachable
1038 // objects have been marked.
1040 void CodeFlusher::ProcessJSFunctionCandidates() {
1041 Code* lazy_compile =
1042 isolate_->builtins()->builtin(Builtins::kCompileUnoptimized);
1043 Object* undefined = isolate_->heap()->undefined_value();
1045 JSFunction* candidate = jsfunction_candidates_head_;
1046 JSFunction* next_candidate;
1047 while (candidate != NULL) {
1048 next_candidate = GetNextCandidate(candidate);
1049 ClearNextCandidate(candidate, undefined);
1051 SharedFunctionInfo* shared = candidate->shared();
1053 Code* code = shared->code();
1054 MarkBit code_mark = Marking::MarkBitFrom(code);
1055 if (!code_mark.Get()) {
1056 if (FLAG_trace_code_flushing && shared->is_compiled()) {
1057 PrintF("[code-flushing clears: ");
1058 shared->ShortPrint();
1059 PrintF(" - age: %d]\n", code->GetAge());
1061 shared->set_code(lazy_compile);
1062 candidate->set_code(lazy_compile);
1064 candidate->set_code(code);
1067 // We are in the middle of a GC cycle so the write barrier in the code
1068 // setter did not record the slot update and we have to do that manually.
1069 Address slot = candidate->address() + JSFunction::kCodeEntryOffset;
1070 Code* target = Code::cast(Code::GetObjectFromEntryAddress(slot));
1071 isolate_->heap()->mark_compact_collector()->
1072 RecordCodeEntrySlot(slot, target);
1074 Object** shared_code_slot =
1075 HeapObject::RawField(shared, SharedFunctionInfo::kCodeOffset);
1076 isolate_->heap()->mark_compact_collector()->
1077 RecordSlot(shared_code_slot, shared_code_slot, *shared_code_slot);
1079 candidate = next_candidate;
1082 jsfunction_candidates_head_ = NULL;
1086 void CodeFlusher::ProcessSharedFunctionInfoCandidates() {
1087 Code* lazy_compile =
1088 isolate_->builtins()->builtin(Builtins::kCompileUnoptimized);
1090 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1091 SharedFunctionInfo* next_candidate;
1092 while (candidate != NULL) {
1093 next_candidate = GetNextCandidate(candidate);
1094 ClearNextCandidate(candidate);
1096 Code* code = candidate->code();
1097 MarkBit code_mark = Marking::MarkBitFrom(code);
1098 if (!code_mark.Get()) {
1099 if (FLAG_trace_code_flushing && candidate->is_compiled()) {
1100 PrintF("[code-flushing clears: ");
1101 candidate->ShortPrint();
1102 PrintF(" - age: %d]\n", code->GetAge());
1104 candidate->set_code(lazy_compile);
1107 Object** code_slot =
1108 HeapObject::RawField(candidate, SharedFunctionInfo::kCodeOffset);
1109 isolate_->heap()->mark_compact_collector()->
1110 RecordSlot(code_slot, code_slot, *code_slot);
1112 candidate = next_candidate;
1115 shared_function_info_candidates_head_ = NULL;
1119 void CodeFlusher::ProcessOptimizedCodeMaps() {
1120 STATIC_ASSERT(SharedFunctionInfo::kEntryLength == 4);
1122 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1123 SharedFunctionInfo* next_holder;
1125 while (holder != NULL) {
1126 next_holder = GetNextCodeMap(holder);
1127 ClearNextCodeMap(holder);
1129 FixedArray* code_map = FixedArray::cast(holder->optimized_code_map());
1130 int new_length = SharedFunctionInfo::kEntriesStart;
1131 int old_length = code_map->length();
1132 for (int i = SharedFunctionInfo::kEntriesStart;
1134 i += SharedFunctionInfo::kEntryLength) {
1136 Code::cast(code_map->get(i + SharedFunctionInfo::kCachedCodeOffset));
1137 if (!Marking::MarkBitFrom(code).Get()) continue;
1139 // Move every slot in the entry.
1140 for (int j = 0; j < SharedFunctionInfo::kEntryLength; j++) {
1141 int dst_index = new_length++;
1142 Object** slot = code_map->RawFieldOfElementAt(dst_index);
1143 Object* object = code_map->get(i + j);
1144 code_map->set(dst_index, object);
1145 if (j == SharedFunctionInfo::kOsrAstIdOffset) {
1146 ASSERT(object->IsSmi());
1148 ASSERT(Marking::IsBlack(
1149 Marking::MarkBitFrom(HeapObject::cast(*slot))));
1150 isolate_->heap()->mark_compact_collector()->
1151 RecordSlot(slot, slot, *slot);
1156 // Trim the optimized code map if entries have been removed.
1157 if (new_length < old_length) {
1158 holder->TrimOptimizedCodeMap(old_length - new_length);
1161 holder = next_holder;
1164 optimized_code_map_holder_head_ = NULL;
1168 void CodeFlusher::EvictCandidate(SharedFunctionInfo* shared_info) {
1169 // Make sure previous flushing decisions are revisited.
1170 isolate_->heap()->incremental_marking()->RecordWrites(shared_info);
1172 if (FLAG_trace_code_flushing) {
1173 PrintF("[code-flushing abandons function-info: ");
1174 shared_info->ShortPrint();
1178 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1179 SharedFunctionInfo* next_candidate;
1180 if (candidate == shared_info) {
1181 next_candidate = GetNextCandidate(shared_info);
1182 shared_function_info_candidates_head_ = next_candidate;
1183 ClearNextCandidate(shared_info);
1185 while (candidate != NULL) {
1186 next_candidate = GetNextCandidate(candidate);
1188 if (next_candidate == shared_info) {
1189 next_candidate = GetNextCandidate(shared_info);
1190 SetNextCandidate(candidate, next_candidate);
1191 ClearNextCandidate(shared_info);
1195 candidate = next_candidate;
1201 void CodeFlusher::EvictCandidate(JSFunction* function) {
1202 ASSERT(!function->next_function_link()->IsUndefined());
1203 Object* undefined = isolate_->heap()->undefined_value();
1205 // Make sure previous flushing decisions are revisited.
1206 isolate_->heap()->incremental_marking()->RecordWrites(function);
1207 isolate_->heap()->incremental_marking()->RecordWrites(function->shared());
1209 if (FLAG_trace_code_flushing) {
1210 PrintF("[code-flushing abandons closure: ");
1211 function->shared()->ShortPrint();
1215 JSFunction* candidate = jsfunction_candidates_head_;
1216 JSFunction* next_candidate;
1217 if (candidate == function) {
1218 next_candidate = GetNextCandidate(function);
1219 jsfunction_candidates_head_ = next_candidate;
1220 ClearNextCandidate(function, undefined);
1222 while (candidate != NULL) {
1223 next_candidate = GetNextCandidate(candidate);
1225 if (next_candidate == function) {
1226 next_candidate = GetNextCandidate(function);
1227 SetNextCandidate(candidate, next_candidate);
1228 ClearNextCandidate(function, undefined);
1232 candidate = next_candidate;
1238 void CodeFlusher::EvictOptimizedCodeMap(SharedFunctionInfo* code_map_holder) {
1239 ASSERT(!FixedArray::cast(code_map_holder->optimized_code_map())->
1240 get(SharedFunctionInfo::kNextMapIndex)->IsUndefined());
1242 // Make sure previous flushing decisions are revisited.
1243 isolate_->heap()->incremental_marking()->RecordWrites(code_map_holder);
1245 if (FLAG_trace_code_flushing) {
1246 PrintF("[code-flushing abandons code-map: ");
1247 code_map_holder->ShortPrint();
1251 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1252 SharedFunctionInfo* next_holder;
1253 if (holder == code_map_holder) {
1254 next_holder = GetNextCodeMap(code_map_holder);
1255 optimized_code_map_holder_head_ = next_holder;
1256 ClearNextCodeMap(code_map_holder);
1258 while (holder != NULL) {
1259 next_holder = GetNextCodeMap(holder);
1261 if (next_holder == code_map_holder) {
1262 next_holder = GetNextCodeMap(code_map_holder);
1263 SetNextCodeMap(holder, next_holder);
1264 ClearNextCodeMap(code_map_holder);
1268 holder = next_holder;
1274 void CodeFlusher::EvictJSFunctionCandidates() {
1275 JSFunction* candidate = jsfunction_candidates_head_;
1276 JSFunction* next_candidate;
1277 while (candidate != NULL) {
1278 next_candidate = GetNextCandidate(candidate);
1279 EvictCandidate(candidate);
1280 candidate = next_candidate;
1282 ASSERT(jsfunction_candidates_head_ == NULL);
1286 void CodeFlusher::EvictSharedFunctionInfoCandidates() {
1287 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1288 SharedFunctionInfo* next_candidate;
1289 while (candidate != NULL) {
1290 next_candidate = GetNextCandidate(candidate);
1291 EvictCandidate(candidate);
1292 candidate = next_candidate;
1294 ASSERT(shared_function_info_candidates_head_ == NULL);
1298 void CodeFlusher::EvictOptimizedCodeMaps() {
1299 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1300 SharedFunctionInfo* next_holder;
1301 while (holder != NULL) {
1302 next_holder = GetNextCodeMap(holder);
1303 EvictOptimizedCodeMap(holder);
1304 holder = next_holder;
1306 ASSERT(optimized_code_map_holder_head_ == NULL);
1310 void CodeFlusher::IteratePointersToFromSpace(ObjectVisitor* v) {
1311 Heap* heap = isolate_->heap();
1313 JSFunction** slot = &jsfunction_candidates_head_;
1314 JSFunction* candidate = jsfunction_candidates_head_;
1315 while (candidate != NULL) {
1316 if (heap->InFromSpace(candidate)) {
1317 v->VisitPointer(reinterpret_cast<Object**>(slot));
1319 candidate = GetNextCandidate(*slot);
1320 slot = GetNextCandidateSlot(*slot);
1325 MarkCompactCollector::~MarkCompactCollector() {
1326 if (code_flusher_ != NULL) {
1327 delete code_flusher_;
1328 code_flusher_ = NULL;
1333 static inline HeapObject* ShortCircuitConsString(Object** p) {
1334 // Optimization: If the heap object pointed to by p is a non-internalized
1335 // cons string whose right substring is HEAP->empty_string, update
1336 // it in place to its left substring. Return the updated value.
1338 // Here we assume that if we change *p, we replace it with a heap object
1339 // (i.e., the left substring of a cons string is always a heap object).
1341 // The check performed is:
1342 // object->IsConsString() && !object->IsInternalizedString() &&
1343 // (ConsString::cast(object)->second() == HEAP->empty_string())
1344 // except the maps for the object and its possible substrings might be
1346 HeapObject* object = HeapObject::cast(*p);
1347 if (!FLAG_clever_optimizations) return object;
1348 Map* map = object->map();
1349 InstanceType type = map->instance_type();
1350 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return object;
1352 Object* second = reinterpret_cast<ConsString*>(object)->second();
1353 Heap* heap = map->GetHeap();
1354 if (second != heap->empty_string()) {
1358 // Since we don't have the object's start, it is impossible to update the
1359 // page dirty marks. Therefore, we only replace the string with its left
1360 // substring when page dirty marks do not change.
1361 Object* first = reinterpret_cast<ConsString*>(object)->first();
1362 if (!heap->InNewSpace(object) && heap->InNewSpace(first)) return object;
1365 return HeapObject::cast(first);
1369 class MarkCompactMarkingVisitor
1370 : public StaticMarkingVisitor<MarkCompactMarkingVisitor> {
1372 static void ObjectStatsVisitBase(StaticVisitorBase::VisitorId id,
1373 Map* map, HeapObject* obj);
1375 static void ObjectStatsCountFixedArray(
1376 FixedArrayBase* fixed_array,
1377 FixedArraySubInstanceType fast_type,
1378 FixedArraySubInstanceType dictionary_type);
1380 template<MarkCompactMarkingVisitor::VisitorId id>
1381 class ObjectStatsTracker {
1383 static inline void Visit(Map* map, HeapObject* obj);
1386 static void Initialize();
1388 INLINE(static void VisitPointer(Heap* heap, Object** p)) {
1389 MarkObjectByPointer(heap->mark_compact_collector(), p, p);
1392 INLINE(static void VisitPointers(Heap* heap, Object** start, Object** end)) {
1393 // Mark all objects pointed to in [start, end).
1394 const int kMinRangeForMarkingRecursion = 64;
1395 if (end - start >= kMinRangeForMarkingRecursion) {
1396 if (VisitUnmarkedObjects(heap, start, end)) return;
1397 // We are close to a stack overflow, so just mark the objects.
1399 MarkCompactCollector* collector = heap->mark_compact_collector();
1400 for (Object** p = start; p < end; p++) {
1401 MarkObjectByPointer(collector, start, p);
1405 // Marks the object black and pushes it on the marking stack.
1406 INLINE(static void MarkObject(Heap* heap, HeapObject* object)) {
1407 MarkBit mark = Marking::MarkBitFrom(object);
1408 heap->mark_compact_collector()->MarkObject(object, mark);
1411 // Marks the object black without pushing it on the marking stack.
1412 // Returns true if object needed marking and false otherwise.
1413 INLINE(static bool MarkObjectWithoutPush(Heap* heap, HeapObject* object)) {
1414 MarkBit mark_bit = Marking::MarkBitFrom(object);
1415 if (!mark_bit.Get()) {
1416 heap->mark_compact_collector()->SetMark(object, mark_bit);
1422 // Mark object pointed to by p.
1423 INLINE(static void MarkObjectByPointer(MarkCompactCollector* collector,
1424 Object** anchor_slot,
1426 if (!(*p)->IsHeapObject()) return;
1427 HeapObject* object = ShortCircuitConsString(p);
1428 collector->RecordSlot(anchor_slot, p, object);
1429 MarkBit mark = Marking::MarkBitFrom(object);
1430 collector->MarkObject(object, mark);
1434 // Visit an unmarked object.
1435 INLINE(static void VisitUnmarkedObject(MarkCompactCollector* collector,
1438 ASSERT(collector->heap()->Contains(obj));
1439 ASSERT(!collector->heap()->mark_compact_collector()->IsMarked(obj));
1441 Map* map = obj->map();
1442 Heap* heap = obj->GetHeap();
1443 MarkBit mark = Marking::MarkBitFrom(obj);
1444 heap->mark_compact_collector()->SetMark(obj, mark);
1445 // Mark the map pointer and the body.
1446 MarkBit map_mark = Marking::MarkBitFrom(map);
1447 heap->mark_compact_collector()->MarkObject(map, map_mark);
1448 IterateBody(map, obj);
1451 // Visit all unmarked objects pointed to by [start, end).
1452 // Returns false if the operation fails (lack of stack space).
1453 INLINE(static bool VisitUnmarkedObjects(Heap* heap,
1456 // Return false is we are close to the stack limit.
1457 StackLimitCheck check(heap->isolate());
1458 if (check.HasOverflowed()) return false;
1460 MarkCompactCollector* collector = heap->mark_compact_collector();
1461 // Visit the unmarked objects.
1462 for (Object** p = start; p < end; p++) {
1464 if (!o->IsHeapObject()) continue;
1465 collector->RecordSlot(start, p, o);
1466 HeapObject* obj = HeapObject::cast(o);
1467 MarkBit mark = Marking::MarkBitFrom(obj);
1468 if (mark.Get()) continue;
1469 VisitUnmarkedObject(collector, obj);
1476 static inline void TrackObjectStatsAndVisit(Map* map, HeapObject* obj);
1478 // Code flushing support.
1480 static const int kRegExpCodeThreshold = 5;
1482 static void UpdateRegExpCodeAgeAndFlush(Heap* heap,
1485 // Make sure that the fixed array is in fact initialized on the RegExp.
1486 // We could potentially trigger a GC when initializing the RegExp.
1487 if (HeapObject::cast(re->data())->map()->instance_type() !=
1488 FIXED_ARRAY_TYPE) return;
1490 // Make sure this is a RegExp that actually contains code.
1491 if (re->TypeTag() != JSRegExp::IRREGEXP) return;
1493 Object* code = re->DataAt(JSRegExp::code_index(is_ascii));
1494 if (!code->IsSmi() &&
1495 HeapObject::cast(code)->map()->instance_type() == CODE_TYPE) {
1496 // Save a copy that can be reinstated if we need the code again.
1497 re->SetDataAt(JSRegExp::saved_code_index(is_ascii), code);
1499 // Saving a copy might create a pointer into compaction candidate
1500 // that was not observed by marker. This might happen if JSRegExp data
1501 // was marked through the compilation cache before marker reached JSRegExp
1503 FixedArray* data = FixedArray::cast(re->data());
1504 Object** slot = data->data_start() + JSRegExp::saved_code_index(is_ascii);
1505 heap->mark_compact_collector()->
1506 RecordSlot(slot, slot, code);
1508 // Set a number in the 0-255 range to guarantee no smi overflow.
1509 re->SetDataAt(JSRegExp::code_index(is_ascii),
1510 Smi::FromInt(heap->sweep_generation() & 0xff));
1511 } else if (code->IsSmi()) {
1512 int value = Smi::cast(code)->value();
1513 // The regexp has not been compiled yet or there was a compilation error.
1514 if (value == JSRegExp::kUninitializedValue ||
1515 value == JSRegExp::kCompilationErrorValue) {
1519 // Check if we should flush now.
1520 if (value == ((heap->sweep_generation() - kRegExpCodeThreshold) & 0xff)) {
1521 re->SetDataAt(JSRegExp::code_index(is_ascii),
1522 Smi::FromInt(JSRegExp::kUninitializedValue));
1523 re->SetDataAt(JSRegExp::saved_code_index(is_ascii),
1524 Smi::FromInt(JSRegExp::kUninitializedValue));
1530 // Works by setting the current sweep_generation (as a smi) in the
1531 // code object place in the data array of the RegExp and keeps a copy
1532 // around that can be reinstated if we reuse the RegExp before flushing.
1533 // If we did not use the code for kRegExpCodeThreshold mark sweep GCs
1534 // we flush the code.
1535 static void VisitRegExpAndFlushCode(Map* map, HeapObject* object) {
1536 Heap* heap = map->GetHeap();
1537 MarkCompactCollector* collector = heap->mark_compact_collector();
1538 if (!collector->is_code_flushing_enabled()) {
1539 VisitJSRegExp(map, object);
1542 JSRegExp* re = reinterpret_cast<JSRegExp*>(object);
1543 // Flush code or set age on both ASCII and two byte code.
1544 UpdateRegExpCodeAgeAndFlush(heap, re, true);
1545 UpdateRegExpCodeAgeAndFlush(heap, re, false);
1546 // Visit the fields of the RegExp, including the updated FixedArray.
1547 VisitJSRegExp(map, object);
1550 static VisitorDispatchTable<Callback> non_count_table_;
1554 void MarkCompactMarkingVisitor::ObjectStatsCountFixedArray(
1555 FixedArrayBase* fixed_array,
1556 FixedArraySubInstanceType fast_type,
1557 FixedArraySubInstanceType dictionary_type) {
1558 Heap* heap = fixed_array->map()->GetHeap();
1559 if (fixed_array->map() != heap->fixed_cow_array_map() &&
1560 fixed_array->map() != heap->fixed_double_array_map() &&
1561 fixed_array != heap->empty_fixed_array()) {
1562 if (fixed_array->IsDictionary()) {
1563 heap->RecordFixedArraySubTypeStats(dictionary_type,
1564 fixed_array->Size());
1566 heap->RecordFixedArraySubTypeStats(fast_type,
1567 fixed_array->Size());
1573 void MarkCompactMarkingVisitor::ObjectStatsVisitBase(
1574 MarkCompactMarkingVisitor::VisitorId id, Map* map, HeapObject* obj) {
1575 Heap* heap = map->GetHeap();
1576 int object_size = obj->Size();
1577 heap->RecordObjectStats(map->instance_type(), object_size);
1578 non_count_table_.GetVisitorById(id)(map, obj);
1579 if (obj->IsJSObject()) {
1580 JSObject* object = JSObject::cast(obj);
1581 ObjectStatsCountFixedArray(object->elements(),
1582 DICTIONARY_ELEMENTS_SUB_TYPE,
1583 FAST_ELEMENTS_SUB_TYPE);
1584 ObjectStatsCountFixedArray(object->properties(),
1585 DICTIONARY_PROPERTIES_SUB_TYPE,
1586 FAST_PROPERTIES_SUB_TYPE);
1591 template<MarkCompactMarkingVisitor::VisitorId id>
1592 void MarkCompactMarkingVisitor::ObjectStatsTracker<id>::Visit(
1593 Map* map, HeapObject* obj) {
1594 ObjectStatsVisitBase(id, map, obj);
1599 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1600 MarkCompactMarkingVisitor::kVisitMap> {
1602 static inline void Visit(Map* map, HeapObject* obj) {
1603 Heap* heap = map->GetHeap();
1604 Map* map_obj = Map::cast(obj);
1605 ASSERT(map->instance_type() == MAP_TYPE);
1606 DescriptorArray* array = map_obj->instance_descriptors();
1607 if (map_obj->owns_descriptors() &&
1608 array != heap->empty_descriptor_array()) {
1609 int fixed_array_size = array->Size();
1610 heap->RecordFixedArraySubTypeStats(DESCRIPTOR_ARRAY_SUB_TYPE,
1613 if (map_obj->HasTransitionArray()) {
1614 int fixed_array_size = map_obj->transitions()->Size();
1615 heap->RecordFixedArraySubTypeStats(TRANSITION_ARRAY_SUB_TYPE,
1618 if (map_obj->has_code_cache()) {
1619 CodeCache* cache = CodeCache::cast(map_obj->code_cache());
1620 heap->RecordFixedArraySubTypeStats(MAP_CODE_CACHE_SUB_TYPE,
1621 cache->default_cache()->Size());
1622 if (!cache->normal_type_cache()->IsUndefined()) {
1623 heap->RecordFixedArraySubTypeStats(
1624 MAP_CODE_CACHE_SUB_TYPE,
1625 FixedArray::cast(cache->normal_type_cache())->Size());
1628 ObjectStatsVisitBase(kVisitMap, map, obj);
1634 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1635 MarkCompactMarkingVisitor::kVisitCode> {
1637 static inline void Visit(Map* map, HeapObject* obj) {
1638 Heap* heap = map->GetHeap();
1639 int object_size = obj->Size();
1640 ASSERT(map->instance_type() == CODE_TYPE);
1641 Code* code_obj = Code::cast(obj);
1642 heap->RecordCodeSubTypeStats(code_obj->kind(), code_obj->GetRawAge(),
1644 ObjectStatsVisitBase(kVisitCode, map, obj);
1650 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1651 MarkCompactMarkingVisitor::kVisitSharedFunctionInfo> {
1653 static inline void Visit(Map* map, HeapObject* obj) {
1654 Heap* heap = map->GetHeap();
1655 SharedFunctionInfo* sfi = SharedFunctionInfo::cast(obj);
1656 if (sfi->scope_info() != heap->empty_fixed_array()) {
1657 heap->RecordFixedArraySubTypeStats(
1658 SCOPE_INFO_SUB_TYPE,
1659 FixedArray::cast(sfi->scope_info())->Size());
1661 ObjectStatsVisitBase(kVisitSharedFunctionInfo, map, obj);
1667 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1668 MarkCompactMarkingVisitor::kVisitFixedArray> {
1670 static inline void Visit(Map* map, HeapObject* obj) {
1671 Heap* heap = map->GetHeap();
1672 FixedArray* fixed_array = FixedArray::cast(obj);
1673 if (fixed_array == heap->string_table()) {
1674 heap->RecordFixedArraySubTypeStats(
1675 STRING_TABLE_SUB_TYPE,
1676 fixed_array->Size());
1678 ObjectStatsVisitBase(kVisitFixedArray, map, obj);
1683 void MarkCompactMarkingVisitor::Initialize() {
1684 StaticMarkingVisitor<MarkCompactMarkingVisitor>::Initialize();
1686 table_.Register(kVisitJSRegExp,
1687 &VisitRegExpAndFlushCode);
1689 if (FLAG_track_gc_object_stats) {
1690 // Copy the visitor table to make call-through possible.
1691 non_count_table_.CopyFrom(&table_);
1692 #define VISITOR_ID_COUNT_FUNCTION(id) \
1693 table_.Register(kVisit##id, ObjectStatsTracker<kVisit##id>::Visit);
1694 VISITOR_ID_LIST(VISITOR_ID_COUNT_FUNCTION)
1695 #undef VISITOR_ID_COUNT_FUNCTION
1700 VisitorDispatchTable<MarkCompactMarkingVisitor::Callback>
1701 MarkCompactMarkingVisitor::non_count_table_;
1704 class CodeMarkingVisitor : public ThreadVisitor {
1706 explicit CodeMarkingVisitor(MarkCompactCollector* collector)
1707 : collector_(collector) {}
1709 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1710 collector_->PrepareThreadForCodeFlushing(isolate, top);
1714 MarkCompactCollector* collector_;
1718 class SharedFunctionInfoMarkingVisitor : public ObjectVisitor {
1720 explicit SharedFunctionInfoMarkingVisitor(MarkCompactCollector* collector)
1721 : collector_(collector) {}
1723 void VisitPointers(Object** start, Object** end) {
1724 for (Object** p = start; p < end; p++) VisitPointer(p);
1727 void VisitPointer(Object** slot) {
1728 Object* obj = *slot;
1729 if (obj->IsSharedFunctionInfo()) {
1730 SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(obj);
1731 MarkBit shared_mark = Marking::MarkBitFrom(shared);
1732 MarkBit code_mark = Marking::MarkBitFrom(shared->code());
1733 collector_->MarkObject(shared->code(), code_mark);
1734 collector_->MarkObject(shared, shared_mark);
1739 MarkCompactCollector* collector_;
1743 void MarkCompactCollector::PrepareThreadForCodeFlushing(Isolate* isolate,
1744 ThreadLocalTop* top) {
1745 for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1746 // Note: for the frame that has a pending lazy deoptimization
1747 // StackFrame::unchecked_code will return a non-optimized code object for
1748 // the outermost function and StackFrame::LookupCode will return
1749 // actual optimized code object.
1750 StackFrame* frame = it.frame();
1751 Code* code = frame->unchecked_code();
1752 MarkBit code_mark = Marking::MarkBitFrom(code);
1753 MarkObject(code, code_mark);
1754 if (frame->is_optimized()) {
1755 MarkCompactMarkingVisitor::MarkInlinedFunctionsCode(heap(),
1756 frame->LookupCode());
1762 void MarkCompactCollector::PrepareForCodeFlushing() {
1763 // Enable code flushing for non-incremental cycles.
1764 if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
1765 EnableCodeFlushing(!was_marked_incrementally_);
1768 // If code flushing is disabled, there is no need to prepare for it.
1769 if (!is_code_flushing_enabled()) return;
1771 // Ensure that empty descriptor array is marked. Method MarkDescriptorArray
1772 // relies on it being marked before any other descriptor array.
1773 HeapObject* descriptor_array = heap()->empty_descriptor_array();
1774 MarkBit descriptor_array_mark = Marking::MarkBitFrom(descriptor_array);
1775 MarkObject(descriptor_array, descriptor_array_mark);
1777 // Make sure we are not referencing the code from the stack.
1778 ASSERT(this == heap()->mark_compact_collector());
1779 PrepareThreadForCodeFlushing(heap()->isolate(),
1780 heap()->isolate()->thread_local_top());
1782 // Iterate the archived stacks in all threads to check if
1783 // the code is referenced.
1784 CodeMarkingVisitor code_marking_visitor(this);
1785 heap()->isolate()->thread_manager()->IterateArchivedThreads(
1786 &code_marking_visitor);
1788 SharedFunctionInfoMarkingVisitor visitor(this);
1789 heap()->isolate()->compilation_cache()->IterateFunctions(&visitor);
1790 heap()->isolate()->handle_scope_implementer()->Iterate(&visitor);
1792 ProcessMarkingDeque();
1796 // Visitor class for marking heap roots.
1797 class RootMarkingVisitor : public ObjectVisitor {
1799 explicit RootMarkingVisitor(Heap* heap)
1800 : collector_(heap->mark_compact_collector()) { }
1802 void VisitPointer(Object** p) {
1803 MarkObjectByPointer(p);
1806 void VisitPointers(Object** start, Object** end) {
1807 for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
1810 // Skip the weak next code link in a code object, which is visited in
1811 // ProcessTopOptimizedFrame.
1812 void VisitNextCodeLink(Object** p) { }
1815 void MarkObjectByPointer(Object** p) {
1816 if (!(*p)->IsHeapObject()) return;
1818 // Replace flat cons strings in place.
1819 HeapObject* object = ShortCircuitConsString(p);
1820 MarkBit mark_bit = Marking::MarkBitFrom(object);
1821 if (mark_bit.Get()) return;
1823 Map* map = object->map();
1825 collector_->SetMark(object, mark_bit);
1827 // Mark the map pointer and body, and push them on the marking stack.
1828 MarkBit map_mark = Marking::MarkBitFrom(map);
1829 collector_->MarkObject(map, map_mark);
1830 MarkCompactMarkingVisitor::IterateBody(map, object);
1832 // Mark all the objects reachable from the map and body. May leave
1833 // overflowed objects in the heap.
1834 collector_->EmptyMarkingDeque();
1837 MarkCompactCollector* collector_;
1841 // Helper class for pruning the string table.
1842 template<bool finalize_external_strings>
1843 class StringTableCleaner : public ObjectVisitor {
1845 explicit StringTableCleaner(Heap* heap)
1846 : heap_(heap), pointers_removed_(0) { }
1848 virtual void VisitPointers(Object** start, Object** end) {
1849 // Visit all HeapObject pointers in [start, end).
1850 for (Object** p = start; p < end; p++) {
1852 if (o->IsHeapObject() &&
1853 !Marking::MarkBitFrom(HeapObject::cast(o)).Get()) {
1854 if (finalize_external_strings) {
1855 ASSERT(o->IsExternalString());
1856 heap_->FinalizeExternalString(String::cast(*p));
1858 pointers_removed_++;
1860 // Set the entry to the_hole_value (as deleted).
1861 *p = heap_->the_hole_value();
1866 int PointersRemoved() {
1867 ASSERT(!finalize_external_strings);
1868 return pointers_removed_;
1873 int pointers_removed_;
1877 typedef StringTableCleaner<false> InternalizedStringTableCleaner;
1878 typedef StringTableCleaner<true> ExternalStringTableCleaner;
1881 // Implementation of WeakObjectRetainer for mark compact GCs. All marked objects
1883 class MarkCompactWeakObjectRetainer : public WeakObjectRetainer {
1885 virtual Object* RetainAs(Object* object) {
1886 if (Marking::MarkBitFrom(HeapObject::cast(object)).Get()) {
1888 } else if (object->IsAllocationSite() &&
1889 !(AllocationSite::cast(object)->IsZombie())) {
1890 // "dead" AllocationSites need to live long enough for a traversal of new
1891 // space. These sites get a one-time reprieve.
1892 AllocationSite* site = AllocationSite::cast(object);
1894 site->GetHeap()->mark_compact_collector()->MarkAllocationSite(site);
1903 // Fill the marking stack with overflowed objects returned by the given
1904 // iterator. Stop when the marking stack is filled or the end of the space
1905 // is reached, whichever comes first.
1907 static void DiscoverGreyObjectsWithIterator(Heap* heap,
1908 MarkingDeque* marking_deque,
1910 // The caller should ensure that the marking stack is initially not full,
1911 // so that we don't waste effort pointlessly scanning for objects.
1912 ASSERT(!marking_deque->IsFull());
1914 Map* filler_map = heap->one_pointer_filler_map();
1915 for (HeapObject* object = it->Next();
1917 object = it->Next()) {
1918 MarkBit markbit = Marking::MarkBitFrom(object);
1919 if ((object->map() != filler_map) && Marking::IsGrey(markbit)) {
1920 Marking::GreyToBlack(markbit);
1921 MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1922 marking_deque->PushBlack(object);
1923 if (marking_deque->IsFull()) return;
1929 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts);
1932 static void DiscoverGreyObjectsOnPage(MarkingDeque* marking_deque,
1934 ASSERT(!marking_deque->IsFull());
1935 ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1936 ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
1937 ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
1938 ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1940 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1941 Address cell_base = it.CurrentCellBase();
1942 MarkBit::CellType* cell = it.CurrentCell();
1944 const MarkBit::CellType current_cell = *cell;
1945 if (current_cell == 0) continue;
1947 MarkBit::CellType grey_objects;
1949 const MarkBit::CellType next_cell = *(cell+1);
1950 grey_objects = current_cell &
1951 ((current_cell >> 1) | (next_cell << (Bitmap::kBitsPerCell - 1)));
1953 grey_objects = current_cell & (current_cell >> 1);
1957 while (grey_objects != 0) {
1958 int trailing_zeros = CompilerIntrinsics::CountTrailingZeros(grey_objects);
1959 grey_objects >>= trailing_zeros;
1960 offset += trailing_zeros;
1961 MarkBit markbit(cell, 1 << offset, false);
1962 ASSERT(Marking::IsGrey(markbit));
1963 Marking::GreyToBlack(markbit);
1964 Address addr = cell_base + offset * kPointerSize;
1965 HeapObject* object = HeapObject::FromAddress(addr);
1966 MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1967 marking_deque->PushBlack(object);
1968 if (marking_deque->IsFull()) return;
1973 grey_objects >>= (Bitmap::kBitsPerCell - 1);
1978 int MarkCompactCollector::DiscoverAndPromoteBlackObjectsOnPage(
1979 NewSpace* new_space,
1981 ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1982 ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
1983 ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
1984 ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1986 MarkBit::CellType* cells = p->markbits()->cells();
1987 int survivors_size = 0;
1989 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1990 Address cell_base = it.CurrentCellBase();
1991 MarkBit::CellType* cell = it.CurrentCell();
1993 MarkBit::CellType current_cell = *cell;
1994 if (current_cell == 0) continue;
1997 while (current_cell != 0) {
1998 int trailing_zeros = CompilerIntrinsics::CountTrailingZeros(current_cell);
1999 current_cell >>= trailing_zeros;
2000 offset += trailing_zeros;
2001 Address address = cell_base + offset * kPointerSize;
2002 HeapObject* object = HeapObject::FromAddress(address);
2004 int size = object->Size();
2005 survivors_size += size;
2007 Heap::UpdateAllocationSiteFeedback(object, Heap::RECORD_SCRATCHPAD_SLOT);
2011 // Aggressively promote young survivors to the old space.
2012 if (TryPromoteObject(object, size)) {
2016 // Promotion failed. Just migrate object to another semispace.
2017 AllocationResult allocation = new_space->AllocateRaw(size);
2018 if (allocation.IsRetry()) {
2019 if (!new_space->AddFreshPage()) {
2020 // Shouldn't happen. We are sweeping linearly, and to-space
2021 // has the same number of pages as from-space, so there is
2025 allocation = new_space->AllocateRaw(size);
2026 ASSERT(!allocation.IsRetry());
2028 Object* target = allocation.ToObjectChecked();
2030 MigrateObject(HeapObject::cast(target),
2034 heap()->IncrementSemiSpaceCopiedObjectSize(size);
2038 return survivors_size;
2042 static void DiscoverGreyObjectsInSpace(Heap* heap,
2043 MarkingDeque* marking_deque,
2044 PagedSpace* space) {
2045 if (!space->was_swept_conservatively()) {
2046 HeapObjectIterator it(space);
2047 DiscoverGreyObjectsWithIterator(heap, marking_deque, &it);
2049 PageIterator it(space);
2050 while (it.has_next()) {
2051 Page* p = it.next();
2052 DiscoverGreyObjectsOnPage(marking_deque, p);
2053 if (marking_deque->IsFull()) return;
2059 static void DiscoverGreyObjectsInNewSpace(Heap* heap,
2060 MarkingDeque* marking_deque) {
2061 NewSpace* space = heap->new_space();
2062 NewSpacePageIterator it(space->bottom(), space->top());
2063 while (it.has_next()) {
2064 NewSpacePage* page = it.next();
2065 DiscoverGreyObjectsOnPage(marking_deque, page);
2066 if (marking_deque->IsFull()) return;
2071 bool MarkCompactCollector::IsUnmarkedHeapObject(Object** p) {
2073 if (!o->IsHeapObject()) return false;
2074 HeapObject* heap_object = HeapObject::cast(o);
2075 MarkBit mark = Marking::MarkBitFrom(heap_object);
2080 bool MarkCompactCollector::IsUnmarkedHeapObjectWithHeap(Heap* heap,
2083 ASSERT(o->IsHeapObject());
2084 HeapObject* heap_object = HeapObject::cast(o);
2085 MarkBit mark = Marking::MarkBitFrom(heap_object);
2090 void MarkCompactCollector::MarkStringTable(RootMarkingVisitor* visitor) {
2091 StringTable* string_table = heap()->string_table();
2092 // Mark the string table itself.
2093 MarkBit string_table_mark = Marking::MarkBitFrom(string_table);
2094 if (!string_table_mark.Get()) {
2095 // String table could have already been marked by visiting the handles list.
2096 SetMark(string_table, string_table_mark);
2098 // Explicitly mark the prefix.
2099 string_table->IteratePrefix(visitor);
2100 ProcessMarkingDeque();
2104 void MarkCompactCollector::MarkAllocationSite(AllocationSite* site) {
2105 MarkBit mark_bit = Marking::MarkBitFrom(site);
2106 SetMark(site, mark_bit);
2110 void MarkCompactCollector::MarkRoots(RootMarkingVisitor* visitor) {
2111 // Mark the heap roots including global variables, stack variables,
2112 // etc., and all objects reachable from them.
2113 heap()->IterateStrongRoots(visitor, VISIT_ONLY_STRONG);
2115 // Handle the string table specially.
2116 MarkStringTable(visitor);
2118 MarkWeakObjectToCodeTable();
2120 // There may be overflowed objects in the heap. Visit them now.
2121 while (marking_deque_.overflowed()) {
2122 RefillMarkingDeque();
2123 EmptyMarkingDeque();
2128 void MarkCompactCollector::MarkImplicitRefGroups() {
2129 List<ImplicitRefGroup*>* ref_groups =
2130 isolate()->global_handles()->implicit_ref_groups();
2133 for (int i = 0; i < ref_groups->length(); i++) {
2134 ImplicitRefGroup* entry = ref_groups->at(i);
2135 ASSERT(entry != NULL);
2137 if (!IsMarked(*entry->parent)) {
2138 (*ref_groups)[last++] = entry;
2142 Object*** children = entry->children;
2143 // A parent object is marked, so mark all child heap objects.
2144 for (size_t j = 0; j < entry->length; ++j) {
2145 if ((*children[j])->IsHeapObject()) {
2146 HeapObject* child = HeapObject::cast(*children[j]);
2147 MarkBit mark = Marking::MarkBitFrom(child);
2148 MarkObject(child, mark);
2152 // Once the entire group has been marked, dispose it because it's
2153 // not needed anymore.
2156 ref_groups->Rewind(last);
2160 void MarkCompactCollector::MarkWeakObjectToCodeTable() {
2161 HeapObject* weak_object_to_code_table =
2162 HeapObject::cast(heap()->weak_object_to_code_table());
2163 if (!IsMarked(weak_object_to_code_table)) {
2164 MarkBit mark = Marking::MarkBitFrom(weak_object_to_code_table);
2165 SetMark(weak_object_to_code_table, mark);
2170 // Mark all objects reachable from the objects on the marking stack.
2171 // Before: the marking stack contains zero or more heap object pointers.
2172 // After: the marking stack is empty, and all objects reachable from the
2173 // marking stack have been marked, or are overflowed in the heap.
2174 void MarkCompactCollector::EmptyMarkingDeque() {
2175 while (!marking_deque_.IsEmpty()) {
2176 HeapObject* object = marking_deque_.Pop();
2177 ASSERT(object->IsHeapObject());
2178 ASSERT(heap()->Contains(object));
2179 ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
2181 Map* map = object->map();
2182 MarkBit map_mark = Marking::MarkBitFrom(map);
2183 MarkObject(map, map_mark);
2185 MarkCompactMarkingVisitor::IterateBody(map, object);
2190 // Sweep the heap for overflowed objects, clear their overflow bits, and
2191 // push them on the marking stack. Stop early if the marking stack fills
2192 // before sweeping completes. If sweeping completes, there are no remaining
2193 // overflowed objects in the heap so the overflow flag on the markings stack
2195 void MarkCompactCollector::RefillMarkingDeque() {
2196 ASSERT(marking_deque_.overflowed());
2198 DiscoverGreyObjectsInNewSpace(heap(), &marking_deque_);
2199 if (marking_deque_.IsFull()) return;
2201 DiscoverGreyObjectsInSpace(heap(),
2203 heap()->old_pointer_space());
2204 if (marking_deque_.IsFull()) return;
2206 DiscoverGreyObjectsInSpace(heap(),
2208 heap()->old_data_space());
2209 if (marking_deque_.IsFull()) return;
2211 DiscoverGreyObjectsInSpace(heap(),
2213 heap()->code_space());
2214 if (marking_deque_.IsFull()) return;
2216 DiscoverGreyObjectsInSpace(heap(),
2218 heap()->map_space());
2219 if (marking_deque_.IsFull()) return;
2221 DiscoverGreyObjectsInSpace(heap(),
2223 heap()->cell_space());
2224 if (marking_deque_.IsFull()) return;
2226 DiscoverGreyObjectsInSpace(heap(),
2228 heap()->property_cell_space());
2229 if (marking_deque_.IsFull()) return;
2231 LargeObjectIterator lo_it(heap()->lo_space());
2232 DiscoverGreyObjectsWithIterator(heap(),
2235 if (marking_deque_.IsFull()) return;
2237 marking_deque_.ClearOverflowed();
2241 // Mark all objects reachable (transitively) from objects on the marking
2242 // stack. Before: the marking stack contains zero or more heap object
2243 // pointers. After: the marking stack is empty and there are no overflowed
2244 // objects in the heap.
2245 void MarkCompactCollector::ProcessMarkingDeque() {
2246 EmptyMarkingDeque();
2247 while (marking_deque_.overflowed()) {
2248 RefillMarkingDeque();
2249 EmptyMarkingDeque();
2254 // Mark all objects reachable (transitively) from objects on the marking
2255 // stack including references only considered in the atomic marking pause.
2256 void MarkCompactCollector::ProcessEphemeralMarking(ObjectVisitor* visitor) {
2257 bool work_to_do = true;
2258 ASSERT(marking_deque_.IsEmpty());
2259 while (work_to_do) {
2260 isolate()->global_handles()->IterateObjectGroups(
2261 visitor, &IsUnmarkedHeapObjectWithHeap);
2262 MarkImplicitRefGroups();
2263 ProcessWeakCollections();
2264 work_to_do = !marking_deque_.IsEmpty();
2265 ProcessMarkingDeque();
2270 void MarkCompactCollector::ProcessTopOptimizedFrame(ObjectVisitor* visitor) {
2271 for (StackFrameIterator it(isolate(), isolate()->thread_local_top());
2272 !it.done(); it.Advance()) {
2273 if (it.frame()->type() == StackFrame::JAVA_SCRIPT) {
2276 if (it.frame()->type() == StackFrame::OPTIMIZED) {
2277 Code* code = it.frame()->LookupCode();
2278 if (!code->CanDeoptAt(it.frame()->pc())) {
2279 code->CodeIterateBody(visitor);
2281 ProcessMarkingDeque();
2288 void MarkCompactCollector::MarkLiveObjects() {
2289 GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_MARK);
2290 // The recursive GC marker detects when it is nearing stack overflow,
2291 // and switches to a different marking system. JS interrupts interfere
2292 // with the C stack limit check.
2293 PostponeInterruptsScope postpone(isolate());
2295 bool incremental_marking_overflowed = false;
2296 IncrementalMarking* incremental_marking = heap_->incremental_marking();
2297 if (was_marked_incrementally_) {
2298 // Finalize the incremental marking and check whether we had an overflow.
2299 // Both markers use grey color to mark overflowed objects so
2300 // non-incremental marker can deal with them as if overflow
2301 // occured during normal marking.
2302 // But incremental marker uses a separate marking deque
2303 // so we have to explicitly copy its overflow state.
2304 incremental_marking->Finalize();
2305 incremental_marking_overflowed =
2306 incremental_marking->marking_deque()->overflowed();
2307 incremental_marking->marking_deque()->ClearOverflowed();
2309 // Abort any pending incremental activities e.g. incremental sweeping.
2310 incremental_marking->Abort();
2314 ASSERT(state_ == PREPARE_GC);
2315 state_ = MARK_LIVE_OBJECTS;
2317 // The to space contains live objects, a page in from space is used as a
2319 Address marking_deque_start = heap()->new_space()->FromSpacePageLow();
2320 Address marking_deque_end = heap()->new_space()->FromSpacePageHigh();
2321 if (FLAG_force_marking_deque_overflows) {
2322 marking_deque_end = marking_deque_start + 64 * kPointerSize;
2324 marking_deque_.Initialize(marking_deque_start,
2326 ASSERT(!marking_deque_.overflowed());
2328 if (incremental_marking_overflowed) {
2329 // There are overflowed objects left in the heap after incremental marking.
2330 marking_deque_.SetOverflowed();
2333 PrepareForCodeFlushing();
2335 if (was_marked_incrementally_) {
2336 // There is no write barrier on cells so we have to scan them now at the end
2337 // of the incremental marking.
2339 HeapObjectIterator cell_iterator(heap()->cell_space());
2341 while ((cell = cell_iterator.Next()) != NULL) {
2342 ASSERT(cell->IsCell());
2343 if (IsMarked(cell)) {
2344 int offset = Cell::kValueOffset;
2345 MarkCompactMarkingVisitor::VisitPointer(
2347 reinterpret_cast<Object**>(cell->address() + offset));
2352 HeapObjectIterator js_global_property_cell_iterator(
2353 heap()->property_cell_space());
2355 while ((cell = js_global_property_cell_iterator.Next()) != NULL) {
2356 ASSERT(cell->IsPropertyCell());
2357 if (IsMarked(cell)) {
2358 MarkCompactMarkingVisitor::VisitPropertyCell(cell->map(), cell);
2364 RootMarkingVisitor root_visitor(heap());
2365 MarkRoots(&root_visitor);
2367 ProcessTopOptimizedFrame(&root_visitor);
2369 // The objects reachable from the roots are marked, yet unreachable
2370 // objects are unmarked. Mark objects reachable due to host
2371 // application specific logic or through Harmony weak maps.
2372 ProcessEphemeralMarking(&root_visitor);
2374 // The objects reachable from the roots, weak maps or object groups
2375 // are marked, yet unreachable objects are unmarked. Mark objects
2376 // reachable only from weak global handles.
2378 // First we identify nonlive weak handles and mark them as pending
2380 heap()->isolate()->global_handles()->IdentifyWeakHandles(
2381 &IsUnmarkedHeapObject);
2382 // Then we mark the objects and process the transitive closure.
2383 heap()->isolate()->global_handles()->IterateWeakRoots(&root_visitor);
2384 while (marking_deque_.overflowed()) {
2385 RefillMarkingDeque();
2386 EmptyMarkingDeque();
2389 // Repeat host application specific and Harmony weak maps marking to
2390 // mark unmarked objects reachable from the weak roots.
2391 ProcessEphemeralMarking(&root_visitor);
2397 void MarkCompactCollector::AfterMarking() {
2398 // Object literal map caches reference strings (cache keys) and maps
2399 // (cache values). At this point still useful maps have already been
2400 // marked. Mark the keys for the alive values before we process the
2404 // Prune the string table removing all strings only pointed to by the
2405 // string table. Cannot use string_table() here because the string
2407 StringTable* string_table = heap()->string_table();
2408 InternalizedStringTableCleaner internalized_visitor(heap());
2409 string_table->IterateElements(&internalized_visitor);
2410 string_table->ElementsRemoved(internalized_visitor.PointersRemoved());
2412 ExternalStringTableCleaner external_visitor(heap());
2413 heap()->external_string_table_.Iterate(&external_visitor);
2414 heap()->external_string_table_.CleanUp();
2416 // Process the weak references.
2417 MarkCompactWeakObjectRetainer mark_compact_object_retainer;
2418 heap()->ProcessWeakReferences(&mark_compact_object_retainer);
2420 // Remove object groups after marking phase.
2421 heap()->isolate()->global_handles()->RemoveObjectGroups();
2422 heap()->isolate()->global_handles()->RemoveImplicitRefGroups();
2424 // Flush code from collected candidates.
2425 if (is_code_flushing_enabled()) {
2426 code_flusher_->ProcessCandidates();
2427 // If incremental marker does not support code flushing, we need to
2428 // disable it before incremental marking steps for next cycle.
2429 if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
2430 EnableCodeFlushing(false);
2434 if (FLAG_track_gc_object_stats) {
2435 heap()->CheckpointObjectStats();
2440 void MarkCompactCollector::ProcessMapCaches() {
2441 Object* raw_context = heap()->native_contexts_list();
2442 while (raw_context != heap()->undefined_value()) {
2443 Context* context = reinterpret_cast<Context*>(raw_context);
2444 if (IsMarked(context)) {
2445 HeapObject* raw_map_cache =
2446 HeapObject::cast(context->get(Context::MAP_CACHE_INDEX));
2447 // A map cache may be reachable from the stack. In this case
2448 // it's already transitively marked and it's too late to clean
2450 if (!IsMarked(raw_map_cache) &&
2451 raw_map_cache != heap()->undefined_value()) {
2452 MapCache* map_cache = reinterpret_cast<MapCache*>(raw_map_cache);
2453 int existing_elements = map_cache->NumberOfElements();
2454 int used_elements = 0;
2455 for (int i = MapCache::kElementsStartIndex;
2456 i < map_cache->length();
2457 i += MapCache::kEntrySize) {
2458 Object* raw_key = map_cache->get(i);
2459 if (raw_key == heap()->undefined_value() ||
2460 raw_key == heap()->the_hole_value()) continue;
2461 STATIC_ASSERT(MapCache::kEntrySize == 2);
2462 Object* raw_map = map_cache->get(i + 1);
2463 if (raw_map->IsHeapObject() && IsMarked(raw_map)) {
2466 // Delete useless entries with unmarked maps.
2467 ASSERT(raw_map->IsMap());
2468 map_cache->set_the_hole(i);
2469 map_cache->set_the_hole(i + 1);
2472 if (used_elements == 0) {
2473 context->set(Context::MAP_CACHE_INDEX, heap()->undefined_value());
2475 // Note: we don't actually shrink the cache here to avoid
2476 // extra complexity during GC. We rely on subsequent cache
2477 // usages (EnsureCapacity) to do this.
2478 map_cache->ElementsRemoved(existing_elements - used_elements);
2479 MarkBit map_cache_markbit = Marking::MarkBitFrom(map_cache);
2480 MarkObject(map_cache, map_cache_markbit);
2484 // Move to next element in the list.
2485 raw_context = context->get(Context::NEXT_CONTEXT_LINK);
2487 ProcessMarkingDeque();
2491 void MarkCompactCollector::ClearNonLiveReferences() {
2492 // Iterate over the map space, setting map transitions that go from
2493 // a marked map to an unmarked map to null transitions. This action
2494 // is carried out only on maps of JSObjects and related subtypes.
2495 HeapObjectIterator map_iterator(heap()->map_space());
2496 for (HeapObject* obj = map_iterator.Next();
2498 obj = map_iterator.Next()) {
2499 Map* map = Map::cast(obj);
2501 if (!map->CanTransition()) continue;
2503 MarkBit map_mark = Marking::MarkBitFrom(map);
2504 ClearNonLivePrototypeTransitions(map);
2505 ClearNonLiveMapTransitions(map, map_mark);
2507 if (map_mark.Get()) {
2508 ClearNonLiveDependentCode(map->dependent_code());
2510 ClearDependentCode(map->dependent_code());
2511 map->set_dependent_code(DependentCode::cast(heap()->empty_fixed_array()));
2515 // Iterate over property cell space, removing dependent code that is not
2516 // otherwise kept alive by strong references.
2517 HeapObjectIterator cell_iterator(heap_->property_cell_space());
2518 for (HeapObject* cell = cell_iterator.Next();
2520 cell = cell_iterator.Next()) {
2521 if (IsMarked(cell)) {
2522 ClearNonLiveDependentCode(PropertyCell::cast(cell)->dependent_code());
2526 // Iterate over allocation sites, removing dependent code that is not
2527 // otherwise kept alive by strong references.
2528 Object* undefined = heap()->undefined_value();
2529 for (Object* site = heap()->allocation_sites_list();
2531 site = AllocationSite::cast(site)->weak_next()) {
2532 if (IsMarked(site)) {
2533 ClearNonLiveDependentCode(AllocationSite::cast(site)->dependent_code());
2537 if (heap_->weak_object_to_code_table()->IsHashTable()) {
2538 WeakHashTable* table =
2539 WeakHashTable::cast(heap_->weak_object_to_code_table());
2540 uint32_t capacity = table->Capacity();
2541 for (uint32_t i = 0; i < capacity; i++) {
2542 uint32_t key_index = table->EntryToIndex(i);
2543 Object* key = table->get(key_index);
2544 if (!table->IsKey(key)) continue;
2545 uint32_t value_index = table->EntryToValueIndex(i);
2546 Object* value = table->get(value_index);
2547 if (key->IsCell() && !IsMarked(key)) {
2548 Cell* cell = Cell::cast(key);
2549 Object* object = cell->value();
2550 if (IsMarked(object)) {
2551 MarkBit mark = Marking::MarkBitFrom(cell);
2552 SetMark(cell, mark);
2553 Object** value_slot = HeapObject::RawField(cell, Cell::kValueOffset);
2554 RecordSlot(value_slot, value_slot, *value_slot);
2557 if (IsMarked(key)) {
2558 if (!IsMarked(value)) {
2559 HeapObject* obj = HeapObject::cast(value);
2560 MarkBit mark = Marking::MarkBitFrom(obj);
2563 ClearNonLiveDependentCode(DependentCode::cast(value));
2565 ClearDependentCode(DependentCode::cast(value));
2566 table->set(key_index, heap_->the_hole_value());
2567 table->set(value_index, heap_->the_hole_value());
2568 table->ElementRemoved();
2575 void MarkCompactCollector::ClearNonLivePrototypeTransitions(Map* map) {
2576 int number_of_transitions = map->NumberOfProtoTransitions();
2577 FixedArray* prototype_transitions = map->GetPrototypeTransitions();
2579 int new_number_of_transitions = 0;
2580 const int header = Map::kProtoTransitionHeaderSize;
2581 const int proto_offset = header + Map::kProtoTransitionPrototypeOffset;
2582 const int map_offset = header + Map::kProtoTransitionMapOffset;
2583 const int step = Map::kProtoTransitionElementsPerEntry;
2584 for (int i = 0; i < number_of_transitions; i++) {
2585 Object* prototype = prototype_transitions->get(proto_offset + i * step);
2586 Object* cached_map = prototype_transitions->get(map_offset + i * step);
2587 if (IsMarked(prototype) && IsMarked(cached_map)) {
2588 ASSERT(!prototype->IsUndefined());
2589 int proto_index = proto_offset + new_number_of_transitions * step;
2590 int map_index = map_offset + new_number_of_transitions * step;
2591 if (new_number_of_transitions != i) {
2592 prototype_transitions->set(
2595 UPDATE_WRITE_BARRIER);
2596 prototype_transitions->set(
2599 SKIP_WRITE_BARRIER);
2601 Object** slot = prototype_transitions->RawFieldOfElementAt(proto_index);
2602 RecordSlot(slot, slot, prototype);
2603 new_number_of_transitions++;
2607 if (new_number_of_transitions != number_of_transitions) {
2608 map->SetNumberOfProtoTransitions(new_number_of_transitions);
2611 // Fill slots that became free with undefined value.
2612 for (int i = new_number_of_transitions * step;
2613 i < number_of_transitions * step;
2615 prototype_transitions->set_undefined(header + i);
2620 void MarkCompactCollector::ClearNonLiveMapTransitions(Map* map,
2622 Object* potential_parent = map->GetBackPointer();
2623 if (!potential_parent->IsMap()) return;
2624 Map* parent = Map::cast(potential_parent);
2626 // Follow back pointer, check whether we are dealing with a map transition
2627 // from a live map to a dead path and in case clear transitions of parent.
2628 bool current_is_alive = map_mark.Get();
2629 bool parent_is_alive = Marking::MarkBitFrom(parent).Get();
2630 if (!current_is_alive && parent_is_alive) {
2631 parent->ClearNonLiveTransitions(heap());
2636 void MarkCompactCollector::ClearDependentICList(Object* head) {
2637 Object* current = head;
2638 Object* undefined = heap()->undefined_value();
2639 while (current != undefined) {
2640 Code* code = Code::cast(current);
2641 if (IsMarked(code)) {
2642 ASSERT(code->is_weak_stub());
2643 IC::InvalidateMaps(code);
2645 current = code->next_code_link();
2646 code->set_next_code_link(undefined);
2651 void MarkCompactCollector::ClearDependentCode(
2652 DependentCode* entries) {
2653 DisallowHeapAllocation no_allocation;
2654 DependentCode::GroupStartIndexes starts(entries);
2655 int number_of_entries = starts.number_of_entries();
2656 if (number_of_entries == 0) return;
2657 int g = DependentCode::kWeakICGroup;
2658 if (starts.at(g) != starts.at(g + 1)) {
2659 int i = starts.at(g);
2660 ASSERT(i + 1 == starts.at(g + 1));
2661 Object* head = entries->object_at(i);
2662 ClearDependentICList(head);
2664 g = DependentCode::kWeakCodeGroup;
2665 for (int i = starts.at(g); i < starts.at(g + 1); i++) {
2666 // If the entry is compilation info then the map must be alive,
2667 // and ClearDependentCode shouldn't be called.
2668 ASSERT(entries->is_code_at(i));
2669 Code* code = entries->code_at(i);
2670 if (IsMarked(code) && !code->marked_for_deoptimization()) {
2671 code->set_marked_for_deoptimization(true);
2672 code->InvalidateEmbeddedObjects();
2673 have_code_to_deoptimize_ = true;
2676 for (int i = 0; i < number_of_entries; i++) {
2677 entries->clear_at(i);
2682 int MarkCompactCollector::ClearNonLiveDependentCodeInGroup(
2683 DependentCode* entries, int group, int start, int end, int new_start) {
2685 if (group == DependentCode::kWeakICGroup) {
2686 // Dependent weak IC stubs form a linked list and only the head is stored
2687 // in the dependent code array.
2689 ASSERT(start + 1 == end);
2690 Object* old_head = entries->object_at(start);
2691 MarkCompactWeakObjectRetainer retainer;
2692 Object* head = VisitWeakList<Code>(heap(), old_head, &retainer);
2693 entries->set_object_at(new_start, head);
2694 Object** slot = entries->slot_at(new_start);
2695 RecordSlot(slot, slot, head);
2696 // We do not compact this group even if the head is undefined,
2697 // more dependent ICs are likely to be added later.
2701 for (int i = start; i < end; i++) {
2702 Object* obj = entries->object_at(i);
2703 ASSERT(obj->IsCode() || IsMarked(obj));
2704 if (IsMarked(obj) &&
2705 (!obj->IsCode() || !WillBeDeoptimized(Code::cast(obj)))) {
2706 if (new_start + survived != i) {
2707 entries->set_object_at(new_start + survived, obj);
2709 Object** slot = entries->slot_at(new_start + survived);
2710 RecordSlot(slot, slot, obj);
2715 entries->set_number_of_entries(
2716 static_cast<DependentCode::DependencyGroup>(group), survived);
2721 void MarkCompactCollector::ClearNonLiveDependentCode(DependentCode* entries) {
2722 DisallowHeapAllocation no_allocation;
2723 DependentCode::GroupStartIndexes starts(entries);
2724 int number_of_entries = starts.number_of_entries();
2725 if (number_of_entries == 0) return;
2726 int new_number_of_entries = 0;
2727 // Go through all groups, remove dead codes and compact.
2728 for (int g = 0; g < DependentCode::kGroupCount; g++) {
2729 int survived = ClearNonLiveDependentCodeInGroup(
2730 entries, g, starts.at(g), starts.at(g + 1), new_number_of_entries);
2731 new_number_of_entries += survived;
2733 for (int i = new_number_of_entries; i < number_of_entries; i++) {
2734 entries->clear_at(i);
2739 void MarkCompactCollector::ProcessWeakCollections() {
2740 GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_WEAKCOLLECTION_PROCESS);
2741 Object* weak_collection_obj = heap()->encountered_weak_collections();
2742 while (weak_collection_obj != Smi::FromInt(0)) {
2743 JSWeakCollection* weak_collection =
2744 reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2745 ASSERT(MarkCompactCollector::IsMarked(weak_collection));
2746 if (weak_collection->table()->IsHashTable()) {
2747 ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2748 Object** anchor = reinterpret_cast<Object**>(table->address());
2749 for (int i = 0; i < table->Capacity(); i++) {
2750 if (MarkCompactCollector::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
2752 table->RawFieldOfElementAt(ObjectHashTable::EntryToIndex(i));
2753 RecordSlot(anchor, key_slot, *key_slot);
2754 Object** value_slot =
2755 table->RawFieldOfElementAt(ObjectHashTable::EntryToValueIndex(i));
2756 MarkCompactMarkingVisitor::MarkObjectByPointer(
2757 this, anchor, value_slot);
2761 weak_collection_obj = weak_collection->next();
2766 void MarkCompactCollector::ClearWeakCollections() {
2767 GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_WEAKCOLLECTION_CLEAR);
2768 Object* weak_collection_obj = heap()->encountered_weak_collections();
2769 while (weak_collection_obj != Smi::FromInt(0)) {
2770 JSWeakCollection* weak_collection =
2771 reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2772 ASSERT(MarkCompactCollector::IsMarked(weak_collection));
2773 if (weak_collection->table()->IsHashTable()) {
2774 ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2775 for (int i = 0; i < table->Capacity(); i++) {
2776 HeapObject* key = HeapObject::cast(table->KeyAt(i));
2777 if (!MarkCompactCollector::IsMarked(key)) {
2778 table->RemoveEntry(i);
2782 weak_collection_obj = weak_collection->next();
2783 weak_collection->set_next(heap()->undefined_value());
2785 heap()->set_encountered_weak_collections(Smi::FromInt(0));
2789 // We scavange new space simultaneously with sweeping. This is done in two
2792 // The first pass migrates all alive objects from one semispace to another or
2793 // promotes them to old space. Forwarding address is written directly into
2794 // first word of object without any encoding. If object is dead we write
2795 // NULL as a forwarding address.
2797 // The second pass updates pointers to new space in all spaces. It is possible
2798 // to encounter pointers to dead new space objects during traversal of pointers
2799 // to new space. We should clear them to avoid encountering them during next
2800 // pointer iteration. This is an issue if the store buffer overflows and we
2801 // have to scan the entire old space, including dead objects, looking for
2802 // pointers to new space.
2803 void MarkCompactCollector::MigrateObject(HeapObject* dst,
2806 AllocationSpace dest) {
2807 Address dst_addr = dst->address();
2808 Address src_addr = src->address();
2809 HeapProfiler* heap_profiler = heap()->isolate()->heap_profiler();
2810 if (heap_profiler->is_tracking_object_moves()) {
2811 heap_profiler->ObjectMoveEvent(src_addr, dst_addr, size);
2813 ASSERT(heap()->AllowedToBeMigrated(src, dest));
2814 ASSERT(dest != LO_SPACE && size <= Page::kMaxRegularHeapObjectSize);
2815 if (dest == OLD_POINTER_SPACE) {
2816 Address src_slot = src_addr;
2817 Address dst_slot = dst_addr;
2818 ASSERT(IsAligned(size, kPointerSize));
2820 for (int remaining = size / kPointerSize; remaining > 0; remaining--) {
2821 Object* value = Memory::Object_at(src_slot);
2823 Memory::Object_at(dst_slot) = value;
2825 if (heap_->InNewSpace(value)) {
2826 heap_->store_buffer()->Mark(dst_slot);
2827 } else if (value->IsHeapObject() && IsOnEvacuationCandidate(value)) {
2828 SlotsBuffer::AddTo(&slots_buffer_allocator_,
2829 &migration_slots_buffer_,
2830 reinterpret_cast<Object**>(dst_slot),
2831 SlotsBuffer::IGNORE_OVERFLOW);
2834 src_slot += kPointerSize;
2835 dst_slot += kPointerSize;
2838 if (compacting_ && dst->IsJSFunction()) {
2839 Address code_entry_slot = dst_addr + JSFunction::kCodeEntryOffset;
2840 Address code_entry = Memory::Address_at(code_entry_slot);
2842 if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2843 SlotsBuffer::AddTo(&slots_buffer_allocator_,
2844 &migration_slots_buffer_,
2845 SlotsBuffer::CODE_ENTRY_SLOT,
2847 SlotsBuffer::IGNORE_OVERFLOW);
2849 } else if (compacting_ && dst->IsConstantPoolArray()) {
2850 ConstantPoolArray* array = ConstantPoolArray::cast(dst);
2851 ConstantPoolArray::Iterator code_iter(array, ConstantPoolArray::CODE_PTR);
2852 while (!code_iter.is_finished()) {
2853 Address code_entry_slot =
2854 dst_addr + array->OffsetOfElementAt(code_iter.next_index());
2855 Address code_entry = Memory::Address_at(code_entry_slot);
2857 if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2858 SlotsBuffer::AddTo(&slots_buffer_allocator_,
2859 &migration_slots_buffer_,
2860 SlotsBuffer::CODE_ENTRY_SLOT,
2862 SlotsBuffer::IGNORE_OVERFLOW);
2866 } else if (dest == CODE_SPACE) {
2867 PROFILE(isolate(), CodeMoveEvent(src_addr, dst_addr));
2868 heap()->MoveBlock(dst_addr, src_addr, size);
2869 SlotsBuffer::AddTo(&slots_buffer_allocator_,
2870 &migration_slots_buffer_,
2871 SlotsBuffer::RELOCATED_CODE_OBJECT,
2873 SlotsBuffer::IGNORE_OVERFLOW);
2874 Code::cast(dst)->Relocate(dst_addr - src_addr);
2876 ASSERT(dest == OLD_DATA_SPACE || dest == NEW_SPACE);
2877 heap()->MoveBlock(dst_addr, src_addr, size);
2879 Memory::Address_at(src_addr) = dst_addr;
2883 // Visitor for updating pointers from live objects in old spaces to new space.
2884 // It does not expect to encounter pointers to dead objects.
2885 class PointersUpdatingVisitor: public ObjectVisitor {
2887 explicit PointersUpdatingVisitor(Heap* heap) : heap_(heap) { }
2889 void VisitPointer(Object** p) {
2893 void VisitPointers(Object** start, Object** end) {
2894 for (Object** p = start; p < end; p++) UpdatePointer(p);
2897 void VisitEmbeddedPointer(RelocInfo* rinfo) {
2898 ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
2899 Object* target = rinfo->target_object();
2900 Object* old_target = target;
2901 VisitPointer(&target);
2902 // Avoid unnecessary changes that might unnecessary flush the instruction
2904 if (target != old_target) {
2905 rinfo->set_target_object(target);
2909 void VisitCodeTarget(RelocInfo* rinfo) {
2910 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
2911 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
2912 Object* old_target = target;
2913 VisitPointer(&target);
2914 if (target != old_target) {
2915 rinfo->set_target_address(Code::cast(target)->instruction_start());
2919 void VisitCodeAgeSequence(RelocInfo* rinfo) {
2920 ASSERT(RelocInfo::IsCodeAgeSequence(rinfo->rmode()));
2921 Object* stub = rinfo->code_age_stub();
2922 ASSERT(stub != NULL);
2923 VisitPointer(&stub);
2924 if (stub != rinfo->code_age_stub()) {
2925 rinfo->set_code_age_stub(Code::cast(stub));
2929 void VisitDebugTarget(RelocInfo* rinfo) {
2930 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
2931 rinfo->IsPatchedReturnSequence()) ||
2932 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
2933 rinfo->IsPatchedDebugBreakSlotSequence()));
2934 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
2935 VisitPointer(&target);
2936 rinfo->set_call_address(Code::cast(target)->instruction_start());
2939 static inline void UpdateSlot(Heap* heap, Object** slot) {
2940 Object* obj = *slot;
2942 if (!obj->IsHeapObject()) return;
2944 HeapObject* heap_obj = HeapObject::cast(obj);
2946 MapWord map_word = heap_obj->map_word();
2947 if (map_word.IsForwardingAddress()) {
2948 ASSERT(heap->InFromSpace(heap_obj) ||
2949 MarkCompactCollector::IsOnEvacuationCandidate(heap_obj));
2950 HeapObject* target = map_word.ToForwardingAddress();
2952 ASSERT(!heap->InFromSpace(target) &&
2953 !MarkCompactCollector::IsOnEvacuationCandidate(target));
2958 inline void UpdatePointer(Object** p) {
2959 UpdateSlot(heap_, p);
2966 static void UpdatePointer(HeapObject** address, HeapObject* object) {
2967 Address new_addr = Memory::Address_at(object->address());
2969 // The new space sweep will overwrite the map word of dead objects
2970 // with NULL. In this case we do not need to transfer this entry to
2971 // the store buffer which we are rebuilding.
2972 // We perform the pointer update with a no barrier compare-and-swap. The
2973 // compare and swap may fail in the case where the pointer update tries to
2974 // update garbage memory which was concurrently accessed by the sweeper.
2975 if (new_addr != NULL) {
2976 base::NoBarrier_CompareAndSwap(
2977 reinterpret_cast<base::AtomicWord*>(address),
2978 reinterpret_cast<base::AtomicWord>(object),
2979 reinterpret_cast<base::AtomicWord>(HeapObject::FromAddress(new_addr)));
2981 // We have to zap this pointer, because the store buffer may overflow later,
2982 // and then we have to scan the entire heap and we don't want to find
2983 // spurious newspace pointers in the old space.
2984 // TODO(mstarzinger): This was changed to a sentinel value to track down
2985 // rare crashes, change it back to Smi::FromInt(0) later.
2986 base::NoBarrier_CompareAndSwap(
2987 reinterpret_cast<base::AtomicWord*>(address),
2988 reinterpret_cast<base::AtomicWord>(object),
2989 reinterpret_cast<base::AtomicWord>(Smi::FromInt(0x0f100d00 >> 1)));
2994 static String* UpdateReferenceInExternalStringTableEntry(Heap* heap,
2996 MapWord map_word = HeapObject::cast(*p)->map_word();
2998 if (map_word.IsForwardingAddress()) {
2999 return String::cast(map_word.ToForwardingAddress());
3002 return String::cast(*p);
3006 bool MarkCompactCollector::TryPromoteObject(HeapObject* object,
3008 ASSERT(object_size <= Page::kMaxRegularHeapObjectSize);
3010 OldSpace* target_space = heap()->TargetSpace(object);
3012 ASSERT(target_space == heap()->old_pointer_space() ||
3013 target_space == heap()->old_data_space());
3015 AllocationResult allocation = target_space->AllocateRaw(object_size);
3016 if (allocation.To(&target)) {
3017 MigrateObject(target,
3020 target_space->identity());
3021 heap()->IncrementPromotedObjectsSize(object_size);
3029 void MarkCompactCollector::EvacuateNewSpace() {
3030 // There are soft limits in the allocation code, designed trigger a mark
3031 // sweep collection by failing allocations. But since we are already in
3032 // a mark-sweep allocation, there is no sense in trying to trigger one.
3033 AlwaysAllocateScope scope(isolate());
3035 NewSpace* new_space = heap()->new_space();
3037 // Store allocation range before flipping semispaces.
3038 Address from_bottom = new_space->bottom();
3039 Address from_top = new_space->top();
3041 // Flip the semispaces. After flipping, to space is empty, from space has
3044 new_space->ResetAllocationInfo();
3046 int survivors_size = 0;
3048 // First pass: traverse all objects in inactive semispace, remove marks,
3049 // migrate live objects and write forwarding addresses. This stage puts
3050 // new entries in the store buffer and may cause some pages to be marked
3051 // scan-on-scavenge.
3052 NewSpacePageIterator it(from_bottom, from_top);
3053 while (it.has_next()) {
3054 NewSpacePage* p = it.next();
3055 survivors_size += DiscoverAndPromoteBlackObjectsOnPage(new_space, p);
3058 heap_->IncrementYoungSurvivorsCounter(survivors_size);
3059 new_space->set_age_mark(new_space->top());
3063 void MarkCompactCollector::EvacuateLiveObjectsFromPage(Page* p) {
3064 AlwaysAllocateScope always_allocate(isolate());
3065 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3066 ASSERT(p->IsEvacuationCandidate() && !p->WasSwept());
3067 p->MarkSweptPrecisely();
3071 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
3072 Address cell_base = it.CurrentCellBase();
3073 MarkBit::CellType* cell = it.CurrentCell();
3075 if (*cell == 0) continue;
3077 int live_objects = MarkWordToObjectStarts(*cell, offsets);
3078 for (int i = 0; i < live_objects; i++) {
3079 Address object_addr = cell_base + offsets[i] * kPointerSize;
3080 HeapObject* object = HeapObject::FromAddress(object_addr);
3081 ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
3083 int size = object->Size();
3085 HeapObject* target_object;
3086 AllocationResult allocation = space->AllocateRaw(size);
3087 if (!allocation.To(&target_object)) {
3088 // OS refused to give us memory.
3089 V8::FatalProcessOutOfMemory("Evacuation");
3093 MigrateObject(target_object, object, size, space->identity());
3094 ASSERT(object->map_word().IsForwardingAddress());
3097 // Clear marking bits for current cell.
3100 p->ResetLiveBytes();
3104 void MarkCompactCollector::EvacuatePages() {
3105 int npages = evacuation_candidates_.length();
3106 for (int i = 0; i < npages; i++) {
3107 Page* p = evacuation_candidates_[i];
3108 ASSERT(p->IsEvacuationCandidate() ||
3109 p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3110 ASSERT(static_cast<int>(p->parallel_sweeping()) ==
3111 MemoryChunk::PARALLEL_SWEEPING_DONE);
3112 if (p->IsEvacuationCandidate()) {
3113 // During compaction we might have to request a new page.
3114 // Check that space still have room for that.
3115 if (static_cast<PagedSpace*>(p->owner())->CanExpand()) {
3116 EvacuateLiveObjectsFromPage(p);
3118 // Without room for expansion evacuation is not guaranteed to succeed.
3119 // Pessimistically abandon unevacuated pages.
3120 for (int j = i; j < npages; j++) {
3121 Page* page = evacuation_candidates_[j];
3122 slots_buffer_allocator_.DeallocateChain(page->slots_buffer_address());
3123 page->ClearEvacuationCandidate();
3124 page->SetFlag(Page::RESCAN_ON_EVACUATION);
3133 class EvacuationWeakObjectRetainer : public WeakObjectRetainer {
3135 virtual Object* RetainAs(Object* object) {
3136 if (object->IsHeapObject()) {
3137 HeapObject* heap_object = HeapObject::cast(object);
3138 MapWord map_word = heap_object->map_word();
3139 if (map_word.IsForwardingAddress()) {
3140 return map_word.ToForwardingAddress();
3148 static inline void UpdateSlot(Isolate* isolate,
3150 SlotsBuffer::SlotType slot_type,
3152 switch (slot_type) {
3153 case SlotsBuffer::CODE_TARGET_SLOT: {
3154 RelocInfo rinfo(addr, RelocInfo::CODE_TARGET, 0, NULL);
3155 rinfo.Visit(isolate, v);
3158 case SlotsBuffer::CODE_ENTRY_SLOT: {
3159 v->VisitCodeEntry(addr);
3162 case SlotsBuffer::RELOCATED_CODE_OBJECT: {
3163 HeapObject* obj = HeapObject::FromAddress(addr);
3164 Code::cast(obj)->CodeIterateBody(v);
3167 case SlotsBuffer::DEBUG_TARGET_SLOT: {
3168 RelocInfo rinfo(addr, RelocInfo::DEBUG_BREAK_SLOT, 0, NULL);
3169 if (rinfo.IsPatchedDebugBreakSlotSequence()) rinfo.Visit(isolate, v);
3172 case SlotsBuffer::JS_RETURN_SLOT: {
3173 RelocInfo rinfo(addr, RelocInfo::JS_RETURN, 0, NULL);
3174 if (rinfo.IsPatchedReturnSequence()) rinfo.Visit(isolate, v);
3177 case SlotsBuffer::EMBEDDED_OBJECT_SLOT: {
3178 RelocInfo rinfo(addr, RelocInfo::EMBEDDED_OBJECT, 0, NULL);
3179 rinfo.Visit(isolate, v);
3191 SWEEP_AND_VISIT_LIVE_OBJECTS
3195 enum SkipListRebuildingMode {
3201 enum FreeSpaceTreatmentMode {
3207 // Sweep a space precisely. After this has been done the space can
3208 // be iterated precisely, hitting only the live objects. Code space
3209 // is always swept precisely because we want to be able to iterate
3210 // over it. Map space is swept precisely, because it is not compacted.
3211 // Slots in live objects pointing into evacuation candidates are updated
3213 template<SweepingMode sweeping_mode,
3214 SkipListRebuildingMode skip_list_mode,
3215 FreeSpaceTreatmentMode free_space_mode>
3216 static void SweepPrecisely(PagedSpace* space,
3219 ASSERT(!p->IsEvacuationCandidate() && !p->WasSwept());
3220 ASSERT_EQ(skip_list_mode == REBUILD_SKIP_LIST,
3221 space->identity() == CODE_SPACE);
3222 ASSERT((p->skip_list() == NULL) || (skip_list_mode == REBUILD_SKIP_LIST));
3224 double start_time = 0.0;
3225 if (FLAG_print_cumulative_gc_stat) {
3226 start_time = OS::TimeCurrentMillis();
3229 p->MarkSweptPrecisely();
3231 Address free_start = p->area_start();
3232 ASSERT(reinterpret_cast<intptr_t>(free_start) % (32 * kPointerSize) == 0);
3235 SkipList* skip_list = p->skip_list();
3236 int curr_region = -1;
3237 if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list) {
3241 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
3242 Address cell_base = it.CurrentCellBase();
3243 MarkBit::CellType* cell = it.CurrentCell();
3244 int live_objects = MarkWordToObjectStarts(*cell, offsets);
3246 for ( ; live_objects != 0; live_objects--) {
3247 Address free_end = cell_base + offsets[live_index++] * kPointerSize;
3248 if (free_end != free_start) {
3249 if (free_space_mode == ZAP_FREE_SPACE) {
3250 memset(free_start, 0xcc, static_cast<int>(free_end - free_start));
3252 space->Free(free_start, static_cast<int>(free_end - free_start));
3253 #ifdef ENABLE_GDB_JIT_INTERFACE
3254 if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3255 GDBJITInterface::RemoveCodeRange(free_start, free_end);
3259 HeapObject* live_object = HeapObject::FromAddress(free_end);
3260 ASSERT(Marking::IsBlack(Marking::MarkBitFrom(live_object)));
3261 Map* map = live_object->map();
3262 int size = live_object->SizeFromMap(map);
3263 if (sweeping_mode == SWEEP_AND_VISIT_LIVE_OBJECTS) {
3264 live_object->IterateBody(map->instance_type(), size, v);
3266 if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list != NULL) {
3267 int new_region_start =
3268 SkipList::RegionNumber(free_end);
3269 int new_region_end =
3270 SkipList::RegionNumber(free_end + size - kPointerSize);
3271 if (new_region_start != curr_region ||
3272 new_region_end != curr_region) {
3273 skip_list->AddObject(free_end, size);
3274 curr_region = new_region_end;
3277 free_start = free_end + size;
3279 // Clear marking bits for current cell.
3282 if (free_start != p->area_end()) {
3283 if (free_space_mode == ZAP_FREE_SPACE) {
3284 memset(free_start, 0xcc, static_cast<int>(p->area_end() - free_start));
3286 space->Free(free_start, static_cast<int>(p->area_end() - free_start));
3287 #ifdef ENABLE_GDB_JIT_INTERFACE
3288 if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3289 GDBJITInterface::RemoveCodeRange(free_start, p->area_end());
3293 p->ResetLiveBytes();
3294 if (FLAG_print_cumulative_gc_stat) {
3295 space->heap()->AddSweepingTime(OS::TimeCurrentMillis() - start_time);
3300 static bool SetMarkBitsUnderInvalidatedCode(Code* code, bool value) {
3301 Page* p = Page::FromAddress(code->address());
3303 if (p->IsEvacuationCandidate() ||
3304 p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3308 Address code_start = code->address();
3309 Address code_end = code_start + code->Size();
3311 uint32_t start_index = MemoryChunk::FastAddressToMarkbitIndex(code_start);
3312 uint32_t end_index =
3313 MemoryChunk::FastAddressToMarkbitIndex(code_end - kPointerSize);
3315 Bitmap* b = p->markbits();
3317 MarkBit start_mark_bit = b->MarkBitFromIndex(start_index);
3318 MarkBit end_mark_bit = b->MarkBitFromIndex(end_index);
3320 MarkBit::CellType* start_cell = start_mark_bit.cell();
3321 MarkBit::CellType* end_cell = end_mark_bit.cell();
3324 MarkBit::CellType start_mask = ~(start_mark_bit.mask() - 1);
3325 MarkBit::CellType end_mask = (end_mark_bit.mask() << 1) - 1;
3327 if (start_cell == end_cell) {
3328 *start_cell |= start_mask & end_mask;
3330 *start_cell |= start_mask;
3331 for (MarkBit::CellType* cell = start_cell + 1; cell < end_cell; cell++) {
3334 *end_cell |= end_mask;
3337 for (MarkBit::CellType* cell = start_cell ; cell <= end_cell; cell++) {
3346 static bool IsOnInvalidatedCodeObject(Address addr) {
3347 // We did not record any slots in large objects thus
3348 // we can safely go to the page from the slot address.
3349 Page* p = Page::FromAddress(addr);
3351 // First check owner's identity because old pointer and old data spaces
3352 // are swept lazily and might still have non-zero mark-bits on some
3354 if (p->owner()->identity() != CODE_SPACE) return false;
3356 // In code space only bits on evacuation candidates (but we don't record
3357 // any slots on them) and under invalidated code objects are non-zero.
3359 p->markbits()->MarkBitFromIndex(Page::FastAddressToMarkbitIndex(addr));
3361 return mark_bit.Get();
3365 void MarkCompactCollector::InvalidateCode(Code* code) {
3366 if (heap_->incremental_marking()->IsCompacting() &&
3367 !ShouldSkipEvacuationSlotRecording(code)) {
3368 ASSERT(compacting_);
3370 // If the object is white than no slots were recorded on it yet.
3371 MarkBit mark_bit = Marking::MarkBitFrom(code);
3372 if (Marking::IsWhite(mark_bit)) return;
3374 invalidated_code_.Add(code);
3379 // Return true if the given code is deoptimized or will be deoptimized.
3380 bool MarkCompactCollector::WillBeDeoptimized(Code* code) {
3381 return code->is_optimized_code() && code->marked_for_deoptimization();
3385 bool MarkCompactCollector::MarkInvalidatedCode() {
3386 bool code_marked = false;
3388 int length = invalidated_code_.length();
3389 for (int i = 0; i < length; i++) {
3390 Code* code = invalidated_code_[i];
3392 if (SetMarkBitsUnderInvalidatedCode(code, true)) {
3401 void MarkCompactCollector::RemoveDeadInvalidatedCode() {
3402 int length = invalidated_code_.length();
3403 for (int i = 0; i < length; i++) {
3404 if (!IsMarked(invalidated_code_[i])) invalidated_code_[i] = NULL;
3409 void MarkCompactCollector::ProcessInvalidatedCode(ObjectVisitor* visitor) {
3410 int length = invalidated_code_.length();
3411 for (int i = 0; i < length; i++) {
3412 Code* code = invalidated_code_[i];
3414 code->Iterate(visitor);
3415 SetMarkBitsUnderInvalidatedCode(code, false);
3418 invalidated_code_.Rewind(0);
3422 void MarkCompactCollector::EvacuateNewSpaceAndCandidates() {
3423 Heap::RelocationLock relocation_lock(heap());
3425 bool code_slots_filtering_required;
3426 { GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP_NEWSPACE);
3427 code_slots_filtering_required = MarkInvalidatedCode();
3431 { GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_EVACUATE_PAGES);
3435 // Second pass: find pointers to new space and update them.
3436 PointersUpdatingVisitor updating_visitor(heap());
3438 { GCTracer::Scope gc_scope(tracer_,
3439 GCTracer::Scope::MC_UPDATE_NEW_TO_NEW_POINTERS);
3440 // Update pointers in to space.
3441 SemiSpaceIterator to_it(heap()->new_space()->bottom(),
3442 heap()->new_space()->top());
3443 for (HeapObject* object = to_it.Next();
3445 object = to_it.Next()) {
3446 Map* map = object->map();
3447 object->IterateBody(map->instance_type(),
3448 object->SizeFromMap(map),
3453 { GCTracer::Scope gc_scope(tracer_,
3454 GCTracer::Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS);
3456 heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_SWEEP_NEWSPACE);
3459 { GCTracer::Scope gc_scope(tracer_,
3460 GCTracer::Scope::MC_UPDATE_OLD_TO_NEW_POINTERS);
3461 StoreBufferRebuildScope scope(heap_,
3462 heap_->store_buffer(),
3463 &Heap::ScavengeStoreBufferCallback);
3464 heap_->store_buffer()->IteratePointersToNewSpaceAndClearMaps(
3468 { GCTracer::Scope gc_scope(tracer_,
3469 GCTracer::Scope::MC_UPDATE_POINTERS_TO_EVACUATED);
3470 SlotsBuffer::UpdateSlotsRecordedIn(heap_,
3471 migration_slots_buffer_,
3472 code_slots_filtering_required);
3473 if (FLAG_trace_fragmentation) {
3474 PrintF(" migration slots buffer: %d\n",
3475 SlotsBuffer::SizeOfChain(migration_slots_buffer_));
3478 if (compacting_ && was_marked_incrementally_) {
3479 // It's difficult to filter out slots recorded for large objects.
3480 LargeObjectIterator it(heap_->lo_space());
3481 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
3482 // LargeObjectSpace is not swept yet thus we have to skip
3483 // dead objects explicitly.
3484 if (!IsMarked(obj)) continue;
3486 Page* p = Page::FromAddress(obj->address());
3487 if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3488 obj->Iterate(&updating_visitor);
3489 p->ClearFlag(Page::RESCAN_ON_EVACUATION);
3495 int npages = evacuation_candidates_.length();
3496 { GCTracer::Scope gc_scope(
3497 tracer_, GCTracer::Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED);
3498 for (int i = 0; i < npages; i++) {
3499 Page* p = evacuation_candidates_[i];
3500 ASSERT(p->IsEvacuationCandidate() ||
3501 p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3503 if (p->IsEvacuationCandidate()) {
3504 SlotsBuffer::UpdateSlotsRecordedIn(heap_,
3506 code_slots_filtering_required);
3507 if (FLAG_trace_fragmentation) {
3508 PrintF(" page %p slots buffer: %d\n",
3509 reinterpret_cast<void*>(p),
3510 SlotsBuffer::SizeOfChain(p->slots_buffer()));
3513 // Important: skip list should be cleared only after roots were updated
3514 // because root iteration traverses the stack and might have to find
3515 // code objects from non-updated pc pointing into evacuation candidate.
3516 SkipList* list = p->skip_list();
3517 if (list != NULL) list->Clear();
3519 if (FLAG_gc_verbose) {
3520 PrintF("Sweeping 0x%" V8PRIxPTR " during evacuation.\n",
3521 reinterpret_cast<intptr_t>(p));
3523 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3524 p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
3526 switch (space->identity()) {
3527 case OLD_DATA_SPACE:
3528 SweepConservatively<SWEEP_SEQUENTIALLY>(space, NULL, p);
3530 case OLD_POINTER_SPACE:
3531 SweepPrecisely<SWEEP_AND_VISIT_LIVE_OBJECTS,
3534 space, p, &updating_visitor);
3537 if (FLAG_zap_code_space) {
3538 SweepPrecisely<SWEEP_AND_VISIT_LIVE_OBJECTS,
3541 space, p, &updating_visitor);
3543 SweepPrecisely<SWEEP_AND_VISIT_LIVE_OBJECTS,
3546 space, p, &updating_visitor);
3557 GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_UPDATE_MISC_POINTERS);
3559 // Update pointers from cells.
3560 HeapObjectIterator cell_iterator(heap_->cell_space());
3561 for (HeapObject* cell = cell_iterator.Next();
3563 cell = cell_iterator.Next()) {
3564 if (cell->IsCell()) {
3565 Cell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3569 HeapObjectIterator js_global_property_cell_iterator(
3570 heap_->property_cell_space());
3571 for (HeapObject* cell = js_global_property_cell_iterator.Next();
3573 cell = js_global_property_cell_iterator.Next()) {
3574 if (cell->IsPropertyCell()) {
3575 PropertyCell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3579 heap_->string_table()->Iterate(&updating_visitor);
3580 updating_visitor.VisitPointer(heap_->weak_object_to_code_table_address());
3581 if (heap_->weak_object_to_code_table()->IsHashTable()) {
3582 WeakHashTable* table =
3583 WeakHashTable::cast(heap_->weak_object_to_code_table());
3584 table->Iterate(&updating_visitor);
3585 table->Rehash(heap_->isolate()->factory()->undefined_value());
3588 // Update pointers from external string table.
3589 heap_->UpdateReferencesInExternalStringTable(
3590 &UpdateReferenceInExternalStringTableEntry);
3592 EvacuationWeakObjectRetainer evacuation_object_retainer;
3593 heap()->ProcessWeakReferences(&evacuation_object_retainer);
3595 // Visit invalidated code (we ignored all slots on it) and clear mark-bits
3597 ProcessInvalidatedCode(&updating_visitor);
3599 heap_->isolate()->inner_pointer_to_code_cache()->Flush();
3602 if (FLAG_verify_heap) {
3603 VerifyEvacuation(heap_);
3607 slots_buffer_allocator_.DeallocateChain(&migration_slots_buffer_);
3608 ASSERT(migration_slots_buffer_ == NULL);
3612 void MarkCompactCollector::MoveEvacuationCandidatesToEndOfPagesList() {
3613 int npages = evacuation_candidates_.length();
3614 for (int i = 0; i < npages; i++) {
3615 Page* p = evacuation_candidates_[i];
3616 if (!p->IsEvacuationCandidate()) continue;
3618 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3619 p->InsertAfter(space->LastPage());
3624 void MarkCompactCollector::ReleaseEvacuationCandidates() {
3625 int npages = evacuation_candidates_.length();
3626 for (int i = 0; i < npages; i++) {
3627 Page* p = evacuation_candidates_[i];
3628 if (!p->IsEvacuationCandidate()) continue;
3629 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3630 space->Free(p->area_start(), p->area_size());
3631 p->set_scan_on_scavenge(false);
3632 slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
3633 p->ResetLiveBytes();
3634 space->ReleasePage(p);
3636 evacuation_candidates_.Rewind(0);
3637 compacting_ = false;
3638 heap()->FreeQueuedChunks();
3642 static const int kStartTableEntriesPerLine = 5;
3643 static const int kStartTableLines = 171;
3644 static const int kStartTableInvalidLine = 127;
3645 static const int kStartTableUnusedEntry = 126;
3647 #define _ kStartTableUnusedEntry
3648 #define X kStartTableInvalidLine
3649 // Mark-bit to object start offset table.
3651 // The line is indexed by the mark bits in a byte. The first number on
3652 // the line describes the number of live object starts for the line and the
3653 // other numbers on the line describe the offsets (in words) of the object
3656 // Since objects are at least 2 words large we don't have entries for two
3657 // consecutive 1 bits. All entries after 170 have at least 2 consecutive bits.
3658 char kStartTable[kStartTableLines * kStartTableEntriesPerLine] = {
3669 2, 1, 3, _, _, // 10
3670 X, _, _, _, _, // 11
3671 X, _, _, _, _, // 12
3672 X, _, _, _, _, // 13
3673 X, _, _, _, _, // 14
3674 X, _, _, _, _, // 15
3675 1, 4, _, _, _, // 16
3676 2, 0, 4, _, _, // 17
3677 2, 1, 4, _, _, // 18
3678 X, _, _, _, _, // 19
3679 2, 2, 4, _, _, // 20
3680 3, 0, 2, 4, _, // 21
3681 X, _, _, _, _, // 22
3682 X, _, _, _, _, // 23
3683 X, _, _, _, _, // 24
3684 X, _, _, _, _, // 25
3685 X, _, _, _, _, // 26
3686 X, _, _, _, _, // 27
3687 X, _, _, _, _, // 28
3688 X, _, _, _, _, // 29
3689 X, _, _, _, _, // 30
3690 X, _, _, _, _, // 31
3691 1, 5, _, _, _, // 32
3692 2, 0, 5, _, _, // 33
3693 2, 1, 5, _, _, // 34
3694 X, _, _, _, _, // 35
3695 2, 2, 5, _, _, // 36
3696 3, 0, 2, 5, _, // 37
3697 X, _, _, _, _, // 38
3698 X, _, _, _, _, // 39
3699 2, 3, 5, _, _, // 40
3700 3, 0, 3, 5, _, // 41
3701 3, 1, 3, 5, _, // 42
3702 X, _, _, _, _, // 43
3703 X, _, _, _, _, // 44
3704 X, _, _, _, _, // 45
3705 X, _, _, _, _, // 46
3706 X, _, _, _, _, // 47
3707 X, _, _, _, _, // 48
3708 X, _, _, _, _, // 49
3709 X, _, _, _, _, // 50
3710 X, _, _, _, _, // 51
3711 X, _, _, _, _, // 52
3712 X, _, _, _, _, // 53
3713 X, _, _, _, _, // 54
3714 X, _, _, _, _, // 55
3715 X, _, _, _, _, // 56
3716 X, _, _, _, _, // 57
3717 X, _, _, _, _, // 58
3718 X, _, _, _, _, // 59
3719 X, _, _, _, _, // 60
3720 X, _, _, _, _, // 61
3721 X, _, _, _, _, // 62
3722 X, _, _, _, _, // 63
3723 1, 6, _, _, _, // 64
3724 2, 0, 6, _, _, // 65
3725 2, 1, 6, _, _, // 66
3726 X, _, _, _, _, // 67
3727 2, 2, 6, _, _, // 68
3728 3, 0, 2, 6, _, // 69
3729 X, _, _, _, _, // 70
3730 X, _, _, _, _, // 71
3731 2, 3, 6, _, _, // 72
3732 3, 0, 3, 6, _, // 73
3733 3, 1, 3, 6, _, // 74
3734 X, _, _, _, _, // 75
3735 X, _, _, _, _, // 76
3736 X, _, _, _, _, // 77
3737 X, _, _, _, _, // 78
3738 X, _, _, _, _, // 79
3739 2, 4, 6, _, _, // 80
3740 3, 0, 4, 6, _, // 81
3741 3, 1, 4, 6, _, // 82
3742 X, _, _, _, _, // 83
3743 3, 2, 4, 6, _, // 84
3744 4, 0, 2, 4, 6, // 85
3745 X, _, _, _, _, // 86
3746 X, _, _, _, _, // 87
3747 X, _, _, _, _, // 88
3748 X, _, _, _, _, // 89
3749 X, _, _, _, _, // 90
3750 X, _, _, _, _, // 91
3751 X, _, _, _, _, // 92
3752 X, _, _, _, _, // 93
3753 X, _, _, _, _, // 94
3754 X, _, _, _, _, // 95
3755 X, _, _, _, _, // 96
3756 X, _, _, _, _, // 97
3757 X, _, _, _, _, // 98
3758 X, _, _, _, _, // 99
3759 X, _, _, _, _, // 100
3760 X, _, _, _, _, // 101
3761 X, _, _, _, _, // 102
3762 X, _, _, _, _, // 103
3763 X, _, _, _, _, // 104
3764 X, _, _, _, _, // 105
3765 X, _, _, _, _, // 106
3766 X, _, _, _, _, // 107
3767 X, _, _, _, _, // 108
3768 X, _, _, _, _, // 109
3769 X, _, _, _, _, // 110
3770 X, _, _, _, _, // 111
3771 X, _, _, _, _, // 112
3772 X, _, _, _, _, // 113
3773 X, _, _, _, _, // 114
3774 X, _, _, _, _, // 115
3775 X, _, _, _, _, // 116
3776 X, _, _, _, _, // 117
3777 X, _, _, _, _, // 118
3778 X, _, _, _, _, // 119
3779 X, _, _, _, _, // 120
3780 X, _, _, _, _, // 121
3781 X, _, _, _, _, // 122
3782 X, _, _, _, _, // 123
3783 X, _, _, _, _, // 124
3784 X, _, _, _, _, // 125
3785 X, _, _, _, _, // 126
3786 X, _, _, _, _, // 127
3787 1, 7, _, _, _, // 128
3788 2, 0, 7, _, _, // 129
3789 2, 1, 7, _, _, // 130
3790 X, _, _, _, _, // 131
3791 2, 2, 7, _, _, // 132
3792 3, 0, 2, 7, _, // 133
3793 X, _, _, _, _, // 134
3794 X, _, _, _, _, // 135
3795 2, 3, 7, _, _, // 136
3796 3, 0, 3, 7, _, // 137
3797 3, 1, 3, 7, _, // 138
3798 X, _, _, _, _, // 139
3799 X, _, _, _, _, // 140
3800 X, _, _, _, _, // 141
3801 X, _, _, _, _, // 142
3802 X, _, _, _, _, // 143
3803 2, 4, 7, _, _, // 144
3804 3, 0, 4, 7, _, // 145
3805 3, 1, 4, 7, _, // 146
3806 X, _, _, _, _, // 147
3807 3, 2, 4, 7, _, // 148
3808 4, 0, 2, 4, 7, // 149
3809 X, _, _, _, _, // 150
3810 X, _, _, _, _, // 151
3811 X, _, _, _, _, // 152
3812 X, _, _, _, _, // 153
3813 X, _, _, _, _, // 154
3814 X, _, _, _, _, // 155
3815 X, _, _, _, _, // 156
3816 X, _, _, _, _, // 157
3817 X, _, _, _, _, // 158
3818 X, _, _, _, _, // 159
3819 2, 5, 7, _, _, // 160
3820 3, 0, 5, 7, _, // 161
3821 3, 1, 5, 7, _, // 162
3822 X, _, _, _, _, // 163
3823 3, 2, 5, 7, _, // 164
3824 4, 0, 2, 5, 7, // 165
3825 X, _, _, _, _, // 166
3826 X, _, _, _, _, // 167
3827 3, 3, 5, 7, _, // 168
3828 4, 0, 3, 5, 7, // 169
3829 4, 1, 3, 5, 7 // 170
3835 // Takes a word of mark bits. Returns the number of objects that start in the
3836 // range. Puts the offsets of the words in the supplied array.
3837 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts) {
3841 // No consecutive 1 bits.
3842 ASSERT((mark_bits & 0x180) != 0x180);
3843 ASSERT((mark_bits & 0x18000) != 0x18000);
3844 ASSERT((mark_bits & 0x1800000) != 0x1800000);
3846 while (mark_bits != 0) {
3847 int byte = (mark_bits & 0xff);
3850 ASSERT(byte < kStartTableLines); // No consecutive 1 bits.
3851 char* table = kStartTable + byte * kStartTableEntriesPerLine;
3852 int objects_in_these_8_words = table[0];
3853 ASSERT(objects_in_these_8_words != kStartTableInvalidLine);
3854 ASSERT(objects_in_these_8_words < kStartTableEntriesPerLine);
3855 for (int i = 0; i < objects_in_these_8_words; i++) {
3856 starts[objects++] = offset + table[1 + i];
3865 static inline Address DigestFreeStart(Address approximate_free_start,
3866 uint32_t free_start_cell) {
3867 ASSERT(free_start_cell != 0);
3869 // No consecutive 1 bits.
3870 ASSERT((free_start_cell & (free_start_cell << 1)) == 0);
3873 uint32_t cell = free_start_cell;
3874 int offset_of_last_live;
3875 if ((cell & 0x80000000u) != 0) {
3876 // This case would overflow below.
3877 offset_of_last_live = 31;
3879 // Remove all but one bit, the most significant. This is an optimization
3880 // that may or may not be worthwhile.
3886 cell = (cell + 1) >> 1;
3887 int live_objects = MarkWordToObjectStarts(cell, offsets);
3888 ASSERT(live_objects == 1);
3889 offset_of_last_live = offsets[live_objects - 1];
3891 Address last_live_start =
3892 approximate_free_start + offset_of_last_live * kPointerSize;
3893 HeapObject* last_live = HeapObject::FromAddress(last_live_start);
3894 Address free_start = last_live_start + last_live->Size();
3899 static inline Address StartOfLiveObject(Address block_address, uint32_t cell) {
3902 // No consecutive 1 bits.
3903 ASSERT((cell & (cell << 1)) == 0);
3906 if (cell == 0x80000000u) { // Avoid overflow below.
3907 return block_address + 31 * kPointerSize;
3909 uint32_t first_set_bit = ((cell ^ (cell - 1)) + 1) >> 1;
3910 ASSERT((first_set_bit & cell) == first_set_bit);
3911 int live_objects = MarkWordToObjectStarts(first_set_bit, offsets);
3912 ASSERT(live_objects == 1);
3914 return block_address + offsets[0] * kPointerSize;
3918 template<MarkCompactCollector::SweepingParallelism mode>
3919 static intptr_t Free(PagedSpace* space,
3920 FreeList* free_list,
3923 if (mode == MarkCompactCollector::SWEEP_SEQUENTIALLY) {
3924 return space->Free(start, size);
3926 return size - free_list->Free(start, size);
3931 // Force instantiation of templatized SweepConservatively method for
3932 // SWEEP_SEQUENTIALLY mode.
3933 template intptr_t MarkCompactCollector::
3934 SweepConservatively<MarkCompactCollector::SWEEP_SEQUENTIALLY>(
3935 PagedSpace*, FreeList*, Page*);
3938 // Force instantiation of templatized SweepConservatively method for
3939 // SWEEP_IN_PARALLEL mode.
3940 template intptr_t MarkCompactCollector::
3941 SweepConservatively<MarkCompactCollector::SWEEP_IN_PARALLEL>(
3942 PagedSpace*, FreeList*, Page*);
3945 // Sweeps a space conservatively. After this has been done the larger free
3946 // spaces have been put on the free list and the smaller ones have been
3947 // ignored and left untouched. A free space is always either ignored or put
3948 // on the free list, never split up into two parts. This is important
3949 // because it means that any FreeSpace maps left actually describe a region of
3950 // memory that can be ignored when scanning. Dead objects other than free
3951 // spaces will not contain the free space map.
3952 template<MarkCompactCollector::SweepingParallelism mode>
3953 intptr_t MarkCompactCollector::SweepConservatively(PagedSpace* space,
3954 FreeList* free_list,
3956 ASSERT(!p->IsEvacuationCandidate() && !p->WasSwept());
3957 ASSERT((mode == MarkCompactCollector::SWEEP_IN_PARALLEL &&
3958 free_list != NULL) ||
3959 (mode == MarkCompactCollector::SWEEP_SEQUENTIALLY &&
3960 free_list == NULL));
3962 // When parallel sweeping is active, the page will be marked after
3963 // sweeping by the main thread.
3964 if (mode != MarkCompactCollector::SWEEP_IN_PARALLEL) {
3965 p->MarkSweptConservatively();
3968 intptr_t freed_bytes = 0;
3971 // Skip over all the dead objects at the start of the page and mark them free.
3972 Address cell_base = 0;
3973 MarkBit::CellType* cell = NULL;
3974 MarkBitCellIterator it(p);
3975 for (; !it.Done(); it.Advance()) {
3976 cell_base = it.CurrentCellBase();
3977 cell = it.CurrentCell();
3978 if (*cell != 0) break;
3982 size = p->area_end() - p->area_start();
3983 freed_bytes += Free<mode>(space, free_list, p->area_start(),
3984 static_cast<int>(size));
3985 ASSERT_EQ(0, p->LiveBytes());
3989 // Grow the size of the start-of-page free space a little to get up to the
3990 // first live object.
3991 Address free_end = StartOfLiveObject(cell_base, *cell);
3992 // Free the first free space.
3993 size = free_end - p->area_start();
3994 freed_bytes += Free<mode>(space, free_list, p->area_start(),
3995 static_cast<int>(size));
3997 // The start of the current free area is represented in undigested form by
3998 // the address of the last 32-word section that contained a live object and
3999 // the marking bitmap for that cell, which describes where the live object
4000 // started. Unless we find a large free space in the bitmap we will not
4001 // digest this pair into a real address. We start the iteration here at the
4002 // first word in the marking bit map that indicates a live object.
4003 Address free_start = cell_base;
4004 MarkBit::CellType free_start_cell = *cell;
4006 for (; !it.Done(); it.Advance()) {
4007 cell_base = it.CurrentCellBase();
4008 cell = it.CurrentCell();
4010 // We have a live object. Check approximately whether it is more than 32
4011 // words since the last live object.
4012 if (cell_base - free_start > 32 * kPointerSize) {
4013 free_start = DigestFreeStart(free_start, free_start_cell);
4014 if (cell_base - free_start > 32 * kPointerSize) {
4015 // Now that we know the exact start of the free space it still looks
4016 // like we have a large enough free space to be worth bothering with.
4017 // so now we need to find the start of the first live object at the
4018 // end of the free space.
4019 free_end = StartOfLiveObject(cell_base, *cell);
4020 freed_bytes += Free<mode>(space, free_list, free_start,
4021 static_cast<int>(free_end - free_start));
4024 // Update our undigested record of where the current free area started.
4025 free_start = cell_base;
4026 free_start_cell = *cell;
4027 // Clear marking bits for current cell.
4032 // Handle the free space at the end of the page.
4033 if (cell_base - free_start > 32 * kPointerSize) {
4034 free_start = DigestFreeStart(free_start, free_start_cell);
4035 freed_bytes += Free<mode>(space, free_list, free_start,
4036 static_cast<int>(p->area_end() - free_start));
4039 p->ResetLiveBytes();
4044 void MarkCompactCollector::SweepInParallel(PagedSpace* space) {
4045 PageIterator it(space);
4046 FreeList* free_list = space == heap()->old_pointer_space()
4047 ? free_list_old_pointer_space_.get()
4048 : free_list_old_data_space_.get();
4049 FreeList private_free_list(space);
4050 while (it.has_next()) {
4051 Page* p = it.next();
4053 if (p->TryParallelSweeping()) {
4054 SweepConservatively<SWEEP_IN_PARALLEL>(space, &private_free_list, p);
4055 free_list->Concatenate(&private_free_list);
4056 p->set_parallel_sweeping(MemoryChunk::PARALLEL_SWEEPING_FINALIZE);
4058 if (p == space->end_of_unswept_pages()) break;
4063 void MarkCompactCollector::SweepSpace(PagedSpace* space, SweeperType sweeper) {
4064 space->set_was_swept_conservatively(sweeper == CONSERVATIVE ||
4065 sweeper == PARALLEL_CONSERVATIVE ||
4066 sweeper == CONCURRENT_CONSERVATIVE);
4067 space->ClearStats();
4069 // We defensively initialize end_of_unswept_pages_ here with the first page
4070 // of the pages list.
4071 space->set_end_of_unswept_pages(space->FirstPage());
4073 PageIterator it(space);
4075 int pages_swept = 0;
4076 bool unused_page_present = false;
4077 bool parallel_sweeping_active = false;
4079 while (it.has_next()) {
4080 Page* p = it.next();
4081 ASSERT(p->parallel_sweeping() == MemoryChunk::PARALLEL_SWEEPING_DONE);
4083 // Clear sweeping flags indicating that marking bits are still intact.
4084 p->ClearSweptPrecisely();
4085 p->ClearSweptConservatively();
4087 if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION) ||
4088 p->IsEvacuationCandidate()) {
4089 // Will be processed in EvacuateNewSpaceAndCandidates.
4090 ASSERT(evacuation_candidates_.length() > 0);
4094 // One unused page is kept, all further are released before sweeping them.
4095 if (p->LiveBytes() == 0) {
4096 if (unused_page_present) {
4097 if (FLAG_gc_verbose) {
4098 PrintF("Sweeping 0x%" V8PRIxPTR " released page.\n",
4099 reinterpret_cast<intptr_t>(p));
4101 // Adjust unswept free bytes because releasing a page expects said
4102 // counter to be accurate for unswept pages.
4103 space->IncreaseUnsweptFreeBytes(p);
4104 space->ReleasePage(p);
4107 unused_page_present = true;
4111 case CONSERVATIVE: {
4112 if (FLAG_gc_verbose) {
4113 PrintF("Sweeping 0x%" V8PRIxPTR " conservatively.\n",
4114 reinterpret_cast<intptr_t>(p));
4116 SweepConservatively<SWEEP_SEQUENTIALLY>(space, NULL, p);
4120 case CONCURRENT_CONSERVATIVE:
4121 case PARALLEL_CONSERVATIVE: {
4122 if (!parallel_sweeping_active) {
4123 if (FLAG_gc_verbose) {
4124 PrintF("Sweeping 0x%" V8PRIxPTR " conservatively.\n",
4125 reinterpret_cast<intptr_t>(p));
4127 SweepConservatively<SWEEP_SEQUENTIALLY>(space, NULL, p);
4129 parallel_sweeping_active = true;
4131 if (FLAG_gc_verbose) {
4132 PrintF("Sweeping 0x%" V8PRIxPTR " conservatively in parallel.\n",
4133 reinterpret_cast<intptr_t>(p));
4135 p->set_parallel_sweeping(MemoryChunk::PARALLEL_SWEEPING_PENDING);
4136 space->IncreaseUnsweptFreeBytes(p);
4138 space->set_end_of_unswept_pages(p);
4142 if (FLAG_gc_verbose) {
4143 PrintF("Sweeping 0x%" V8PRIxPTR " precisely.\n",
4144 reinterpret_cast<intptr_t>(p));
4146 if (space->identity() == CODE_SPACE && FLAG_zap_code_space) {
4147 SweepPrecisely<SWEEP_ONLY, REBUILD_SKIP_LIST, ZAP_FREE_SPACE>(
4149 } else if (space->identity() == CODE_SPACE) {
4150 SweepPrecisely<SWEEP_ONLY, REBUILD_SKIP_LIST, IGNORE_FREE_SPACE>(
4153 SweepPrecisely<SWEEP_ONLY, IGNORE_SKIP_LIST, IGNORE_FREE_SPACE>(
4165 if (FLAG_gc_verbose) {
4166 PrintF("SweepSpace: %s (%d pages swept)\n",
4167 AllocationSpaceName(space->identity()),
4171 // Give pages that are queued to be freed back to the OS.
4172 heap()->FreeQueuedChunks();
4176 void MarkCompactCollector::SweepSpaces() {
4177 GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP);
4179 state_ = SWEEP_SPACES;
4181 SweeperType how_to_sweep = CONSERVATIVE;
4182 if (AreSweeperThreadsActivated()) {
4183 if (FLAG_parallel_sweeping) how_to_sweep = PARALLEL_CONSERVATIVE;
4184 if (FLAG_concurrent_sweeping) how_to_sweep = CONCURRENT_CONSERVATIVE;
4186 if (sweep_precisely_) how_to_sweep = PRECISE;
4188 MoveEvacuationCandidatesToEndOfPagesList();
4190 // Noncompacting collections simply sweep the spaces to clear the mark
4191 // bits and free the nonlive blocks (for old and map spaces). We sweep
4192 // the map space last because freeing non-live maps overwrites them and
4193 // the other spaces rely on possibly non-live maps to get the sizes for
4194 // non-live objects.
4195 { GCTracer::Scope sweep_scope(tracer_, GCTracer::Scope::MC_SWEEP_OLDSPACE);
4196 { SequentialSweepingScope scope(this);
4197 SweepSpace(heap()->old_pointer_space(), how_to_sweep);
4198 SweepSpace(heap()->old_data_space(), how_to_sweep);
4201 if (how_to_sweep == PARALLEL_CONSERVATIVE ||
4202 how_to_sweep == CONCURRENT_CONSERVATIVE) {
4203 StartSweeperThreads();
4206 if (how_to_sweep == PARALLEL_CONSERVATIVE) {
4207 WaitUntilSweepingCompleted();
4210 RemoveDeadInvalidatedCode();
4211 SweepSpace(heap()->code_space(), PRECISE);
4213 SweepSpace(heap()->cell_space(), PRECISE);
4214 SweepSpace(heap()->property_cell_space(), PRECISE);
4216 EvacuateNewSpaceAndCandidates();
4218 // ClearNonLiveTransitions depends on precise sweeping of map space to
4219 // detect whether unmarked map became dead in this collection or in one
4220 // of the previous ones.
4221 SweepSpace(heap()->map_space(), PRECISE);
4223 // Deallocate unmarked objects and clear marked bits for marked objects.
4224 heap_->lo_space()->FreeUnmarkedObjects();
4226 // Deallocate evacuated candidate pages.
4227 ReleaseEvacuationCandidates();
4231 void MarkCompactCollector::ParallelSweepSpaceComplete(PagedSpace* space) {
4232 PageIterator it(space);
4233 while (it.has_next()) {
4234 Page* p = it.next();
4235 if (p->parallel_sweeping() == MemoryChunk::PARALLEL_SWEEPING_FINALIZE) {
4236 p->set_parallel_sweeping(MemoryChunk::PARALLEL_SWEEPING_DONE);
4237 p->MarkSweptConservatively();
4239 ASSERT(p->parallel_sweeping() == MemoryChunk::PARALLEL_SWEEPING_DONE);
4244 void MarkCompactCollector::ParallelSweepSpacesComplete() {
4245 ParallelSweepSpaceComplete(heap()->old_pointer_space());
4246 ParallelSweepSpaceComplete(heap()->old_data_space());
4250 void MarkCompactCollector::EnableCodeFlushing(bool enable) {
4251 if (isolate()->debug()->is_loaded() ||
4252 isolate()->debug()->has_break_points()) {
4257 if (code_flusher_ != NULL) return;
4258 code_flusher_ = new CodeFlusher(isolate());
4260 if (code_flusher_ == NULL) return;
4261 code_flusher_->EvictAllCandidates();
4262 delete code_flusher_;
4263 code_flusher_ = NULL;
4266 if (FLAG_trace_code_flushing) {
4267 PrintF("[code-flushing is now %s]\n", enable ? "on" : "off");
4272 // TODO(1466) ReportDeleteIfNeeded is not called currently.
4273 // Our profiling tools do not expect intersections between
4274 // code objects. We should either reenable it or change our tools.
4275 void MarkCompactCollector::ReportDeleteIfNeeded(HeapObject* obj,
4277 #ifdef ENABLE_GDB_JIT_INTERFACE
4278 if (obj->IsCode()) {
4279 GDBJITInterface::RemoveCode(reinterpret_cast<Code*>(obj));
4282 if (obj->IsCode()) {
4283 PROFILE(isolate, CodeDeleteEvent(obj->address()));
4288 Isolate* MarkCompactCollector::isolate() const {
4289 return heap_->isolate();
4293 void MarkCompactCollector::Initialize() {
4294 MarkCompactMarkingVisitor::Initialize();
4295 IncrementalMarking::Initialize();
4299 bool SlotsBuffer::IsTypedSlot(ObjectSlot slot) {
4300 return reinterpret_cast<uintptr_t>(slot) < NUMBER_OF_SLOT_TYPES;
4304 bool SlotsBuffer::AddTo(SlotsBufferAllocator* allocator,
4305 SlotsBuffer** buffer_address,
4308 AdditionMode mode) {
4309 SlotsBuffer* buffer = *buffer_address;
4310 if (buffer == NULL || !buffer->HasSpaceForTypedSlot()) {
4311 if (mode == FAIL_ON_OVERFLOW && ChainLengthThresholdReached(buffer)) {
4312 allocator->DeallocateChain(buffer_address);
4315 buffer = allocator->AllocateBuffer(buffer);
4316 *buffer_address = buffer;
4318 ASSERT(buffer->HasSpaceForTypedSlot());
4319 buffer->Add(reinterpret_cast<ObjectSlot>(type));
4320 buffer->Add(reinterpret_cast<ObjectSlot>(addr));
4325 static inline SlotsBuffer::SlotType SlotTypeForRMode(RelocInfo::Mode rmode) {
4326 if (RelocInfo::IsCodeTarget(rmode)) {
4327 return SlotsBuffer::CODE_TARGET_SLOT;
4328 } else if (RelocInfo::IsEmbeddedObject(rmode)) {
4329 return SlotsBuffer::EMBEDDED_OBJECT_SLOT;
4330 } else if (RelocInfo::IsDebugBreakSlot(rmode)) {
4331 return SlotsBuffer::DEBUG_TARGET_SLOT;
4332 } else if (RelocInfo::IsJSReturn(rmode)) {
4333 return SlotsBuffer::JS_RETURN_SLOT;
4336 return SlotsBuffer::NUMBER_OF_SLOT_TYPES;
4340 void MarkCompactCollector::RecordRelocSlot(RelocInfo* rinfo, Object* target) {
4341 Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4342 RelocInfo::Mode rmode = rinfo->rmode();
4343 if (target_page->IsEvacuationCandidate() &&
4344 (rinfo->host() == NULL ||
4345 !ShouldSkipEvacuationSlotRecording(rinfo->host()))) {
4347 if (RelocInfo::IsEmbeddedObject(rmode) && rinfo->IsInConstantPool()) {
4348 // This doesn't need to be typed since it is just a normal heap pointer.
4349 Object** target_pointer =
4350 reinterpret_cast<Object**>(rinfo->constant_pool_entry_address());
4351 success = SlotsBuffer::AddTo(&slots_buffer_allocator_,
4352 target_page->slots_buffer_address(),
4354 SlotsBuffer::FAIL_ON_OVERFLOW);
4355 } else if (RelocInfo::IsCodeTarget(rmode) && rinfo->IsInConstantPool()) {
4356 success = SlotsBuffer::AddTo(&slots_buffer_allocator_,
4357 target_page->slots_buffer_address(),
4358 SlotsBuffer::CODE_ENTRY_SLOT,
4359 rinfo->constant_pool_entry_address(),
4360 SlotsBuffer::FAIL_ON_OVERFLOW);
4362 success = SlotsBuffer::AddTo(&slots_buffer_allocator_,
4363 target_page->slots_buffer_address(),
4364 SlotTypeForRMode(rmode),
4366 SlotsBuffer::FAIL_ON_OVERFLOW);
4369 EvictEvacuationCandidate(target_page);
4375 void MarkCompactCollector::RecordCodeEntrySlot(Address slot, Code* target) {
4376 Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4377 if (target_page->IsEvacuationCandidate() &&
4378 !ShouldSkipEvacuationSlotRecording(reinterpret_cast<Object**>(slot))) {
4379 if (!SlotsBuffer::AddTo(&slots_buffer_allocator_,
4380 target_page->slots_buffer_address(),
4381 SlotsBuffer::CODE_ENTRY_SLOT,
4383 SlotsBuffer::FAIL_ON_OVERFLOW)) {
4384 EvictEvacuationCandidate(target_page);
4390 void MarkCompactCollector::RecordCodeTargetPatch(Address pc, Code* target) {
4391 ASSERT(heap()->gc_state() == Heap::MARK_COMPACT);
4392 if (is_compacting()) {
4393 Code* host = isolate()->inner_pointer_to_code_cache()->
4394 GcSafeFindCodeForInnerPointer(pc);
4395 MarkBit mark_bit = Marking::MarkBitFrom(host);
4396 if (Marking::IsBlack(mark_bit)) {
4397 RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
4398 RecordRelocSlot(&rinfo, target);
4404 static inline SlotsBuffer::SlotType DecodeSlotType(
4405 SlotsBuffer::ObjectSlot slot) {
4406 return static_cast<SlotsBuffer::SlotType>(reinterpret_cast<intptr_t>(slot));
4410 void SlotsBuffer::UpdateSlots(Heap* heap) {
4411 PointersUpdatingVisitor v(heap);
4413 for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4414 ObjectSlot slot = slots_[slot_idx];
4415 if (!IsTypedSlot(slot)) {
4416 PointersUpdatingVisitor::UpdateSlot(heap, slot);
4419 ASSERT(slot_idx < idx_);
4420 UpdateSlot(heap->isolate(),
4422 DecodeSlotType(slot),
4423 reinterpret_cast<Address>(slots_[slot_idx]));
4429 void SlotsBuffer::UpdateSlotsWithFilter(Heap* heap) {
4430 PointersUpdatingVisitor v(heap);
4432 for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4433 ObjectSlot slot = slots_[slot_idx];
4434 if (!IsTypedSlot(slot)) {
4435 if (!IsOnInvalidatedCodeObject(reinterpret_cast<Address>(slot))) {
4436 PointersUpdatingVisitor::UpdateSlot(heap, slot);
4440 ASSERT(slot_idx < idx_);
4441 Address pc = reinterpret_cast<Address>(slots_[slot_idx]);
4442 if (!IsOnInvalidatedCodeObject(pc)) {
4443 UpdateSlot(heap->isolate(),
4445 DecodeSlotType(slot),
4446 reinterpret_cast<Address>(slots_[slot_idx]));
4453 SlotsBuffer* SlotsBufferAllocator::AllocateBuffer(SlotsBuffer* next_buffer) {
4454 return new SlotsBuffer(next_buffer);
4458 void SlotsBufferAllocator::DeallocateBuffer(SlotsBuffer* buffer) {
4463 void SlotsBufferAllocator::DeallocateChain(SlotsBuffer** buffer_address) {
4464 SlotsBuffer* buffer = *buffer_address;
4465 while (buffer != NULL) {
4466 SlotsBuffer* next_buffer = buffer->next();
4467 DeallocateBuffer(buffer);
4468 buffer = next_buffer;
4470 *buffer_address = NULL;
4474 } } // namespace v8::internal