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/base/bits.h"
9 #include "src/code-stubs.h"
10 #include "src/compilation-cache.h"
11 #include "src/cpu-profiler.h"
12 #include "src/deoptimizer.h"
13 #include "src/execution.h"
14 #include "src/gdb-jit.h"
15 #include "src/global-handles.h"
16 #include "src/heap/incremental-marking.h"
17 #include "src/heap/mark-compact.h"
18 #include "src/heap/objects-visiting.h"
19 #include "src/heap/objects-visiting-inl.h"
20 #include "src/heap/spaces-inl.h"
21 #include "src/heap-profiler.h"
22 #include "src/ic/ic.h"
23 #include "src/ic/stub-cache.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)
43 reduce_memory_footprint_(false),
44 abort_incremental_marking_(false),
45 marking_parity_(ODD_MARKING_PARITY),
47 was_marked_incrementally_(false),
48 sweeping_in_progress_(false),
49 pending_sweeper_jobs_semaphore_(0),
51 migration_slots_buffer_(NULL),
53 marking_deque_memory_(NULL),
54 marking_deque_memory_committed_(false),
56 have_code_to_deoptimize_(false) {
60 class VerifyMarkingVisitor : public ObjectVisitor {
62 explicit VerifyMarkingVisitor(Heap* heap) : heap_(heap) {}
64 void VisitPointers(Object** start, Object** end) {
65 for (Object** current = start; current < end; current++) {
66 if ((*current)->IsHeapObject()) {
67 HeapObject* object = HeapObject::cast(*current);
68 CHECK(heap_->mark_compact_collector()->IsMarked(object));
73 void VisitEmbeddedPointer(RelocInfo* rinfo) {
74 DCHECK(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
75 if (!rinfo->host()->IsWeakObject(rinfo->target_object())) {
76 Object* p = rinfo->target_object();
81 void VisitCell(RelocInfo* rinfo) {
82 Code* code = rinfo->host();
83 DCHECK(rinfo->rmode() == RelocInfo::CELL);
84 if (!code->IsWeakObject(rinfo->target_cell())) {
85 ObjectVisitor::VisitCell(rinfo);
94 static void VerifyMarking(Heap* heap, Address bottom, Address top) {
95 VerifyMarkingVisitor visitor(heap);
97 Address next_object_must_be_here_or_later = bottom;
99 for (Address current = bottom; current < top; 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(Page* page) {
172 VerifyEvacuationVisitor visitor;
173 HeapObjectIterator iterator(page, NULL);
174 for (HeapObject* heap_object = iterator.Next(); heap_object != NULL;
175 heap_object = iterator.Next()) {
176 // We skip free space objects.
177 if (!heap_object->IsFiller()) {
178 heap_object->Iterate(&visitor);
184 static void VerifyEvacuation(NewSpace* space) {
185 NewSpacePageIterator it(space->bottom(), space->top());
186 VerifyEvacuationVisitor visitor;
188 while (it.has_next()) {
189 NewSpacePage* page = it.next();
190 Address current = page->area_start();
191 Address limit = it.has_next() ? page->area_end() : space->top();
192 CHECK(limit == space->top() || !page->Contains(space->top()));
193 while (current < limit) {
194 HeapObject* object = HeapObject::FromAddress(current);
195 object->Iterate(&visitor);
196 current += object->Size();
202 static void VerifyEvacuation(Heap* heap, PagedSpace* space) {
203 if (FLAG_use_allocation_folding &&
204 (space == heap->old_pointer_space() || space == heap->old_data_space())) {
207 PageIterator it(space);
209 while (it.has_next()) {
211 if (p->IsEvacuationCandidate()) continue;
217 static void VerifyEvacuation(Heap* heap) {
218 VerifyEvacuation(heap, heap->old_pointer_space());
219 VerifyEvacuation(heap, heap->old_data_space());
220 VerifyEvacuation(heap, heap->code_space());
221 VerifyEvacuation(heap, heap->cell_space());
222 VerifyEvacuation(heap, heap->property_cell_space());
223 VerifyEvacuation(heap, heap->map_space());
224 VerifyEvacuation(heap->new_space());
226 VerifyEvacuationVisitor visitor;
227 heap->IterateStrongRoots(&visitor, VISIT_ALL);
229 #endif // VERIFY_HEAP
232 void MarkCompactCollector::SetUp() {
233 free_list_old_data_space_.Reset(new FreeList(heap_->old_data_space()));
234 free_list_old_pointer_space_.Reset(new FreeList(heap_->old_pointer_space()));
238 void MarkCompactCollector::TearDown() {
240 delete marking_deque_memory_;
244 void MarkCompactCollector::AddEvacuationCandidate(Page* p) {
245 p->MarkEvacuationCandidate();
246 evacuation_candidates_.Add(p);
250 static void TraceFragmentation(PagedSpace* space) {
251 int number_of_pages = space->CountTotalPages();
252 intptr_t reserved = (number_of_pages * space->AreaSize());
253 intptr_t free = reserved - space->SizeOfObjects();
254 PrintF("[%s]: %d pages, %d (%.1f%%) free\n",
255 AllocationSpaceName(space->identity()), number_of_pages,
256 static_cast<int>(free), static_cast<double>(free) * 100 / reserved);
260 bool MarkCompactCollector::StartCompaction(CompactionMode mode) {
262 DCHECK(evacuation_candidates_.length() == 0);
264 #ifdef ENABLE_GDB_JIT_INTERFACE
265 // If GDBJIT interface is active disable compaction.
266 if (FLAG_gdbjit) return false;
269 CollectEvacuationCandidates(heap()->old_pointer_space());
270 CollectEvacuationCandidates(heap()->old_data_space());
272 if (FLAG_compact_code_space && (mode == NON_INCREMENTAL_COMPACTION ||
273 FLAG_incremental_code_compaction)) {
274 CollectEvacuationCandidates(heap()->code_space());
275 } else if (FLAG_trace_fragmentation) {
276 TraceFragmentation(heap()->code_space());
279 if (FLAG_trace_fragmentation) {
280 TraceFragmentation(heap()->map_space());
281 TraceFragmentation(heap()->cell_space());
282 TraceFragmentation(heap()->property_cell_space());
285 heap()->old_pointer_space()->EvictEvacuationCandidatesFromFreeLists();
286 heap()->old_data_space()->EvictEvacuationCandidatesFromFreeLists();
287 heap()->code_space()->EvictEvacuationCandidatesFromFreeLists();
289 compacting_ = evacuation_candidates_.length() > 0;
296 void MarkCompactCollector::CollectGarbage() {
297 // Make sure that Prepare() has been called. The individual steps below will
298 // update the state as they proceed.
299 DCHECK(state_ == PREPARE_GC);
302 DCHECK(heap_->incremental_marking()->IsStopped());
304 if (FLAG_collect_maps) ClearNonLiveReferences();
306 ProcessAndClearWeakCells();
308 ClearWeakCollections();
310 heap_->set_encountered_weak_cells(Smi::FromInt(0));
312 isolate()->global_handles()->CollectPhantomCallbackData();
315 if (FLAG_verify_heap) {
316 VerifyMarking(heap_);
323 if (heap()->weak_embedded_objects_verification_enabled()) {
324 VerifyWeakEmbeddedObjectsInCode();
326 if (FLAG_collect_maps && FLAG_omit_map_checks_for_leaf_maps) {
327 VerifyOmittedMapChecks();
333 if (marking_parity_ == EVEN_MARKING_PARITY) {
334 marking_parity_ = ODD_MARKING_PARITY;
336 DCHECK(marking_parity_ == ODD_MARKING_PARITY);
337 marking_parity_ = EVEN_MARKING_PARITY;
343 void MarkCompactCollector::VerifyMarkbitsAreClean(PagedSpace* space) {
344 PageIterator it(space);
346 while (it.has_next()) {
348 CHECK(p->markbits()->IsClean());
349 CHECK_EQ(0, p->LiveBytes());
354 void MarkCompactCollector::VerifyMarkbitsAreClean(NewSpace* space) {
355 NewSpacePageIterator it(space->bottom(), space->top());
357 while (it.has_next()) {
358 NewSpacePage* p = it.next();
359 CHECK(p->markbits()->IsClean());
360 CHECK_EQ(0, p->LiveBytes());
365 void MarkCompactCollector::VerifyMarkbitsAreClean() {
366 VerifyMarkbitsAreClean(heap_->old_pointer_space());
367 VerifyMarkbitsAreClean(heap_->old_data_space());
368 VerifyMarkbitsAreClean(heap_->code_space());
369 VerifyMarkbitsAreClean(heap_->cell_space());
370 VerifyMarkbitsAreClean(heap_->property_cell_space());
371 VerifyMarkbitsAreClean(heap_->map_space());
372 VerifyMarkbitsAreClean(heap_->new_space());
374 LargeObjectIterator it(heap_->lo_space());
375 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
376 MarkBit mark_bit = Marking::MarkBitFrom(obj);
377 CHECK(Marking::IsWhite(mark_bit));
378 CHECK_EQ(0, Page::FromAddress(obj->address())->LiveBytes());
383 void MarkCompactCollector::VerifyWeakEmbeddedObjectsInCode() {
384 HeapObjectIterator code_iterator(heap()->code_space());
385 for (HeapObject* obj = code_iterator.Next(); obj != NULL;
386 obj = code_iterator.Next()) {
387 Code* code = Code::cast(obj);
388 if (!code->is_optimized_code()) continue;
389 if (WillBeDeoptimized(code)) continue;
390 code->VerifyEmbeddedObjectsDependency();
395 void MarkCompactCollector::VerifyOmittedMapChecks() {
396 HeapObjectIterator iterator(heap()->map_space());
397 for (HeapObject* obj = iterator.Next(); obj != NULL; obj = iterator.Next()) {
398 Map* map = Map::cast(obj);
399 map->VerifyOmittedMapChecks();
402 #endif // VERIFY_HEAP
405 static void ClearMarkbitsInPagedSpace(PagedSpace* space) {
406 PageIterator it(space);
408 while (it.has_next()) {
409 Bitmap::Clear(it.next());
414 static void ClearMarkbitsInNewSpace(NewSpace* space) {
415 NewSpacePageIterator it(space->ToSpaceStart(), space->ToSpaceEnd());
417 while (it.has_next()) {
418 Bitmap::Clear(it.next());
423 void MarkCompactCollector::ClearMarkbits() {
424 ClearMarkbitsInPagedSpace(heap_->code_space());
425 ClearMarkbitsInPagedSpace(heap_->map_space());
426 ClearMarkbitsInPagedSpace(heap_->old_pointer_space());
427 ClearMarkbitsInPagedSpace(heap_->old_data_space());
428 ClearMarkbitsInPagedSpace(heap_->cell_space());
429 ClearMarkbitsInPagedSpace(heap_->property_cell_space());
430 ClearMarkbitsInNewSpace(heap_->new_space());
432 LargeObjectIterator it(heap_->lo_space());
433 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
434 MarkBit mark_bit = Marking::MarkBitFrom(obj);
436 mark_bit.Next().Clear();
437 Page::FromAddress(obj->address())->ResetProgressBar();
438 Page::FromAddress(obj->address())->ResetLiveBytes();
443 class MarkCompactCollector::SweeperTask : public v8::Task {
445 SweeperTask(Heap* heap, PagedSpace* space) : heap_(heap), space_(space) {}
447 virtual ~SweeperTask() {}
450 // v8::Task overrides.
451 void Run() OVERRIDE {
452 heap_->mark_compact_collector()->SweepInParallel(space_, 0);
453 heap_->mark_compact_collector()->pending_sweeper_jobs_semaphore_.Signal();
459 DISALLOW_COPY_AND_ASSIGN(SweeperTask);
463 void MarkCompactCollector::StartSweeperThreads() {
464 DCHECK(free_list_old_pointer_space_.get()->IsEmpty());
465 DCHECK(free_list_old_data_space_.get()->IsEmpty());
466 V8::GetCurrentPlatform()->CallOnBackgroundThread(
467 new SweeperTask(heap(), heap()->old_data_space()),
468 v8::Platform::kShortRunningTask);
469 V8::GetCurrentPlatform()->CallOnBackgroundThread(
470 new SweeperTask(heap(), heap()->old_pointer_space()),
471 v8::Platform::kShortRunningTask);
475 void MarkCompactCollector::EnsureSweepingCompleted() {
476 DCHECK(sweeping_in_progress_ == true);
478 // If sweeping is not completed or not running at all, we try to complete it
480 if (!FLAG_concurrent_sweeping || !IsSweepingCompleted()) {
481 SweepInParallel(heap()->paged_space(OLD_DATA_SPACE), 0);
482 SweepInParallel(heap()->paged_space(OLD_POINTER_SPACE), 0);
484 // Wait twice for both jobs.
485 if (FLAG_concurrent_sweeping) {
486 pending_sweeper_jobs_semaphore_.Wait();
487 pending_sweeper_jobs_semaphore_.Wait();
489 ParallelSweepSpacesComplete();
490 sweeping_in_progress_ = false;
491 RefillFreeList(heap()->paged_space(OLD_DATA_SPACE));
492 RefillFreeList(heap()->paged_space(OLD_POINTER_SPACE));
493 heap()->paged_space(OLD_DATA_SPACE)->ResetUnsweptFreeBytes();
494 heap()->paged_space(OLD_POINTER_SPACE)->ResetUnsweptFreeBytes();
497 if (FLAG_verify_heap && !evacuation()) {
498 VerifyEvacuation(heap_);
504 bool MarkCompactCollector::IsSweepingCompleted() {
505 if (!pending_sweeper_jobs_semaphore_.WaitFor(
506 base::TimeDelta::FromSeconds(0))) {
509 pending_sweeper_jobs_semaphore_.Signal();
514 void MarkCompactCollector::RefillFreeList(PagedSpace* space) {
517 if (space == heap()->old_pointer_space()) {
518 free_list = free_list_old_pointer_space_.get();
519 } else if (space == heap()->old_data_space()) {
520 free_list = free_list_old_data_space_.get();
522 // Any PagedSpace might invoke RefillFreeLists, so we need to make sure
523 // to only refill them for old data and pointer spaces.
527 intptr_t freed_bytes = space->free_list()->Concatenate(free_list);
528 space->AddToAccountingStats(freed_bytes);
529 space->DecrementUnsweptFreeBytes(freed_bytes);
533 void Marking::TransferMark(Address old_start, Address new_start) {
534 // This is only used when resizing an object.
535 DCHECK(MemoryChunk::FromAddress(old_start) ==
536 MemoryChunk::FromAddress(new_start));
538 if (!heap_->incremental_marking()->IsMarking()) return;
540 // If the mark doesn't move, we don't check the color of the object.
541 // It doesn't matter whether the object is black, since it hasn't changed
542 // size, so the adjustment to the live data count will be zero anyway.
543 if (old_start == new_start) return;
545 MarkBit new_mark_bit = MarkBitFrom(new_start);
546 MarkBit old_mark_bit = MarkBitFrom(old_start);
549 ObjectColor old_color = Color(old_mark_bit);
552 if (Marking::IsBlack(old_mark_bit)) {
553 old_mark_bit.Clear();
554 DCHECK(IsWhite(old_mark_bit));
555 Marking::MarkBlack(new_mark_bit);
557 } else if (Marking::IsGrey(old_mark_bit)) {
558 old_mark_bit.Clear();
559 old_mark_bit.Next().Clear();
560 DCHECK(IsWhite(old_mark_bit));
561 heap_->incremental_marking()->WhiteToGreyAndPush(
562 HeapObject::FromAddress(new_start), new_mark_bit);
563 heap_->incremental_marking()->RestartIfNotMarking();
567 ObjectColor new_color = Color(new_mark_bit);
568 DCHECK(new_color == old_color);
573 const char* AllocationSpaceName(AllocationSpace space) {
577 case OLD_POINTER_SPACE:
578 return "OLD_POINTER_SPACE";
580 return "OLD_DATA_SPACE";
587 case PROPERTY_CELL_SPACE:
588 return "PROPERTY_CELL_SPACE";
599 // Returns zero for pages that have so little fragmentation that it is not
600 // worth defragmenting them. Otherwise a positive integer that gives an
601 // estimate of fragmentation on an arbitrary scale.
602 static int FreeListFragmentation(PagedSpace* space, Page* p) {
603 // If page was not swept then there are no free list items on it.
604 if (!p->WasSwept()) {
605 if (FLAG_trace_fragmentation) {
606 PrintF("%p [%s]: %d bytes live (unswept)\n", reinterpret_cast<void*>(p),
607 AllocationSpaceName(space->identity()), p->LiveBytes());
612 PagedSpace::SizeStats sizes;
613 space->ObtainFreeListStatistics(p, &sizes);
616 intptr_t ratio_threshold;
617 intptr_t area_size = space->AreaSize();
618 if (space->identity() == CODE_SPACE) {
619 ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 / area_size;
620 ratio_threshold = 10;
622 ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 / area_size;
623 ratio_threshold = 15;
626 if (FLAG_trace_fragmentation) {
627 PrintF("%p [%s]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
628 reinterpret_cast<void*>(p), AllocationSpaceName(space->identity()),
629 static_cast<int>(sizes.small_size_),
630 static_cast<double>(sizes.small_size_ * 100) / area_size,
631 static_cast<int>(sizes.medium_size_),
632 static_cast<double>(sizes.medium_size_ * 100) / area_size,
633 static_cast<int>(sizes.large_size_),
634 static_cast<double>(sizes.large_size_ * 100) / area_size,
635 static_cast<int>(sizes.huge_size_),
636 static_cast<double>(sizes.huge_size_ * 100) / area_size,
637 (ratio > ratio_threshold) ? "[fragmented]" : "");
640 if (FLAG_always_compact && sizes.Total() != area_size) {
644 if (ratio <= ratio_threshold) return 0; // Not fragmented.
646 return static_cast<int>(ratio - ratio_threshold);
650 void MarkCompactCollector::CollectEvacuationCandidates(PagedSpace* space) {
651 DCHECK(space->identity() == OLD_POINTER_SPACE ||
652 space->identity() == OLD_DATA_SPACE ||
653 space->identity() == CODE_SPACE);
655 static const int kMaxMaxEvacuationCandidates = 1000;
656 int number_of_pages = space->CountTotalPages();
657 int max_evacuation_candidates =
658 static_cast<int>(std::sqrt(number_of_pages / 2.0) + 1);
660 if (FLAG_stress_compaction || FLAG_always_compact) {
661 max_evacuation_candidates = kMaxMaxEvacuationCandidates;
666 Candidate() : fragmentation_(0), page_(NULL) {}
667 Candidate(int f, Page* p) : fragmentation_(f), page_(p) {}
669 int fragmentation() { return fragmentation_; }
670 Page* page() { return page_; }
677 enum CompactionMode { COMPACT_FREE_LISTS, REDUCE_MEMORY_FOOTPRINT };
679 CompactionMode mode = COMPACT_FREE_LISTS;
681 intptr_t reserved = number_of_pages * space->AreaSize();
682 intptr_t over_reserved = reserved - space->SizeOfObjects();
683 static const intptr_t kFreenessThreshold = 50;
685 if (reduce_memory_footprint_ && over_reserved >= space->AreaSize()) {
686 // If reduction of memory footprint was requested, we are aggressive
687 // about choosing pages to free. We expect that half-empty pages
688 // are easier to compact so slightly bump the limit.
689 mode = REDUCE_MEMORY_FOOTPRINT;
690 max_evacuation_candidates += 2;
694 if (over_reserved > reserved / 3 && over_reserved >= 2 * space->AreaSize()) {
695 // If over-usage is very high (more than a third of the space), we
696 // try to free all mostly empty pages. We expect that almost empty
697 // pages are even easier to compact so bump the limit even more.
698 mode = REDUCE_MEMORY_FOOTPRINT;
699 max_evacuation_candidates *= 2;
702 if (FLAG_trace_fragmentation && mode == REDUCE_MEMORY_FOOTPRINT) {
704 "Estimated over reserved memory: %.1f / %.1f MB (threshold %d), "
705 "evacuation candidate limit: %d\n",
706 static_cast<double>(over_reserved) / MB,
707 static_cast<double>(reserved) / MB,
708 static_cast<int>(kFreenessThreshold), max_evacuation_candidates);
711 intptr_t estimated_release = 0;
713 Candidate candidates[kMaxMaxEvacuationCandidates];
715 max_evacuation_candidates =
716 Min(kMaxMaxEvacuationCandidates, max_evacuation_candidates);
719 int fragmentation = 0;
720 Candidate* least = NULL;
722 PageIterator it(space);
723 if (it.has_next()) it.next(); // Never compact the first page.
725 while (it.has_next()) {
727 p->ClearEvacuationCandidate();
729 if (FLAG_stress_compaction) {
730 unsigned int counter = space->heap()->ms_count();
731 uintptr_t page_number = reinterpret_cast<uintptr_t>(p) >> kPageSizeBits;
732 if ((counter & 1) == (page_number & 1)) fragmentation = 1;
733 } else if (mode == REDUCE_MEMORY_FOOTPRINT) {
734 // Don't try to release too many pages.
735 if (estimated_release >= over_reserved) {
739 intptr_t free_bytes = 0;
741 if (!p->WasSwept()) {
742 free_bytes = (p->area_size() - p->LiveBytes());
744 PagedSpace::SizeStats sizes;
745 space->ObtainFreeListStatistics(p, &sizes);
746 free_bytes = sizes.Total();
749 int free_pct = static_cast<int>(free_bytes * 100) / p->area_size();
751 if (free_pct >= kFreenessThreshold) {
752 estimated_release += free_bytes;
753 fragmentation = free_pct;
758 if (FLAG_trace_fragmentation) {
759 PrintF("%p [%s]: %d (%.2f%%) free %s\n", reinterpret_cast<void*>(p),
760 AllocationSpaceName(space->identity()),
761 static_cast<int>(free_bytes),
762 static_cast<double>(free_bytes * 100) / p->area_size(),
763 (fragmentation > 0) ? "[fragmented]" : "");
766 fragmentation = FreeListFragmentation(space, p);
769 if (fragmentation != 0) {
770 if (count < max_evacuation_candidates) {
771 candidates[count++] = Candidate(fragmentation, p);
774 for (int i = 0; i < max_evacuation_candidates; i++) {
776 candidates[i].fragmentation() < least->fragmentation()) {
777 least = candidates + i;
781 if (least->fragmentation() < fragmentation) {
782 *least = Candidate(fragmentation, p);
789 for (int i = 0; i < count; i++) {
790 AddEvacuationCandidate(candidates[i].page());
793 if (count > 0 && FLAG_trace_fragmentation) {
794 PrintF("Collected %d evacuation candidates for space %s\n", count,
795 AllocationSpaceName(space->identity()));
800 void MarkCompactCollector::AbortCompaction() {
802 int npages = evacuation_candidates_.length();
803 for (int i = 0; i < npages; i++) {
804 Page* p = evacuation_candidates_[i];
805 slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
806 p->ClearEvacuationCandidate();
807 p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
810 evacuation_candidates_.Rewind(0);
811 invalidated_code_.Rewind(0);
813 DCHECK_EQ(0, evacuation_candidates_.length());
817 void MarkCompactCollector::Prepare() {
818 was_marked_incrementally_ = heap()->incremental_marking()->IsMarking();
821 DCHECK(state_ == IDLE);
825 DCHECK(!FLAG_never_compact || !FLAG_always_compact);
827 if (sweeping_in_progress()) {
828 // Instead of waiting we could also abort the sweeper threads here.
829 EnsureSweepingCompleted();
832 // Clear marking bits if incremental marking is aborted.
833 if (was_marked_incrementally_ && abort_incremental_marking_) {
834 heap()->incremental_marking()->Abort();
836 AbortWeakCollections();
839 was_marked_incrementally_ = false;
842 // Don't start compaction if we are in the middle of incremental
843 // marking cycle. We did not collect any slots.
844 if (!FLAG_never_compact && !was_marked_incrementally_) {
845 StartCompaction(NON_INCREMENTAL_COMPACTION);
848 PagedSpaces spaces(heap());
849 for (PagedSpace* space = spaces.next(); space != NULL;
850 space = spaces.next()) {
851 space->PrepareForMarkCompact();
855 if (!was_marked_incrementally_ && FLAG_verify_heap) {
856 VerifyMarkbitsAreClean();
862 void MarkCompactCollector::Finish() {
864 DCHECK(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS);
867 // The stub cache is not traversed during GC; clear the cache to
868 // force lazy re-initialization of it. This must be done after the
869 // GC, because it relies on the new address of certain old space
870 // objects (empty string, illegal builtin).
871 isolate()->stub_cache()->Clear();
873 if (have_code_to_deoptimize_) {
874 // Some code objects were marked for deoptimization during the GC.
875 Deoptimizer::DeoptimizeMarkedCode(isolate());
876 have_code_to_deoptimize_ = false;
879 heap_->incremental_marking()->ClearIdleMarkingDelayCounter();
883 // -------------------------------------------------------------------------
884 // Phase 1: tracing and marking live objects.
885 // before: all objects are in normal state.
886 // after: a live object's map pointer is marked as '00'.
888 // Marking all live objects in the heap as part of mark-sweep or mark-compact
889 // collection. Before marking, all objects are in their normal state. After
890 // marking, live objects' map pointers are marked indicating that the object
891 // has been found reachable.
893 // The marking algorithm is a (mostly) depth-first (because of possible stack
894 // overflow) traversal of the graph of objects reachable from the roots. It
895 // uses an explicit stack of pointers rather than recursion. The young
896 // generation's inactive ('from') space is used as a marking stack. The
897 // objects in the marking stack are the ones that have been reached and marked
898 // but their children have not yet been visited.
900 // The marking stack can overflow during traversal. In that case, we set an
901 // overflow flag. When the overflow flag is set, we continue marking objects
902 // reachable from the objects on the marking stack, but no longer push them on
903 // the marking stack. Instead, we mark them as both marked and overflowed.
904 // When the stack is in the overflowed state, objects marked as overflowed
905 // have been reached and marked but their children have not been visited yet.
906 // After emptying the marking stack, we clear the overflow flag and traverse
907 // the heap looking for objects marked as overflowed, push them on the stack,
908 // and continue with marking. This process repeats until all reachable
909 // objects have been marked.
911 void CodeFlusher::ProcessJSFunctionCandidates() {
912 Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kCompileLazy);
913 Object* undefined = isolate_->heap()->undefined_value();
915 JSFunction* candidate = jsfunction_candidates_head_;
916 JSFunction* next_candidate;
917 while (candidate != NULL) {
918 next_candidate = GetNextCandidate(candidate);
919 ClearNextCandidate(candidate, undefined);
921 SharedFunctionInfo* shared = candidate->shared();
923 Code* code = shared->code();
924 MarkBit code_mark = Marking::MarkBitFrom(code);
925 if (!code_mark.Get()) {
926 if (FLAG_trace_code_flushing && shared->is_compiled()) {
927 PrintF("[code-flushing clears: ");
928 shared->ShortPrint();
929 PrintF(" - age: %d]\n", code->GetAge());
931 shared->set_code(lazy_compile);
932 candidate->set_code(lazy_compile);
934 candidate->set_code(code);
937 // We are in the middle of a GC cycle so the write barrier in the code
938 // setter did not record the slot update and we have to do that manually.
939 Address slot = candidate->address() + JSFunction::kCodeEntryOffset;
940 Code* target = Code::cast(Code::GetObjectFromEntryAddress(slot));
941 isolate_->heap()->mark_compact_collector()->RecordCodeEntrySlot(slot,
944 Object** shared_code_slot =
945 HeapObject::RawField(shared, SharedFunctionInfo::kCodeOffset);
946 isolate_->heap()->mark_compact_collector()->RecordSlot(
947 shared_code_slot, shared_code_slot, *shared_code_slot);
949 candidate = next_candidate;
952 jsfunction_candidates_head_ = NULL;
956 void CodeFlusher::ProcessSharedFunctionInfoCandidates() {
957 Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kCompileLazy);
959 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
960 SharedFunctionInfo* next_candidate;
961 while (candidate != NULL) {
962 next_candidate = GetNextCandidate(candidate);
963 ClearNextCandidate(candidate);
965 Code* code = candidate->code();
966 MarkBit code_mark = Marking::MarkBitFrom(code);
967 if (!code_mark.Get()) {
968 if (FLAG_trace_code_flushing && candidate->is_compiled()) {
969 PrintF("[code-flushing clears: ");
970 candidate->ShortPrint();
971 PrintF(" - age: %d]\n", code->GetAge());
973 candidate->set_code(lazy_compile);
977 HeapObject::RawField(candidate, SharedFunctionInfo::kCodeOffset);
978 isolate_->heap()->mark_compact_collector()->RecordSlot(code_slot, code_slot,
981 candidate = next_candidate;
984 shared_function_info_candidates_head_ = NULL;
988 void CodeFlusher::ProcessOptimizedCodeMaps() {
989 STATIC_ASSERT(SharedFunctionInfo::kEntryLength == 4);
991 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
992 SharedFunctionInfo* next_holder;
994 while (holder != NULL) {
995 next_holder = GetNextCodeMap(holder);
996 ClearNextCodeMap(holder);
998 FixedArray* code_map = FixedArray::cast(holder->optimized_code_map());
999 int new_length = SharedFunctionInfo::kEntriesStart;
1000 int old_length = code_map->length();
1001 for (int i = SharedFunctionInfo::kEntriesStart; i < old_length;
1002 i += SharedFunctionInfo::kEntryLength) {
1004 Code::cast(code_map->get(i + SharedFunctionInfo::kCachedCodeOffset));
1005 if (!Marking::MarkBitFrom(code).Get()) continue;
1007 // Move every slot in the entry.
1008 for (int j = 0; j < SharedFunctionInfo::kEntryLength; j++) {
1009 int dst_index = new_length++;
1010 Object** slot = code_map->RawFieldOfElementAt(dst_index);
1011 Object* object = code_map->get(i + j);
1012 code_map->set(dst_index, object);
1013 if (j == SharedFunctionInfo::kOsrAstIdOffset) {
1014 DCHECK(object->IsSmi());
1017 Marking::IsBlack(Marking::MarkBitFrom(HeapObject::cast(*slot))));
1018 isolate_->heap()->mark_compact_collector()->RecordSlot(slot, slot,
1024 // Trim the optimized code map if entries have been removed.
1025 if (new_length < old_length) {
1026 holder->TrimOptimizedCodeMap(old_length - new_length);
1029 holder = next_holder;
1032 optimized_code_map_holder_head_ = NULL;
1036 void CodeFlusher::EvictCandidate(SharedFunctionInfo* shared_info) {
1037 // Make sure previous flushing decisions are revisited.
1038 isolate_->heap()->incremental_marking()->RecordWrites(shared_info);
1040 if (FLAG_trace_code_flushing) {
1041 PrintF("[code-flushing abandons function-info: ");
1042 shared_info->ShortPrint();
1046 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1047 SharedFunctionInfo* next_candidate;
1048 if (candidate == shared_info) {
1049 next_candidate = GetNextCandidate(shared_info);
1050 shared_function_info_candidates_head_ = next_candidate;
1051 ClearNextCandidate(shared_info);
1053 while (candidate != NULL) {
1054 next_candidate = GetNextCandidate(candidate);
1056 if (next_candidate == shared_info) {
1057 next_candidate = GetNextCandidate(shared_info);
1058 SetNextCandidate(candidate, next_candidate);
1059 ClearNextCandidate(shared_info);
1063 candidate = next_candidate;
1069 void CodeFlusher::EvictCandidate(JSFunction* function) {
1070 DCHECK(!function->next_function_link()->IsUndefined());
1071 Object* undefined = isolate_->heap()->undefined_value();
1073 // Make sure previous flushing decisions are revisited.
1074 isolate_->heap()->incremental_marking()->RecordWrites(function);
1075 isolate_->heap()->incremental_marking()->RecordWrites(function->shared());
1077 if (FLAG_trace_code_flushing) {
1078 PrintF("[code-flushing abandons closure: ");
1079 function->shared()->ShortPrint();
1083 JSFunction* candidate = jsfunction_candidates_head_;
1084 JSFunction* next_candidate;
1085 if (candidate == function) {
1086 next_candidate = GetNextCandidate(function);
1087 jsfunction_candidates_head_ = next_candidate;
1088 ClearNextCandidate(function, undefined);
1090 while (candidate != NULL) {
1091 next_candidate = GetNextCandidate(candidate);
1093 if (next_candidate == function) {
1094 next_candidate = GetNextCandidate(function);
1095 SetNextCandidate(candidate, next_candidate);
1096 ClearNextCandidate(function, undefined);
1100 candidate = next_candidate;
1106 void CodeFlusher::EvictOptimizedCodeMap(SharedFunctionInfo* code_map_holder) {
1107 DCHECK(!FixedArray::cast(code_map_holder->optimized_code_map())
1108 ->get(SharedFunctionInfo::kNextMapIndex)
1111 // Make sure previous flushing decisions are revisited.
1112 isolate_->heap()->incremental_marking()->RecordWrites(code_map_holder);
1114 if (FLAG_trace_code_flushing) {
1115 PrintF("[code-flushing abandons code-map: ");
1116 code_map_holder->ShortPrint();
1120 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1121 SharedFunctionInfo* next_holder;
1122 if (holder == code_map_holder) {
1123 next_holder = GetNextCodeMap(code_map_holder);
1124 optimized_code_map_holder_head_ = next_holder;
1125 ClearNextCodeMap(code_map_holder);
1127 while (holder != NULL) {
1128 next_holder = GetNextCodeMap(holder);
1130 if (next_holder == code_map_holder) {
1131 next_holder = GetNextCodeMap(code_map_holder);
1132 SetNextCodeMap(holder, next_holder);
1133 ClearNextCodeMap(code_map_holder);
1137 holder = next_holder;
1143 void CodeFlusher::EvictJSFunctionCandidates() {
1144 JSFunction* candidate = jsfunction_candidates_head_;
1145 JSFunction* next_candidate;
1146 while (candidate != NULL) {
1147 next_candidate = GetNextCandidate(candidate);
1148 EvictCandidate(candidate);
1149 candidate = next_candidate;
1151 DCHECK(jsfunction_candidates_head_ == NULL);
1155 void CodeFlusher::EvictSharedFunctionInfoCandidates() {
1156 SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1157 SharedFunctionInfo* next_candidate;
1158 while (candidate != NULL) {
1159 next_candidate = GetNextCandidate(candidate);
1160 EvictCandidate(candidate);
1161 candidate = next_candidate;
1163 DCHECK(shared_function_info_candidates_head_ == NULL);
1167 void CodeFlusher::EvictOptimizedCodeMaps() {
1168 SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1169 SharedFunctionInfo* next_holder;
1170 while (holder != NULL) {
1171 next_holder = GetNextCodeMap(holder);
1172 EvictOptimizedCodeMap(holder);
1173 holder = next_holder;
1175 DCHECK(optimized_code_map_holder_head_ == NULL);
1179 void CodeFlusher::IteratePointersToFromSpace(ObjectVisitor* v) {
1180 Heap* heap = isolate_->heap();
1182 JSFunction** slot = &jsfunction_candidates_head_;
1183 JSFunction* candidate = jsfunction_candidates_head_;
1184 while (candidate != NULL) {
1185 if (heap->InFromSpace(candidate)) {
1186 v->VisitPointer(reinterpret_cast<Object**>(slot));
1188 candidate = GetNextCandidate(*slot);
1189 slot = GetNextCandidateSlot(*slot);
1194 MarkCompactCollector::~MarkCompactCollector() {
1195 if (code_flusher_ != NULL) {
1196 delete code_flusher_;
1197 code_flusher_ = NULL;
1202 static inline HeapObject* ShortCircuitConsString(Object** p) {
1203 // Optimization: If the heap object pointed to by p is a non-internalized
1204 // cons string whose right substring is HEAP->empty_string, update
1205 // it in place to its left substring. Return the updated value.
1207 // Here we assume that if we change *p, we replace it with a heap object
1208 // (i.e., the left substring of a cons string is always a heap object).
1210 // The check performed is:
1211 // object->IsConsString() && !object->IsInternalizedString() &&
1212 // (ConsString::cast(object)->second() == HEAP->empty_string())
1213 // except the maps for the object and its possible substrings might be
1215 HeapObject* object = HeapObject::cast(*p);
1216 Map* map = object->map();
1217 InstanceType type = map->instance_type();
1218 if (!IsShortcutCandidate(type)) return object;
1220 Object* second = reinterpret_cast<ConsString*>(object)->second();
1221 Heap* heap = map->GetHeap();
1222 if (second != heap->empty_string()) {
1226 // Since we don't have the object's start, it is impossible to update the
1227 // page dirty marks. Therefore, we only replace the string with its left
1228 // substring when page dirty marks do not change.
1229 Object* first = reinterpret_cast<ConsString*>(object)->first();
1230 if (!heap->InNewSpace(object) && heap->InNewSpace(first)) return object;
1233 return HeapObject::cast(first);
1237 class MarkCompactMarkingVisitor
1238 : public StaticMarkingVisitor<MarkCompactMarkingVisitor> {
1240 static void ObjectStatsVisitBase(StaticVisitorBase::VisitorId id, Map* map,
1243 static void ObjectStatsCountFixedArray(
1244 FixedArrayBase* fixed_array, FixedArraySubInstanceType fast_type,
1245 FixedArraySubInstanceType dictionary_type);
1247 template <MarkCompactMarkingVisitor::VisitorId id>
1248 class ObjectStatsTracker {
1250 static inline void Visit(Map* map, HeapObject* obj);
1253 static void Initialize();
1255 INLINE(static void VisitPointer(Heap* heap, Object** p)) {
1256 MarkObjectByPointer(heap->mark_compact_collector(), p, p);
1259 INLINE(static void VisitPointers(Heap* heap, Object** start, Object** end)) {
1260 // Mark all objects pointed to in [start, end).
1261 const int kMinRangeForMarkingRecursion = 64;
1262 if (end - start >= kMinRangeForMarkingRecursion) {
1263 if (VisitUnmarkedObjects(heap, start, end)) return;
1264 // We are close to a stack overflow, so just mark the objects.
1266 MarkCompactCollector* collector = heap->mark_compact_collector();
1267 for (Object** p = start; p < end; p++) {
1268 MarkObjectByPointer(collector, start, p);
1272 // Marks the object black and pushes it on the marking stack.
1273 INLINE(static void MarkObject(Heap* heap, HeapObject* object)) {
1274 MarkBit mark = Marking::MarkBitFrom(object);
1275 heap->mark_compact_collector()->MarkObject(object, mark);
1278 // Marks the object black without pushing it on the marking stack.
1279 // Returns true if object needed marking and false otherwise.
1280 INLINE(static bool MarkObjectWithoutPush(Heap* heap, HeapObject* object)) {
1281 MarkBit mark_bit = Marking::MarkBitFrom(object);
1282 if (!mark_bit.Get()) {
1283 heap->mark_compact_collector()->SetMark(object, mark_bit);
1289 // Mark object pointed to by p.
1290 INLINE(static void MarkObjectByPointer(MarkCompactCollector* collector,
1291 Object** anchor_slot, Object** p)) {
1292 if (!(*p)->IsHeapObject()) return;
1293 HeapObject* object = ShortCircuitConsString(p);
1294 collector->RecordSlot(anchor_slot, p, object);
1295 MarkBit mark = Marking::MarkBitFrom(object);
1296 collector->MarkObject(object, mark);
1300 // Visit an unmarked object.
1301 INLINE(static void VisitUnmarkedObject(MarkCompactCollector* collector,
1304 DCHECK(collector->heap()->Contains(obj));
1305 DCHECK(!collector->heap()->mark_compact_collector()->IsMarked(obj));
1307 Map* map = obj->map();
1308 Heap* heap = obj->GetHeap();
1309 MarkBit mark = Marking::MarkBitFrom(obj);
1310 heap->mark_compact_collector()->SetMark(obj, mark);
1311 // Mark the map pointer and the body.
1312 MarkBit map_mark = Marking::MarkBitFrom(map);
1313 heap->mark_compact_collector()->MarkObject(map, map_mark);
1314 IterateBody(map, obj);
1317 // Visit all unmarked objects pointed to by [start, end).
1318 // Returns false if the operation fails (lack of stack space).
1319 INLINE(static bool VisitUnmarkedObjects(Heap* heap, Object** start,
1321 // Return false is we are close to the stack limit.
1322 StackLimitCheck check(heap->isolate());
1323 if (check.HasOverflowed()) return false;
1325 MarkCompactCollector* collector = heap->mark_compact_collector();
1326 // Visit the unmarked objects.
1327 for (Object** p = start; p < end; p++) {
1329 if (!o->IsHeapObject()) continue;
1330 collector->RecordSlot(start, p, o);
1331 HeapObject* obj = HeapObject::cast(o);
1332 MarkBit mark = Marking::MarkBitFrom(obj);
1333 if (mark.Get()) continue;
1334 VisitUnmarkedObject(collector, obj);
1341 static inline void TrackObjectStatsAndVisit(Map* map, HeapObject* obj);
1343 // Code flushing support.
1345 static const int kRegExpCodeThreshold = 5;
1347 static void UpdateRegExpCodeAgeAndFlush(Heap* heap, JSRegExp* re,
1349 // Make sure that the fixed array is in fact initialized on the RegExp.
1350 // We could potentially trigger a GC when initializing the RegExp.
1351 if (HeapObject::cast(re->data())->map()->instance_type() !=
1355 // Make sure this is a RegExp that actually contains code.
1356 if (re->TypeTag() != JSRegExp::IRREGEXP) return;
1358 Object* code = re->DataAt(JSRegExp::code_index(is_one_byte));
1359 if (!code->IsSmi() &&
1360 HeapObject::cast(code)->map()->instance_type() == CODE_TYPE) {
1361 // Save a copy that can be reinstated if we need the code again.
1362 re->SetDataAt(JSRegExp::saved_code_index(is_one_byte), code);
1364 // Saving a copy might create a pointer into compaction candidate
1365 // that was not observed by marker. This might happen if JSRegExp data
1366 // was marked through the compilation cache before marker reached JSRegExp
1368 FixedArray* data = FixedArray::cast(re->data());
1370 data->data_start() + JSRegExp::saved_code_index(is_one_byte);
1371 heap->mark_compact_collector()->RecordSlot(slot, slot, code);
1373 // Set a number in the 0-255 range to guarantee no smi overflow.
1374 re->SetDataAt(JSRegExp::code_index(is_one_byte),
1375 Smi::FromInt(heap->sweep_generation() & 0xff));
1376 } else if (code->IsSmi()) {
1377 int value = Smi::cast(code)->value();
1378 // The regexp has not been compiled yet or there was a compilation error.
1379 if (value == JSRegExp::kUninitializedValue ||
1380 value == JSRegExp::kCompilationErrorValue) {
1384 // Check if we should flush now.
1385 if (value == ((heap->sweep_generation() - kRegExpCodeThreshold) & 0xff)) {
1386 re->SetDataAt(JSRegExp::code_index(is_one_byte),
1387 Smi::FromInt(JSRegExp::kUninitializedValue));
1388 re->SetDataAt(JSRegExp::saved_code_index(is_one_byte),
1389 Smi::FromInt(JSRegExp::kUninitializedValue));
1395 // Works by setting the current sweep_generation (as a smi) in the
1396 // code object place in the data array of the RegExp and keeps a copy
1397 // around that can be reinstated if we reuse the RegExp before flushing.
1398 // If we did not use the code for kRegExpCodeThreshold mark sweep GCs
1399 // we flush the code.
1400 static void VisitRegExpAndFlushCode(Map* map, HeapObject* object) {
1401 Heap* heap = map->GetHeap();
1402 MarkCompactCollector* collector = heap->mark_compact_collector();
1403 if (!collector->is_code_flushing_enabled()) {
1404 VisitJSRegExp(map, object);
1407 JSRegExp* re = reinterpret_cast<JSRegExp*>(object);
1408 // Flush code or set age on both one byte and two byte code.
1409 UpdateRegExpCodeAgeAndFlush(heap, re, true);
1410 UpdateRegExpCodeAgeAndFlush(heap, re, false);
1411 // Visit the fields of the RegExp, including the updated FixedArray.
1412 VisitJSRegExp(map, object);
1415 static VisitorDispatchTable<Callback> non_count_table_;
1419 void MarkCompactMarkingVisitor::ObjectStatsCountFixedArray(
1420 FixedArrayBase* fixed_array, FixedArraySubInstanceType fast_type,
1421 FixedArraySubInstanceType dictionary_type) {
1422 Heap* heap = fixed_array->map()->GetHeap();
1423 if (fixed_array->map() != heap->fixed_cow_array_map() &&
1424 fixed_array->map() != heap->fixed_double_array_map() &&
1425 fixed_array != heap->empty_fixed_array()) {
1426 if (fixed_array->IsDictionary()) {
1427 heap->RecordFixedArraySubTypeStats(dictionary_type, fixed_array->Size());
1429 heap->RecordFixedArraySubTypeStats(fast_type, fixed_array->Size());
1435 void MarkCompactMarkingVisitor::ObjectStatsVisitBase(
1436 MarkCompactMarkingVisitor::VisitorId id, Map* map, HeapObject* obj) {
1437 Heap* heap = map->GetHeap();
1438 int object_size = obj->Size();
1439 heap->RecordObjectStats(map->instance_type(), object_size);
1440 non_count_table_.GetVisitorById(id)(map, obj);
1441 if (obj->IsJSObject()) {
1442 JSObject* object = JSObject::cast(obj);
1443 ObjectStatsCountFixedArray(object->elements(), DICTIONARY_ELEMENTS_SUB_TYPE,
1444 FAST_ELEMENTS_SUB_TYPE);
1445 ObjectStatsCountFixedArray(object->properties(),
1446 DICTIONARY_PROPERTIES_SUB_TYPE,
1447 FAST_PROPERTIES_SUB_TYPE);
1452 template <MarkCompactMarkingVisitor::VisitorId id>
1453 void MarkCompactMarkingVisitor::ObjectStatsTracker<id>::Visit(Map* map,
1455 ObjectStatsVisitBase(id, map, obj);
1460 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1461 MarkCompactMarkingVisitor::kVisitMap> {
1463 static inline void Visit(Map* map, HeapObject* obj) {
1464 Heap* heap = map->GetHeap();
1465 Map* map_obj = Map::cast(obj);
1466 DCHECK(map->instance_type() == MAP_TYPE);
1467 DescriptorArray* array = map_obj->instance_descriptors();
1468 if (map_obj->owns_descriptors() &&
1469 array != heap->empty_descriptor_array()) {
1470 int fixed_array_size = array->Size();
1471 heap->RecordFixedArraySubTypeStats(DESCRIPTOR_ARRAY_SUB_TYPE,
1474 if (map_obj->HasTransitionArray()) {
1475 int fixed_array_size = map_obj->transitions()->Size();
1476 heap->RecordFixedArraySubTypeStats(TRANSITION_ARRAY_SUB_TYPE,
1479 if (map_obj->has_code_cache()) {
1480 CodeCache* cache = CodeCache::cast(map_obj->code_cache());
1481 heap->RecordFixedArraySubTypeStats(MAP_CODE_CACHE_SUB_TYPE,
1482 cache->default_cache()->Size());
1483 if (!cache->normal_type_cache()->IsUndefined()) {
1484 heap->RecordFixedArraySubTypeStats(
1485 MAP_CODE_CACHE_SUB_TYPE,
1486 FixedArray::cast(cache->normal_type_cache())->Size());
1489 ObjectStatsVisitBase(kVisitMap, map, obj);
1495 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1496 MarkCompactMarkingVisitor::kVisitCode> {
1498 static inline void Visit(Map* map, HeapObject* obj) {
1499 Heap* heap = map->GetHeap();
1500 int object_size = obj->Size();
1501 DCHECK(map->instance_type() == CODE_TYPE);
1502 Code* code_obj = Code::cast(obj);
1503 heap->RecordCodeSubTypeStats(code_obj->kind(), code_obj->GetRawAge(),
1505 ObjectStatsVisitBase(kVisitCode, map, obj);
1511 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1512 MarkCompactMarkingVisitor::kVisitSharedFunctionInfo> {
1514 static inline void Visit(Map* map, HeapObject* obj) {
1515 Heap* heap = map->GetHeap();
1516 SharedFunctionInfo* sfi = SharedFunctionInfo::cast(obj);
1517 if (sfi->scope_info() != heap->empty_fixed_array()) {
1518 heap->RecordFixedArraySubTypeStats(
1519 SCOPE_INFO_SUB_TYPE, FixedArray::cast(sfi->scope_info())->Size());
1521 ObjectStatsVisitBase(kVisitSharedFunctionInfo, map, obj);
1527 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1528 MarkCompactMarkingVisitor::kVisitFixedArray> {
1530 static inline void Visit(Map* map, HeapObject* obj) {
1531 Heap* heap = map->GetHeap();
1532 FixedArray* fixed_array = FixedArray::cast(obj);
1533 if (fixed_array == heap->string_table()) {
1534 heap->RecordFixedArraySubTypeStats(STRING_TABLE_SUB_TYPE,
1535 fixed_array->Size());
1537 ObjectStatsVisitBase(kVisitFixedArray, map, obj);
1542 void MarkCompactMarkingVisitor::Initialize() {
1543 StaticMarkingVisitor<MarkCompactMarkingVisitor>::Initialize();
1545 table_.Register(kVisitJSRegExp, &VisitRegExpAndFlushCode);
1547 if (FLAG_track_gc_object_stats) {
1548 // Copy the visitor table to make call-through possible.
1549 non_count_table_.CopyFrom(&table_);
1550 #define VISITOR_ID_COUNT_FUNCTION(id) \
1551 table_.Register(kVisit##id, ObjectStatsTracker<kVisit##id>::Visit);
1552 VISITOR_ID_LIST(VISITOR_ID_COUNT_FUNCTION)
1553 #undef VISITOR_ID_COUNT_FUNCTION
1558 VisitorDispatchTable<MarkCompactMarkingVisitor::Callback>
1559 MarkCompactMarkingVisitor::non_count_table_;
1562 class CodeMarkingVisitor : public ThreadVisitor {
1564 explicit CodeMarkingVisitor(MarkCompactCollector* collector)
1565 : collector_(collector) {}
1567 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1568 collector_->PrepareThreadForCodeFlushing(isolate, top);
1572 MarkCompactCollector* collector_;
1576 class SharedFunctionInfoMarkingVisitor : public ObjectVisitor {
1578 explicit SharedFunctionInfoMarkingVisitor(MarkCompactCollector* collector)
1579 : collector_(collector) {}
1581 void VisitPointers(Object** start, Object** end) {
1582 for (Object** p = start; p < end; p++) VisitPointer(p);
1585 void VisitPointer(Object** slot) {
1586 Object* obj = *slot;
1587 if (obj->IsSharedFunctionInfo()) {
1588 SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(obj);
1589 MarkBit shared_mark = Marking::MarkBitFrom(shared);
1590 MarkBit code_mark = Marking::MarkBitFrom(shared->code());
1591 collector_->MarkObject(shared->code(), code_mark);
1592 collector_->MarkObject(shared, shared_mark);
1597 MarkCompactCollector* collector_;
1601 void MarkCompactCollector::PrepareThreadForCodeFlushing(Isolate* isolate,
1602 ThreadLocalTop* top) {
1603 for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1604 // Note: for the frame that has a pending lazy deoptimization
1605 // StackFrame::unchecked_code will return a non-optimized code object for
1606 // the outermost function and StackFrame::LookupCode will return
1607 // actual optimized code object.
1608 StackFrame* frame = it.frame();
1609 Code* code = frame->unchecked_code();
1610 MarkBit code_mark = Marking::MarkBitFrom(code);
1611 MarkObject(code, code_mark);
1612 if (frame->is_optimized()) {
1613 MarkCompactMarkingVisitor::MarkInlinedFunctionsCode(heap(),
1614 frame->LookupCode());
1620 void MarkCompactCollector::PrepareForCodeFlushing() {
1621 // Enable code flushing for non-incremental cycles.
1622 if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
1623 EnableCodeFlushing(!was_marked_incrementally_);
1626 // If code flushing is disabled, there is no need to prepare for it.
1627 if (!is_code_flushing_enabled()) return;
1629 // Ensure that empty descriptor array is marked. Method MarkDescriptorArray
1630 // relies on it being marked before any other descriptor array.
1631 HeapObject* descriptor_array = heap()->empty_descriptor_array();
1632 MarkBit descriptor_array_mark = Marking::MarkBitFrom(descriptor_array);
1633 MarkObject(descriptor_array, descriptor_array_mark);
1635 // Make sure we are not referencing the code from the stack.
1636 DCHECK(this == heap()->mark_compact_collector());
1637 PrepareThreadForCodeFlushing(heap()->isolate(),
1638 heap()->isolate()->thread_local_top());
1640 // Iterate the archived stacks in all threads to check if
1641 // the code is referenced.
1642 CodeMarkingVisitor code_marking_visitor(this);
1643 heap()->isolate()->thread_manager()->IterateArchivedThreads(
1644 &code_marking_visitor);
1646 SharedFunctionInfoMarkingVisitor visitor(this);
1647 heap()->isolate()->compilation_cache()->IterateFunctions(&visitor);
1648 heap()->isolate()->handle_scope_implementer()->Iterate(&visitor);
1650 ProcessMarkingDeque();
1654 // Visitor class for marking heap roots.
1655 class RootMarkingVisitor : public ObjectVisitor {
1657 explicit RootMarkingVisitor(Heap* heap)
1658 : collector_(heap->mark_compact_collector()) {}
1660 void VisitPointer(Object** p) { MarkObjectByPointer(p); }
1662 void VisitPointers(Object** start, Object** end) {
1663 for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
1666 // Skip the weak next code link in a code object, which is visited in
1667 // ProcessTopOptimizedFrame.
1668 void VisitNextCodeLink(Object** p) {}
1671 void MarkObjectByPointer(Object** p) {
1672 if (!(*p)->IsHeapObject()) return;
1674 // Replace flat cons strings in place.
1675 HeapObject* object = ShortCircuitConsString(p);
1676 MarkBit mark_bit = Marking::MarkBitFrom(object);
1677 if (mark_bit.Get()) return;
1679 Map* map = object->map();
1681 collector_->SetMark(object, mark_bit);
1683 // Mark the map pointer and body, and push them on the marking stack.
1684 MarkBit map_mark = Marking::MarkBitFrom(map);
1685 collector_->MarkObject(map, map_mark);
1686 MarkCompactMarkingVisitor::IterateBody(map, object);
1688 // Mark all the objects reachable from the map and body. May leave
1689 // overflowed objects in the heap.
1690 collector_->EmptyMarkingDeque();
1693 MarkCompactCollector* collector_;
1697 // Helper class for pruning the string table.
1698 template <bool finalize_external_strings>
1699 class StringTableCleaner : public ObjectVisitor {
1701 explicit StringTableCleaner(Heap* heap) : heap_(heap), pointers_removed_(0) {}
1703 virtual void VisitPointers(Object** start, Object** end) {
1704 // Visit all HeapObject pointers in [start, end).
1705 for (Object** p = start; p < end; p++) {
1707 if (o->IsHeapObject() &&
1708 !Marking::MarkBitFrom(HeapObject::cast(o)).Get()) {
1709 if (finalize_external_strings) {
1710 DCHECK(o->IsExternalString());
1711 heap_->FinalizeExternalString(String::cast(*p));
1713 pointers_removed_++;
1715 // Set the entry to the_hole_value (as deleted).
1716 *p = heap_->the_hole_value();
1721 int PointersRemoved() {
1722 DCHECK(!finalize_external_strings);
1723 return pointers_removed_;
1728 int pointers_removed_;
1732 typedef StringTableCleaner<false> InternalizedStringTableCleaner;
1733 typedef StringTableCleaner<true> ExternalStringTableCleaner;
1736 // Implementation of WeakObjectRetainer for mark compact GCs. All marked objects
1738 class MarkCompactWeakObjectRetainer : public WeakObjectRetainer {
1740 virtual Object* RetainAs(Object* object) {
1741 if (Marking::MarkBitFrom(HeapObject::cast(object)).Get()) {
1743 } else if (object->IsAllocationSite() &&
1744 !(AllocationSite::cast(object)->IsZombie())) {
1745 // "dead" AllocationSites need to live long enough for a traversal of new
1746 // space. These sites get a one-time reprieve.
1747 AllocationSite* site = AllocationSite::cast(object);
1749 site->GetHeap()->mark_compact_collector()->MarkAllocationSite(site);
1758 // Fill the marking stack with overflowed objects returned by the given
1759 // iterator. Stop when the marking stack is filled or the end of the space
1760 // is reached, whichever comes first.
1762 static void DiscoverGreyObjectsWithIterator(Heap* heap,
1763 MarkingDeque* marking_deque,
1765 // The caller should ensure that the marking stack is initially not full,
1766 // so that we don't waste effort pointlessly scanning for objects.
1767 DCHECK(!marking_deque->IsFull());
1769 Map* filler_map = heap->one_pointer_filler_map();
1770 for (HeapObject* object = it->Next(); object != NULL; object = it->Next()) {
1771 MarkBit markbit = Marking::MarkBitFrom(object);
1772 if ((object->map() != filler_map) && Marking::IsGrey(markbit)) {
1773 Marking::GreyToBlack(markbit);
1774 MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1775 marking_deque->PushBlack(object);
1776 if (marking_deque->IsFull()) return;
1782 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts);
1785 static void DiscoverGreyObjectsOnPage(MarkingDeque* marking_deque,
1787 DCHECK(!marking_deque->IsFull());
1788 DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1789 DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
1790 DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
1791 DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1793 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1794 Address cell_base = it.CurrentCellBase();
1795 MarkBit::CellType* cell = it.CurrentCell();
1797 const MarkBit::CellType current_cell = *cell;
1798 if (current_cell == 0) continue;
1800 MarkBit::CellType grey_objects;
1802 const MarkBit::CellType next_cell = *(cell + 1);
1803 grey_objects = current_cell & ((current_cell >> 1) |
1804 (next_cell << (Bitmap::kBitsPerCell - 1)));
1806 grey_objects = current_cell & (current_cell >> 1);
1810 while (grey_objects != 0) {
1811 int trailing_zeros = base::bits::CountTrailingZeros32(grey_objects);
1812 grey_objects >>= trailing_zeros;
1813 offset += trailing_zeros;
1814 MarkBit markbit(cell, 1 << offset, false);
1815 DCHECK(Marking::IsGrey(markbit));
1816 Marking::GreyToBlack(markbit);
1817 Address addr = cell_base + offset * kPointerSize;
1818 HeapObject* object = HeapObject::FromAddress(addr);
1819 MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1820 marking_deque->PushBlack(object);
1821 if (marking_deque->IsFull()) return;
1826 grey_objects >>= (Bitmap::kBitsPerCell - 1);
1831 int MarkCompactCollector::DiscoverAndEvacuateBlackObjectsOnPage(
1832 NewSpace* new_space, NewSpacePage* p) {
1833 DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1834 DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
1835 DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
1836 DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1838 MarkBit::CellType* cells = p->markbits()->cells();
1839 int survivors_size = 0;
1841 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1842 Address cell_base = it.CurrentCellBase();
1843 MarkBit::CellType* cell = it.CurrentCell();
1845 MarkBit::CellType current_cell = *cell;
1846 if (current_cell == 0) continue;
1849 while (current_cell != 0) {
1850 int trailing_zeros = base::bits::CountTrailingZeros32(current_cell);
1851 current_cell >>= trailing_zeros;
1852 offset += trailing_zeros;
1853 Address address = cell_base + offset * kPointerSize;
1854 HeapObject* object = HeapObject::FromAddress(address);
1856 int size = object->Size();
1857 survivors_size += size;
1859 Heap::UpdateAllocationSiteFeedback(object, Heap::RECORD_SCRATCHPAD_SLOT);
1864 // TODO(hpayer): Refactor EvacuateObject and call this function instead.
1865 if (heap()->ShouldBePromoted(object->address(), size) &&
1866 TryPromoteObject(object, size)) {
1870 AllocationResult allocation = new_space->AllocateRaw(size);
1871 if (allocation.IsRetry()) {
1872 if (!new_space->AddFreshPage()) {
1873 // Shouldn't happen. We are sweeping linearly, and to-space
1874 // has the same number of pages as from-space, so there is
1878 allocation = new_space->AllocateRaw(size);
1879 DCHECK(!allocation.IsRetry());
1881 Object* target = allocation.ToObjectChecked();
1883 MigrateObject(HeapObject::cast(target), object, size, NEW_SPACE);
1884 heap()->IncrementSemiSpaceCopiedObjectSize(size);
1888 return survivors_size;
1892 static void DiscoverGreyObjectsInSpace(Heap* heap, MarkingDeque* marking_deque,
1893 PagedSpace* space) {
1894 PageIterator it(space);
1895 while (it.has_next()) {
1896 Page* p = it.next();
1897 DiscoverGreyObjectsOnPage(marking_deque, p);
1898 if (marking_deque->IsFull()) return;
1903 static void DiscoverGreyObjectsInNewSpace(Heap* heap,
1904 MarkingDeque* marking_deque) {
1905 NewSpace* space = heap->new_space();
1906 NewSpacePageIterator it(space->bottom(), space->top());
1907 while (it.has_next()) {
1908 NewSpacePage* page = it.next();
1909 DiscoverGreyObjectsOnPage(marking_deque, page);
1910 if (marking_deque->IsFull()) return;
1915 bool MarkCompactCollector::IsUnmarkedHeapObject(Object** p) {
1917 if (!o->IsHeapObject()) return false;
1918 HeapObject* heap_object = HeapObject::cast(o);
1919 MarkBit mark = Marking::MarkBitFrom(heap_object);
1924 bool MarkCompactCollector::IsUnmarkedHeapObjectWithHeap(Heap* heap,
1927 DCHECK(o->IsHeapObject());
1928 HeapObject* heap_object = HeapObject::cast(o);
1929 MarkBit mark = Marking::MarkBitFrom(heap_object);
1934 void MarkCompactCollector::MarkStringTable(RootMarkingVisitor* visitor) {
1935 StringTable* string_table = heap()->string_table();
1936 // Mark the string table itself.
1937 MarkBit string_table_mark = Marking::MarkBitFrom(string_table);
1938 if (!string_table_mark.Get()) {
1939 // String table could have already been marked by visiting the handles list.
1940 SetMark(string_table, string_table_mark);
1942 // Explicitly mark the prefix.
1943 string_table->IteratePrefix(visitor);
1944 ProcessMarkingDeque();
1948 void MarkCompactCollector::MarkAllocationSite(AllocationSite* site) {
1949 MarkBit mark_bit = Marking::MarkBitFrom(site);
1950 SetMark(site, mark_bit);
1954 void MarkCompactCollector::MarkRoots(RootMarkingVisitor* visitor) {
1955 // Mark the heap roots including global variables, stack variables,
1956 // etc., and all objects reachable from them.
1957 heap()->IterateStrongRoots(visitor, VISIT_ONLY_STRONG);
1959 // Handle the string table specially.
1960 MarkStringTable(visitor);
1962 MarkWeakObjectToCodeTable();
1964 // There may be overflowed objects in the heap. Visit them now.
1965 while (marking_deque_.overflowed()) {
1966 RefillMarkingDeque();
1967 EmptyMarkingDeque();
1972 void MarkCompactCollector::MarkImplicitRefGroups() {
1973 List<ImplicitRefGroup*>* ref_groups =
1974 isolate()->global_handles()->implicit_ref_groups();
1977 for (int i = 0; i < ref_groups->length(); i++) {
1978 ImplicitRefGroup* entry = ref_groups->at(i);
1979 DCHECK(entry != NULL);
1981 if (!IsMarked(*entry->parent)) {
1982 (*ref_groups)[last++] = entry;
1986 Object*** children = entry->children;
1987 // A parent object is marked, so mark all child heap objects.
1988 for (size_t j = 0; j < entry->length; ++j) {
1989 if ((*children[j])->IsHeapObject()) {
1990 HeapObject* child = HeapObject::cast(*children[j]);
1991 MarkBit mark = Marking::MarkBitFrom(child);
1992 MarkObject(child, mark);
1996 // Once the entire group has been marked, dispose it because it's
1997 // not needed anymore.
2000 ref_groups->Rewind(last);
2004 void MarkCompactCollector::MarkWeakObjectToCodeTable() {
2005 HeapObject* weak_object_to_code_table =
2006 HeapObject::cast(heap()->weak_object_to_code_table());
2007 if (!IsMarked(weak_object_to_code_table)) {
2008 MarkBit mark = Marking::MarkBitFrom(weak_object_to_code_table);
2009 SetMark(weak_object_to_code_table, mark);
2014 // Mark all objects reachable from the objects on the marking stack.
2015 // Before: the marking stack contains zero or more heap object pointers.
2016 // After: the marking stack is empty, and all objects reachable from the
2017 // marking stack have been marked, or are overflowed in the heap.
2018 void MarkCompactCollector::EmptyMarkingDeque() {
2019 Map* filler_map = heap_->one_pointer_filler_map();
2020 while (!marking_deque_.IsEmpty()) {
2021 HeapObject* object = marking_deque_.Pop();
2022 // Explicitly skip one word fillers. Incremental markbit patterns are
2023 // correct only for objects that occupy at least two words.
2024 Map* map = object->map();
2025 if (map == filler_map) continue;
2027 DCHECK(object->IsHeapObject());
2028 DCHECK(heap()->Contains(object));
2029 DCHECK(!Marking::IsWhite(Marking::MarkBitFrom(object)));
2031 MarkBit map_mark = Marking::MarkBitFrom(map);
2032 MarkObject(map, map_mark);
2034 MarkCompactMarkingVisitor::IterateBody(map, object);
2039 // Sweep the heap for overflowed objects, clear their overflow bits, and
2040 // push them on the marking stack. Stop early if the marking stack fills
2041 // before sweeping completes. If sweeping completes, there are no remaining
2042 // overflowed objects in the heap so the overflow flag on the markings stack
2044 void MarkCompactCollector::RefillMarkingDeque() {
2045 DCHECK(marking_deque_.overflowed());
2047 DiscoverGreyObjectsInNewSpace(heap(), &marking_deque_);
2048 if (marking_deque_.IsFull()) return;
2050 DiscoverGreyObjectsInSpace(heap(), &marking_deque_,
2051 heap()->old_pointer_space());
2052 if (marking_deque_.IsFull()) return;
2054 DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->old_data_space());
2055 if (marking_deque_.IsFull()) return;
2057 DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->code_space());
2058 if (marking_deque_.IsFull()) return;
2060 DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->map_space());
2061 if (marking_deque_.IsFull()) return;
2063 DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->cell_space());
2064 if (marking_deque_.IsFull()) return;
2066 DiscoverGreyObjectsInSpace(heap(), &marking_deque_,
2067 heap()->property_cell_space());
2068 if (marking_deque_.IsFull()) return;
2070 LargeObjectIterator lo_it(heap()->lo_space());
2071 DiscoverGreyObjectsWithIterator(heap(), &marking_deque_, &lo_it);
2072 if (marking_deque_.IsFull()) return;
2074 marking_deque_.ClearOverflowed();
2078 // Mark all objects reachable (transitively) from objects on the marking
2079 // stack. Before: the marking stack contains zero or more heap object
2080 // pointers. After: the marking stack is empty and there are no overflowed
2081 // objects in the heap.
2082 void MarkCompactCollector::ProcessMarkingDeque() {
2083 EmptyMarkingDeque();
2084 while (marking_deque_.overflowed()) {
2085 RefillMarkingDeque();
2086 EmptyMarkingDeque();
2091 // Mark all objects reachable (transitively) from objects on the marking
2092 // stack including references only considered in the atomic marking pause.
2093 void MarkCompactCollector::ProcessEphemeralMarking(
2094 ObjectVisitor* visitor, bool only_process_harmony_weak_collections) {
2095 bool work_to_do = true;
2096 DCHECK(marking_deque_.IsEmpty() && !marking_deque_.overflowed());
2097 while (work_to_do) {
2098 if (!only_process_harmony_weak_collections) {
2099 isolate()->global_handles()->IterateObjectGroups(
2100 visitor, &IsUnmarkedHeapObjectWithHeap);
2101 MarkImplicitRefGroups();
2103 ProcessWeakCollections();
2104 work_to_do = !marking_deque_.IsEmpty();
2105 ProcessMarkingDeque();
2110 void MarkCompactCollector::ProcessTopOptimizedFrame(ObjectVisitor* visitor) {
2111 for (StackFrameIterator it(isolate(), isolate()->thread_local_top());
2112 !it.done(); it.Advance()) {
2113 if (it.frame()->type() == StackFrame::JAVA_SCRIPT) {
2116 if (it.frame()->type() == StackFrame::OPTIMIZED) {
2117 Code* code = it.frame()->LookupCode();
2118 if (!code->CanDeoptAt(it.frame()->pc())) {
2119 code->CodeIterateBody(visitor);
2121 ProcessMarkingDeque();
2128 void MarkCompactCollector::EnsureMarkingDequeIsCommittedAndInitialize() {
2129 if (marking_deque_memory_ == NULL) {
2130 marking_deque_memory_ = new base::VirtualMemory(4 * MB);
2132 if (!marking_deque_memory_committed_) {
2133 bool success = marking_deque_memory_->Commit(
2134 reinterpret_cast<Address>(marking_deque_memory_->address()),
2135 marking_deque_memory_->size(),
2136 false); // Not executable.
2138 marking_deque_memory_committed_ = true;
2139 InitializeMarkingDeque();
2144 void MarkCompactCollector::InitializeMarkingDeque() {
2145 if (marking_deque_memory_committed_) {
2146 Address addr = static_cast<Address>(marking_deque_memory_->address());
2147 size_t size = marking_deque_memory_->size();
2148 if (FLAG_force_marking_deque_overflows) size = 64 * kPointerSize;
2149 marking_deque_.Initialize(addr, addr + size);
2154 void MarkCompactCollector::UncommitMarkingDeque() {
2155 if (marking_deque_memory_committed_) {
2156 bool success = marking_deque_memory_->Uncommit(
2157 reinterpret_cast<Address>(marking_deque_memory_->address()),
2158 marking_deque_memory_->size());
2160 marking_deque_memory_committed_ = false;
2165 void MarkCompactCollector::MarkLiveObjects() {
2166 GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_MARK);
2167 double start_time = 0.0;
2168 if (FLAG_print_cumulative_gc_stat) {
2169 start_time = base::OS::TimeCurrentMillis();
2171 // The recursive GC marker detects when it is nearing stack overflow,
2172 // and switches to a different marking system. JS interrupts interfere
2173 // with the C stack limit check.
2174 PostponeInterruptsScope postpone(isolate());
2176 IncrementalMarking* incremental_marking = heap_->incremental_marking();
2177 if (was_marked_incrementally_) {
2178 incremental_marking->Finalize();
2180 // Abort any pending incremental activities e.g. incremental sweeping.
2181 incremental_marking->Abort();
2182 InitializeMarkingDeque();
2186 DCHECK(state_ == PREPARE_GC);
2187 state_ = MARK_LIVE_OBJECTS;
2190 EnsureMarkingDequeIsCommittedAndInitialize();
2192 PrepareForCodeFlushing();
2194 if (was_marked_incrementally_) {
2195 // There is no write barrier on cells so we have to scan them now at the end
2196 // of the incremental marking.
2198 HeapObjectIterator cell_iterator(heap()->cell_space());
2200 while ((cell = cell_iterator.Next()) != NULL) {
2201 DCHECK(cell->IsCell());
2202 if (IsMarked(cell)) {
2203 int offset = Cell::kValueOffset;
2204 MarkCompactMarkingVisitor::VisitPointer(
2205 heap(), reinterpret_cast<Object**>(cell->address() + offset));
2210 HeapObjectIterator js_global_property_cell_iterator(
2211 heap()->property_cell_space());
2213 while ((cell = js_global_property_cell_iterator.Next()) != NULL) {
2214 DCHECK(cell->IsPropertyCell());
2215 if (IsMarked(cell)) {
2216 MarkCompactMarkingVisitor::VisitPropertyCell(cell->map(), cell);
2222 RootMarkingVisitor root_visitor(heap());
2223 MarkRoots(&root_visitor);
2225 ProcessTopOptimizedFrame(&root_visitor);
2228 GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_WEAKCLOSURE);
2230 // The objects reachable from the roots are marked, yet unreachable
2231 // objects are unmarked. Mark objects reachable due to host
2232 // application specific logic or through Harmony weak maps.
2233 ProcessEphemeralMarking(&root_visitor, false);
2235 // The objects reachable from the roots, weak maps or object groups
2236 // are marked. Objects pointed to only by weak global handles cannot be
2237 // immediately reclaimed. Instead, we have to mark them as pending and mark
2238 // objects reachable from them.
2240 // First we identify nonlive weak handles and mark them as pending
2242 heap()->isolate()->global_handles()->IdentifyWeakHandles(
2243 &IsUnmarkedHeapObject);
2244 // Then we mark the objects.
2245 heap()->isolate()->global_handles()->IterateWeakRoots(&root_visitor);
2246 ProcessMarkingDeque();
2248 // Repeat Harmony weak maps marking to mark unmarked objects reachable from
2249 // the weak roots we just marked as pending destruction.
2251 // We only process harmony collections, as all object groups have been fully
2252 // processed and no weakly reachable node can discover new objects groups.
2253 ProcessEphemeralMarking(&root_visitor, true);
2258 if (FLAG_print_cumulative_gc_stat) {
2259 heap_->tracer()->AddMarkingTime(base::OS::TimeCurrentMillis() - start_time);
2264 void MarkCompactCollector::AfterMarking() {
2265 // Prune the string table removing all strings only pointed to by the
2266 // string table. Cannot use string_table() here because the string
2268 StringTable* string_table = heap()->string_table();
2269 InternalizedStringTableCleaner internalized_visitor(heap());
2270 string_table->IterateElements(&internalized_visitor);
2271 string_table->ElementsRemoved(internalized_visitor.PointersRemoved());
2273 ExternalStringTableCleaner external_visitor(heap());
2274 heap()->external_string_table_.Iterate(&external_visitor);
2275 heap()->external_string_table_.CleanUp();
2277 // Process the weak references.
2278 MarkCompactWeakObjectRetainer mark_compact_object_retainer;
2279 heap()->ProcessWeakReferences(&mark_compact_object_retainer);
2281 // Remove object groups after marking phase.
2282 heap()->isolate()->global_handles()->RemoveObjectGroups();
2283 heap()->isolate()->global_handles()->RemoveImplicitRefGroups();
2285 // Flush code from collected candidates.
2286 if (is_code_flushing_enabled()) {
2287 code_flusher_->ProcessCandidates();
2288 // If incremental marker does not support code flushing, we need to
2289 // disable it before incremental marking steps for next cycle.
2290 if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
2291 EnableCodeFlushing(false);
2295 if (FLAG_track_gc_object_stats) {
2296 heap()->CheckpointObjectStats();
2301 void MarkCompactCollector::ClearNonLiveReferences() {
2302 // Iterate over the map space, setting map transitions that go from
2303 // a marked map to an unmarked map to null transitions. This action
2304 // is carried out only on maps of JSObjects and related subtypes.
2305 HeapObjectIterator map_iterator(heap()->map_space());
2306 for (HeapObject* obj = map_iterator.Next(); obj != NULL;
2307 obj = map_iterator.Next()) {
2308 Map* map = Map::cast(obj);
2310 if (!map->CanTransition()) continue;
2312 MarkBit map_mark = Marking::MarkBitFrom(map);
2313 ClearNonLivePrototypeTransitions(map);
2314 ClearNonLiveMapTransitions(map, map_mark);
2316 if (map_mark.Get()) {
2317 ClearNonLiveDependentCode(map->dependent_code());
2319 ClearDependentCode(map->dependent_code());
2320 map->set_dependent_code(DependentCode::cast(heap()->empty_fixed_array()));
2324 // Iterate over property cell space, removing dependent code that is not
2325 // otherwise kept alive by strong references.
2326 HeapObjectIterator cell_iterator(heap_->property_cell_space());
2327 for (HeapObject* cell = cell_iterator.Next(); cell != NULL;
2328 cell = cell_iterator.Next()) {
2329 if (IsMarked(cell)) {
2330 ClearNonLiveDependentCode(PropertyCell::cast(cell)->dependent_code());
2334 // Iterate over allocation sites, removing dependent code that is not
2335 // otherwise kept alive by strong references.
2336 Object* undefined = heap()->undefined_value();
2337 for (Object* site = heap()->allocation_sites_list(); site != undefined;
2338 site = AllocationSite::cast(site)->weak_next()) {
2339 if (IsMarked(site)) {
2340 ClearNonLiveDependentCode(AllocationSite::cast(site)->dependent_code());
2344 if (heap_->weak_object_to_code_table()->IsHashTable()) {
2345 WeakHashTable* table =
2346 WeakHashTable::cast(heap_->weak_object_to_code_table());
2347 uint32_t capacity = table->Capacity();
2348 for (uint32_t i = 0; i < capacity; i++) {
2349 uint32_t key_index = table->EntryToIndex(i);
2350 Object* key = table->get(key_index);
2351 if (!table->IsKey(key)) continue;
2352 uint32_t value_index = table->EntryToValueIndex(i);
2353 Object* value = table->get(value_index);
2354 if (key->IsCell() && !IsMarked(key)) {
2355 Cell* cell = Cell::cast(key);
2356 Object* object = cell->value();
2357 if (IsMarked(object)) {
2358 MarkBit mark = Marking::MarkBitFrom(cell);
2359 SetMark(cell, mark);
2360 Object** value_slot = HeapObject::RawField(cell, Cell::kValueOffset);
2361 RecordSlot(value_slot, value_slot, *value_slot);
2364 if (IsMarked(key)) {
2365 if (!IsMarked(value)) {
2366 HeapObject* obj = HeapObject::cast(value);
2367 MarkBit mark = Marking::MarkBitFrom(obj);
2370 ClearNonLiveDependentCode(DependentCode::cast(value));
2372 ClearDependentCode(DependentCode::cast(value));
2373 table->set(key_index, heap_->the_hole_value());
2374 table->set(value_index, heap_->the_hole_value());
2375 table->ElementRemoved();
2382 void MarkCompactCollector::ClearNonLivePrototypeTransitions(Map* map) {
2383 int number_of_transitions = map->NumberOfProtoTransitions();
2384 FixedArray* prototype_transitions = map->GetPrototypeTransitions();
2386 int new_number_of_transitions = 0;
2387 const int header = Map::kProtoTransitionHeaderSize;
2388 const int proto_offset = header + Map::kProtoTransitionPrototypeOffset;
2389 const int map_offset = header + Map::kProtoTransitionMapOffset;
2390 const int step = Map::kProtoTransitionElementsPerEntry;
2391 for (int i = 0; i < number_of_transitions; i++) {
2392 Object* prototype = prototype_transitions->get(proto_offset + i * step);
2393 Object* cached_map = prototype_transitions->get(map_offset + i * step);
2394 if (IsMarked(prototype) && IsMarked(cached_map)) {
2395 DCHECK(!prototype->IsUndefined());
2396 int proto_index = proto_offset + new_number_of_transitions * step;
2397 int map_index = map_offset + new_number_of_transitions * step;
2398 if (new_number_of_transitions != i) {
2399 prototype_transitions->set(proto_index, prototype,
2400 UPDATE_WRITE_BARRIER);
2401 prototype_transitions->set(map_index, cached_map, SKIP_WRITE_BARRIER);
2403 Object** slot = prototype_transitions->RawFieldOfElementAt(proto_index);
2404 RecordSlot(slot, slot, prototype);
2405 new_number_of_transitions++;
2409 if (new_number_of_transitions != number_of_transitions) {
2410 map->SetNumberOfProtoTransitions(new_number_of_transitions);
2413 // Fill slots that became free with undefined value.
2414 for (int i = new_number_of_transitions * step;
2415 i < number_of_transitions * step; i++) {
2416 prototype_transitions->set_undefined(header + i);
2421 void MarkCompactCollector::ClearNonLiveMapTransitions(Map* map,
2423 Object* potential_parent = map->GetBackPointer();
2424 if (!potential_parent->IsMap()) return;
2425 Map* parent = Map::cast(potential_parent);
2427 // Follow back pointer, check whether we are dealing with a map transition
2428 // from a live map to a dead path and in case clear transitions of parent.
2429 bool current_is_alive = map_mark.Get();
2430 bool parent_is_alive = Marking::MarkBitFrom(parent).Get();
2431 if (!current_is_alive && parent_is_alive) {
2432 ClearMapTransitions(parent);
2437 // Clear a possible back pointer in case the transition leads to a dead map.
2438 // Return true in case a back pointer has been cleared and false otherwise.
2439 bool MarkCompactCollector::ClearMapBackPointer(Map* target) {
2440 if (Marking::MarkBitFrom(target).Get()) return false;
2441 target->SetBackPointer(heap_->undefined_value(), SKIP_WRITE_BARRIER);
2446 void MarkCompactCollector::ClearMapTransitions(Map* map) {
2447 // If there are no transitions to be cleared, return.
2448 // TODO(verwaest) Should be an assert, otherwise back pointers are not
2449 // properly cleared.
2450 if (!map->HasTransitionArray()) return;
2452 TransitionArray* t = map->transitions();
2454 int transition_index = 0;
2456 DescriptorArray* descriptors = map->instance_descriptors();
2457 bool descriptors_owner_died = false;
2459 // Compact all live descriptors to the left.
2460 for (int i = 0; i < t->number_of_transitions(); ++i) {
2461 Map* target = t->GetTarget(i);
2462 if (ClearMapBackPointer(target)) {
2463 if (target->instance_descriptors() == descriptors) {
2464 descriptors_owner_died = true;
2467 if (i != transition_index) {
2468 Name* key = t->GetKey(i);
2469 t->SetKey(transition_index, key);
2470 Object** key_slot = t->GetKeySlot(transition_index);
2471 RecordSlot(key_slot, key_slot, key);
2472 // Target slots do not need to be recorded since maps are not compacted.
2473 t->SetTarget(transition_index, t->GetTarget(i));
2479 // If there are no transitions to be cleared, return.
2480 // TODO(verwaest) Should be an assert, otherwise back pointers are not
2481 // properly cleared.
2482 if (transition_index == t->number_of_transitions()) return;
2484 int number_of_own_descriptors = map->NumberOfOwnDescriptors();
2486 if (descriptors_owner_died) {
2487 if (number_of_own_descriptors > 0) {
2488 TrimDescriptorArray(map, descriptors, number_of_own_descriptors);
2489 DCHECK(descriptors->number_of_descriptors() == number_of_own_descriptors);
2490 map->set_owns_descriptors(true);
2492 DCHECK(descriptors == heap_->empty_descriptor_array());
2496 // Note that we never eliminate a transition array, though we might right-trim
2497 // such that number_of_transitions() == 0. If this assumption changes,
2498 // TransitionArray::Insert() will need to deal with the case that a transition
2499 // array disappeared during GC.
2500 int trim = t->number_of_transitions_storage() - transition_index;
2502 heap_->RightTrimFixedArray<Heap::FROM_GC>(
2503 t, t->IsSimpleTransition() ? trim
2504 : trim * TransitionArray::kTransitionSize);
2505 t->SetNumberOfTransitions(transition_index);
2507 DCHECK(map->HasTransitionArray());
2511 void MarkCompactCollector::TrimDescriptorArray(Map* map,
2512 DescriptorArray* descriptors,
2513 int number_of_own_descriptors) {
2514 int number_of_descriptors = descriptors->number_of_descriptors_storage();
2515 int to_trim = number_of_descriptors - number_of_own_descriptors;
2516 if (to_trim == 0) return;
2518 heap_->RightTrimFixedArray<Heap::FROM_GC>(
2519 descriptors, to_trim * DescriptorArray::kDescriptorSize);
2520 descriptors->SetNumberOfDescriptors(number_of_own_descriptors);
2522 if (descriptors->HasEnumCache()) TrimEnumCache(map, descriptors);
2523 descriptors->Sort();
2527 void MarkCompactCollector::TrimEnumCache(Map* map,
2528 DescriptorArray* descriptors) {
2529 int live_enum = map->EnumLength();
2530 if (live_enum == kInvalidEnumCacheSentinel) {
2531 live_enum = map->NumberOfDescribedProperties(OWN_DESCRIPTORS, DONT_ENUM);
2533 if (live_enum == 0) return descriptors->ClearEnumCache();
2535 FixedArray* enum_cache = descriptors->GetEnumCache();
2537 int to_trim = enum_cache->length() - live_enum;
2538 if (to_trim <= 0) return;
2539 heap_->RightTrimFixedArray<Heap::FROM_GC>(descriptors->GetEnumCache(),
2542 if (!descriptors->HasEnumIndicesCache()) return;
2543 FixedArray* enum_indices_cache = descriptors->GetEnumIndicesCache();
2544 heap_->RightTrimFixedArray<Heap::FROM_GC>(enum_indices_cache, to_trim);
2548 void MarkCompactCollector::ClearDependentCode(DependentCode* entries) {
2549 DisallowHeapAllocation no_allocation;
2550 DependentCode::GroupStartIndexes starts(entries);
2551 int number_of_entries = starts.number_of_entries();
2552 if (number_of_entries == 0) return;
2553 int g = DependentCode::kWeakCodeGroup;
2554 for (int i = starts.at(g); i < starts.at(g + 1); i++) {
2555 // If the entry is compilation info then the map must be alive,
2556 // and ClearDependentCode shouldn't be called.
2557 DCHECK(entries->is_code_at(i));
2558 Code* code = entries->code_at(i);
2559 if (IsMarked(code) && !code->marked_for_deoptimization()) {
2560 DependentCode::SetMarkedForDeoptimization(
2561 code, static_cast<DependentCode::DependencyGroup>(g));
2562 code->InvalidateEmbeddedObjects();
2563 have_code_to_deoptimize_ = true;
2566 for (int i = 0; i < number_of_entries; i++) {
2567 entries->clear_at(i);
2572 int MarkCompactCollector::ClearNonLiveDependentCodeInGroup(
2573 DependentCode* entries, int group, int start, int end, int new_start) {
2575 for (int i = start; i < end; i++) {
2576 Object* obj = entries->object_at(i);
2577 DCHECK(obj->IsCode() || IsMarked(obj));
2578 if (IsMarked(obj) &&
2579 (!obj->IsCode() || !WillBeDeoptimized(Code::cast(obj)))) {
2580 if (new_start + survived != i) {
2581 entries->set_object_at(new_start + survived, obj);
2583 Object** slot = entries->slot_at(new_start + survived);
2584 RecordSlot(slot, slot, obj);
2588 entries->set_number_of_entries(
2589 static_cast<DependentCode::DependencyGroup>(group), survived);
2594 void MarkCompactCollector::ClearNonLiveDependentCode(DependentCode* entries) {
2595 DisallowHeapAllocation no_allocation;
2596 DependentCode::GroupStartIndexes starts(entries);
2597 int number_of_entries = starts.number_of_entries();
2598 if (number_of_entries == 0) return;
2599 int new_number_of_entries = 0;
2600 // Go through all groups, remove dead codes and compact.
2601 for (int g = 0; g < DependentCode::kGroupCount; g++) {
2602 int survived = ClearNonLiveDependentCodeInGroup(
2603 entries, g, starts.at(g), starts.at(g + 1), new_number_of_entries);
2604 new_number_of_entries += survived;
2606 for (int i = new_number_of_entries; i < number_of_entries; i++) {
2607 entries->clear_at(i);
2612 void MarkCompactCollector::ProcessWeakCollections() {
2613 GCTracer::Scope gc_scope(heap()->tracer(),
2614 GCTracer::Scope::MC_WEAKCOLLECTION_PROCESS);
2615 Object* weak_collection_obj = heap()->encountered_weak_collections();
2616 while (weak_collection_obj != Smi::FromInt(0)) {
2617 JSWeakCollection* weak_collection =
2618 reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2619 DCHECK(MarkCompactCollector::IsMarked(weak_collection));
2620 if (weak_collection->table()->IsHashTable()) {
2621 ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2622 Object** anchor = reinterpret_cast<Object**>(table->address());
2623 for (int i = 0; i < table->Capacity(); i++) {
2624 if (MarkCompactCollector::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
2626 table->RawFieldOfElementAt(ObjectHashTable::EntryToIndex(i));
2627 RecordSlot(anchor, key_slot, *key_slot);
2628 Object** value_slot =
2629 table->RawFieldOfElementAt(ObjectHashTable::EntryToValueIndex(i));
2630 MarkCompactMarkingVisitor::MarkObjectByPointer(this, anchor,
2635 weak_collection_obj = weak_collection->next();
2640 void MarkCompactCollector::ClearWeakCollections() {
2641 GCTracer::Scope gc_scope(heap()->tracer(),
2642 GCTracer::Scope::MC_WEAKCOLLECTION_CLEAR);
2643 Object* weak_collection_obj = heap()->encountered_weak_collections();
2644 while (weak_collection_obj != Smi::FromInt(0)) {
2645 JSWeakCollection* weak_collection =
2646 reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2647 DCHECK(MarkCompactCollector::IsMarked(weak_collection));
2648 if (weak_collection->table()->IsHashTable()) {
2649 ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2650 for (int i = 0; i < table->Capacity(); i++) {
2651 HeapObject* key = HeapObject::cast(table->KeyAt(i));
2652 if (!MarkCompactCollector::IsMarked(key)) {
2653 table->RemoveEntry(i);
2657 weak_collection_obj = weak_collection->next();
2658 weak_collection->set_next(heap()->undefined_value());
2660 heap()->set_encountered_weak_collections(Smi::FromInt(0));
2664 void MarkCompactCollector::AbortWeakCollections() {
2665 GCTracer::Scope gc_scope(heap()->tracer(),
2666 GCTracer::Scope::MC_WEAKCOLLECTION_ABORT);
2667 Object* weak_collection_obj = heap()->encountered_weak_collections();
2668 while (weak_collection_obj != Smi::FromInt(0)) {
2669 JSWeakCollection* weak_collection =
2670 reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2671 weak_collection_obj = weak_collection->next();
2672 weak_collection->set_next(heap()->undefined_value());
2674 heap()->set_encountered_weak_collections(Smi::FromInt(0));
2678 void MarkCompactCollector::ProcessAndClearWeakCells() {
2679 HeapObject* undefined = heap()->undefined_value();
2680 Object* weak_cell_obj = heap()->encountered_weak_cells();
2681 while (weak_cell_obj != Smi::FromInt(0)) {
2682 WeakCell* weak_cell = reinterpret_cast<WeakCell*>(weak_cell_obj);
2683 // We do not insert cleared weak cells into the list, so the value
2684 // cannot be a Smi here.
2685 HeapObject* value = HeapObject::cast(weak_cell->value());
2686 if (!MarkCompactCollector::IsMarked(value)) {
2689 Object** slot = HeapObject::RawField(weak_cell, WeakCell::kValueOffset);
2690 heap()->mark_compact_collector()->RecordSlot(slot, slot, value);
2692 weak_cell_obj = weak_cell->next();
2693 weak_cell->set_next(undefined, SKIP_WRITE_BARRIER);
2695 heap()->set_encountered_weak_cells(Smi::FromInt(0));
2699 void MarkCompactCollector::AbortWeakCells() {
2700 Object* undefined = heap()->undefined_value();
2701 Object* weak_cell_obj = heap()->encountered_weak_cells();
2702 while (weak_cell_obj != Smi::FromInt(0)) {
2703 WeakCell* weak_cell = reinterpret_cast<WeakCell*>(weak_cell_obj);
2704 weak_cell_obj = weak_cell->next();
2705 weak_cell->set_next(undefined, SKIP_WRITE_BARRIER);
2707 heap()->set_encountered_weak_cells(Smi::FromInt(0));
2711 void MarkCompactCollector::RecordMigratedSlot(Object* value, Address slot) {
2712 if (heap_->InNewSpace(value)) {
2713 heap_->store_buffer()->Mark(slot);
2714 } else if (value->IsHeapObject() && IsOnEvacuationCandidate(value)) {
2715 SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2716 reinterpret_cast<Object**>(slot),
2717 SlotsBuffer::IGNORE_OVERFLOW);
2722 // We scavenge new space simultaneously with sweeping. This is done in two
2725 // The first pass migrates all alive objects from one semispace to another or
2726 // promotes them to old space. Forwarding address is written directly into
2727 // first word of object without any encoding. If object is dead we write
2728 // NULL as a forwarding address.
2730 // The second pass updates pointers to new space in all spaces. It is possible
2731 // to encounter pointers to dead new space objects during traversal of pointers
2732 // to new space. We should clear them to avoid encountering them during next
2733 // pointer iteration. This is an issue if the store buffer overflows and we
2734 // have to scan the entire old space, including dead objects, looking for
2735 // pointers to new space.
2736 void MarkCompactCollector::MigrateObject(HeapObject* dst, HeapObject* src,
2737 int size, AllocationSpace dest) {
2738 Address dst_addr = dst->address();
2739 Address src_addr = src->address();
2740 DCHECK(heap()->AllowedToBeMigrated(src, dest));
2741 DCHECK(dest != LO_SPACE && size <= Page::kMaxRegularHeapObjectSize);
2742 if (dest == OLD_POINTER_SPACE) {
2743 Address src_slot = src_addr;
2744 Address dst_slot = dst_addr;
2745 DCHECK(IsAligned(size, kPointerSize));
2747 bool may_contain_raw_values = src->MayContainRawValues();
2748 #if V8_DOUBLE_FIELDS_UNBOXING
2749 LayoutDescriptorHelper helper(src->map());
2750 bool has_only_tagged_fields = helper.all_fields_tagged();
2752 for (int remaining = size / kPointerSize; remaining > 0; remaining--) {
2753 Object* value = Memory::Object_at(src_slot);
2755 Memory::Object_at(dst_slot) = value;
2757 #if V8_DOUBLE_FIELDS_UNBOXING
2758 if (!may_contain_raw_values &&
2759 (has_only_tagged_fields ||
2760 helper.IsTagged(static_cast<int>(src_slot - src_addr))))
2762 if (!may_contain_raw_values)
2765 RecordMigratedSlot(value, dst_slot);
2768 src_slot += kPointerSize;
2769 dst_slot += kPointerSize;
2772 if (compacting_ && dst->IsJSFunction()) {
2773 Address code_entry_slot = dst_addr + JSFunction::kCodeEntryOffset;
2774 Address code_entry = Memory::Address_at(code_entry_slot);
2776 if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2777 SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2778 SlotsBuffer::CODE_ENTRY_SLOT, code_entry_slot,
2779 SlotsBuffer::IGNORE_OVERFLOW);
2781 } else if (dst->IsConstantPoolArray()) {
2782 // We special case ConstantPoolArrays since they could contain integers
2783 // value entries which look like tagged pointers.
2784 // TODO(mstarzinger): restructure this code to avoid this special-casing.
2785 ConstantPoolArray* array = ConstantPoolArray::cast(dst);
2786 ConstantPoolArray::Iterator code_iter(array, ConstantPoolArray::CODE_PTR);
2787 while (!code_iter.is_finished()) {
2788 Address code_entry_slot =
2789 dst_addr + array->OffsetOfElementAt(code_iter.next_index());
2790 Address code_entry = Memory::Address_at(code_entry_slot);
2792 if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2793 SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2794 SlotsBuffer::CODE_ENTRY_SLOT, code_entry_slot,
2795 SlotsBuffer::IGNORE_OVERFLOW);
2798 ConstantPoolArray::Iterator heap_iter(array, ConstantPoolArray::HEAP_PTR);
2799 while (!heap_iter.is_finished()) {
2801 dst_addr + array->OffsetOfElementAt(heap_iter.next_index());
2802 Object* value = Memory::Object_at(heap_slot);
2803 RecordMigratedSlot(value, heap_slot);
2806 } else if (dest == CODE_SPACE) {
2807 PROFILE(isolate(), CodeMoveEvent(src_addr, dst_addr));
2808 heap()->MoveBlock(dst_addr, src_addr, size);
2809 SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2810 SlotsBuffer::RELOCATED_CODE_OBJECT, dst_addr,
2811 SlotsBuffer::IGNORE_OVERFLOW);
2812 Code::cast(dst)->Relocate(dst_addr - src_addr);
2814 DCHECK(dest == OLD_DATA_SPACE || dest == NEW_SPACE);
2815 heap()->MoveBlock(dst_addr, src_addr, size);
2817 heap()->OnMoveEvent(dst, src, size);
2818 Memory::Address_at(src_addr) = dst_addr;
2822 // Visitor for updating pointers from live objects in old spaces to new space.
2823 // It does not expect to encounter pointers to dead objects.
2824 class PointersUpdatingVisitor : public ObjectVisitor {
2826 explicit PointersUpdatingVisitor(Heap* heap) : heap_(heap) {}
2828 void VisitPointer(Object** p) { UpdatePointer(p); }
2830 void VisitPointers(Object** start, Object** end) {
2831 for (Object** p = start; p < end; p++) UpdatePointer(p);
2834 void VisitEmbeddedPointer(RelocInfo* rinfo) {
2835 DCHECK(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
2836 Object* target = rinfo->target_object();
2837 Object* old_target = target;
2838 VisitPointer(&target);
2839 // Avoid unnecessary changes that might unnecessary flush the instruction
2841 if (target != old_target) {
2842 rinfo->set_target_object(target);
2846 void VisitCodeTarget(RelocInfo* rinfo) {
2847 DCHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
2848 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
2849 Object* old_target = target;
2850 VisitPointer(&target);
2851 if (target != old_target) {
2852 rinfo->set_target_address(Code::cast(target)->instruction_start());
2856 void VisitCodeAgeSequence(RelocInfo* rinfo) {
2857 DCHECK(RelocInfo::IsCodeAgeSequence(rinfo->rmode()));
2858 Object* stub = rinfo->code_age_stub();
2859 DCHECK(stub != NULL);
2860 VisitPointer(&stub);
2861 if (stub != rinfo->code_age_stub()) {
2862 rinfo->set_code_age_stub(Code::cast(stub));
2866 void VisitDebugTarget(RelocInfo* rinfo) {
2867 DCHECK((RelocInfo::IsJSReturn(rinfo->rmode()) &&
2868 rinfo->IsPatchedReturnSequence()) ||
2869 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
2870 rinfo->IsPatchedDebugBreakSlotSequence()));
2871 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
2872 VisitPointer(&target);
2873 rinfo->set_call_address(Code::cast(target)->instruction_start());
2876 static inline void UpdateSlot(Heap* heap, Object** slot) {
2877 Object* obj = reinterpret_cast<Object*>(
2878 base::NoBarrier_Load(reinterpret_cast<base::AtomicWord*>(slot)));
2880 if (!obj->IsHeapObject()) return;
2882 HeapObject* heap_obj = HeapObject::cast(obj);
2884 MapWord map_word = heap_obj->map_word();
2885 if (map_word.IsForwardingAddress()) {
2886 DCHECK(heap->InFromSpace(heap_obj) ||
2887 MarkCompactCollector::IsOnEvacuationCandidate(heap_obj));
2888 HeapObject* target = map_word.ToForwardingAddress();
2889 base::NoBarrier_CompareAndSwap(
2890 reinterpret_cast<base::AtomicWord*>(slot),
2891 reinterpret_cast<base::AtomicWord>(obj),
2892 reinterpret_cast<base::AtomicWord>(target));
2893 DCHECK(!heap->InFromSpace(target) &&
2894 !MarkCompactCollector::IsOnEvacuationCandidate(target));
2899 inline void UpdatePointer(Object** p) { UpdateSlot(heap_, p); }
2905 static void UpdatePointer(HeapObject** address, HeapObject* object) {
2906 Address new_addr = Memory::Address_at(object->address());
2908 // The new space sweep will overwrite the map word of dead objects
2909 // with NULL. In this case we do not need to transfer this entry to
2910 // the store buffer which we are rebuilding.
2911 // We perform the pointer update with a no barrier compare-and-swap. The
2912 // compare and swap may fail in the case where the pointer update tries to
2913 // update garbage memory which was concurrently accessed by the sweeper.
2914 if (new_addr != NULL) {
2915 base::NoBarrier_CompareAndSwap(
2916 reinterpret_cast<base::AtomicWord*>(address),
2917 reinterpret_cast<base::AtomicWord>(object),
2918 reinterpret_cast<base::AtomicWord>(HeapObject::FromAddress(new_addr)));
2923 static String* UpdateReferenceInExternalStringTableEntry(Heap* heap,
2925 MapWord map_word = HeapObject::cast(*p)->map_word();
2927 if (map_word.IsForwardingAddress()) {
2928 return String::cast(map_word.ToForwardingAddress());
2931 return String::cast(*p);
2935 bool MarkCompactCollector::TryPromoteObject(HeapObject* object,
2937 DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
2939 OldSpace* target_space = heap()->TargetSpace(object);
2941 DCHECK(target_space == heap()->old_pointer_space() ||
2942 target_space == heap()->old_data_space());
2944 AllocationResult allocation = target_space->AllocateRaw(object_size);
2945 if (allocation.To(&target)) {
2946 MigrateObject(target, object, object_size, target_space->identity());
2947 heap()->IncrementPromotedObjectsSize(object_size);
2955 void MarkCompactCollector::EvacuateNewSpace() {
2956 // There are soft limits in the allocation code, designed trigger a mark
2957 // sweep collection by failing allocations. But since we are already in
2958 // a mark-sweep allocation, there is no sense in trying to trigger one.
2959 AlwaysAllocateScope scope(isolate());
2961 NewSpace* new_space = heap()->new_space();
2963 // Store allocation range before flipping semispaces.
2964 Address from_bottom = new_space->bottom();
2965 Address from_top = new_space->top();
2967 // Flip the semispaces. After flipping, to space is empty, from space has
2970 new_space->ResetAllocationInfo();
2972 int survivors_size = 0;
2974 // First pass: traverse all objects in inactive semispace, remove marks,
2975 // migrate live objects and write forwarding addresses. This stage puts
2976 // new entries in the store buffer and may cause some pages to be marked
2977 // scan-on-scavenge.
2978 NewSpacePageIterator it(from_bottom, from_top);
2979 while (it.has_next()) {
2980 NewSpacePage* p = it.next();
2981 survivors_size += DiscoverAndEvacuateBlackObjectsOnPage(new_space, p);
2984 heap_->IncrementYoungSurvivorsCounter(survivors_size);
2985 new_space->set_age_mark(new_space->top());
2989 void MarkCompactCollector::EvacuateLiveObjectsFromPage(Page* p) {
2990 AlwaysAllocateScope always_allocate(isolate());
2991 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
2992 DCHECK(p->IsEvacuationCandidate() && !p->WasSwept());
2997 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
2998 Address cell_base = it.CurrentCellBase();
2999 MarkBit::CellType* cell = it.CurrentCell();
3001 if (*cell == 0) continue;
3003 int live_objects = MarkWordToObjectStarts(*cell, offsets);
3004 for (int i = 0; i < live_objects; i++) {
3005 Address object_addr = cell_base + offsets[i] * kPointerSize;
3006 HeapObject* object = HeapObject::FromAddress(object_addr);
3007 DCHECK(Marking::IsBlack(Marking::MarkBitFrom(object)));
3009 int size = object->Size();
3011 HeapObject* target_object;
3012 AllocationResult allocation = space->AllocateRaw(size);
3013 if (!allocation.To(&target_object)) {
3014 // If allocation failed, use emergency memory and re-try allocation.
3015 CHECK(space->HasEmergencyMemory());
3016 space->UseEmergencyMemory();
3017 allocation = space->AllocateRaw(size);
3019 if (!allocation.To(&target_object)) {
3020 // OS refused to give us memory.
3021 V8::FatalProcessOutOfMemory("Evacuation");
3025 MigrateObject(target_object, object, size, space->identity());
3026 DCHECK(object->map_word().IsForwardingAddress());
3029 // Clear marking bits for current cell.
3032 p->ResetLiveBytes();
3036 void MarkCompactCollector::EvacuatePages() {
3037 int npages = evacuation_candidates_.length();
3038 for (int i = 0; i < npages; i++) {
3039 Page* p = evacuation_candidates_[i];
3040 DCHECK(p->IsEvacuationCandidate() ||
3041 p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3042 DCHECK(static_cast<int>(p->parallel_sweeping()) ==
3043 MemoryChunk::SWEEPING_DONE);
3044 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3045 // Allocate emergency memory for the case when compaction fails due to out
3047 if (!space->HasEmergencyMemory()) {
3048 space->CreateEmergencyMemory();
3050 if (p->IsEvacuationCandidate()) {
3051 // During compaction we might have to request a new page. Check that we
3052 // have an emergency page and the space still has room for that.
3053 if (space->HasEmergencyMemory() && space->CanExpand()) {
3054 EvacuateLiveObjectsFromPage(p);
3056 // Without room for expansion evacuation is not guaranteed to succeed.
3057 // Pessimistically abandon unevacuated pages.
3058 for (int j = i; j < npages; j++) {
3059 Page* page = evacuation_candidates_[j];
3060 slots_buffer_allocator_.DeallocateChain(page->slots_buffer_address());
3061 page->ClearEvacuationCandidate();
3062 page->SetFlag(Page::RESCAN_ON_EVACUATION);
3069 // Release emergency memory.
3070 PagedSpaces spaces(heap());
3071 for (PagedSpace* space = spaces.next(); space != NULL;
3072 space = spaces.next()) {
3073 if (space->HasEmergencyMemory()) {
3074 space->FreeEmergencyMemory();
3081 class EvacuationWeakObjectRetainer : public WeakObjectRetainer {
3083 virtual Object* RetainAs(Object* object) {
3084 if (object->IsHeapObject()) {
3085 HeapObject* heap_object = HeapObject::cast(object);
3086 MapWord map_word = heap_object->map_word();
3087 if (map_word.IsForwardingAddress()) {
3088 return map_word.ToForwardingAddress();
3096 static inline void UpdateSlot(Isolate* isolate, ObjectVisitor* v,
3097 SlotsBuffer::SlotType slot_type, Address addr) {
3098 switch (slot_type) {
3099 case SlotsBuffer::CODE_TARGET_SLOT: {
3100 RelocInfo rinfo(addr, RelocInfo::CODE_TARGET, 0, NULL);
3101 rinfo.Visit(isolate, v);
3104 case SlotsBuffer::CODE_ENTRY_SLOT: {
3105 v->VisitCodeEntry(addr);
3108 case SlotsBuffer::RELOCATED_CODE_OBJECT: {
3109 HeapObject* obj = HeapObject::FromAddress(addr);
3110 Code::cast(obj)->CodeIterateBody(v);
3113 case SlotsBuffer::DEBUG_TARGET_SLOT: {
3114 RelocInfo rinfo(addr, RelocInfo::DEBUG_BREAK_SLOT, 0, NULL);
3115 if (rinfo.IsPatchedDebugBreakSlotSequence()) rinfo.Visit(isolate, v);
3118 case SlotsBuffer::JS_RETURN_SLOT: {
3119 RelocInfo rinfo(addr, RelocInfo::JS_RETURN, 0, NULL);
3120 if (rinfo.IsPatchedReturnSequence()) rinfo.Visit(isolate, v);
3123 case SlotsBuffer::EMBEDDED_OBJECT_SLOT: {
3124 RelocInfo rinfo(addr, RelocInfo::EMBEDDED_OBJECT, 0, NULL);
3125 rinfo.Visit(isolate, v);
3135 enum SweepingMode { SWEEP_ONLY, SWEEP_AND_VISIT_LIVE_OBJECTS };
3138 enum SkipListRebuildingMode { REBUILD_SKIP_LIST, IGNORE_SKIP_LIST };
3141 enum FreeSpaceTreatmentMode { IGNORE_FREE_SPACE, ZAP_FREE_SPACE };
3144 template <MarkCompactCollector::SweepingParallelism mode>
3145 static intptr_t Free(PagedSpace* space, FreeList* free_list, Address start,
3147 if (mode == MarkCompactCollector::SWEEP_ON_MAIN_THREAD) {
3148 DCHECK(free_list == NULL);
3149 return space->Free(start, size);
3151 // TODO(hpayer): account for wasted bytes in concurrent sweeping too.
3152 return size - free_list->Free(start, size);
3157 // Sweeps a page. After sweeping the page can be iterated.
3158 // Slots in live objects pointing into evacuation candidates are updated
3160 // Returns the size of the biggest continuous freed memory chunk in bytes.
3161 template <SweepingMode sweeping_mode,
3162 MarkCompactCollector::SweepingParallelism parallelism,
3163 SkipListRebuildingMode skip_list_mode,
3164 FreeSpaceTreatmentMode free_space_mode>
3165 static int Sweep(PagedSpace* space, FreeList* free_list, Page* p,
3167 DCHECK(!p->IsEvacuationCandidate() && !p->WasSwept());
3168 DCHECK_EQ(skip_list_mode == REBUILD_SKIP_LIST,
3169 space->identity() == CODE_SPACE);
3170 DCHECK((p->skip_list() == NULL) || (skip_list_mode == REBUILD_SKIP_LIST));
3171 DCHECK(parallelism == MarkCompactCollector::SWEEP_ON_MAIN_THREAD ||
3172 sweeping_mode == SWEEP_ONLY);
3174 Address free_start = p->area_start();
3175 DCHECK(reinterpret_cast<intptr_t>(free_start) % (32 * kPointerSize) == 0);
3178 SkipList* skip_list = p->skip_list();
3179 int curr_region = -1;
3180 if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list) {
3184 intptr_t freed_bytes = 0;
3185 intptr_t max_freed_bytes = 0;
3187 for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
3188 Address cell_base = it.CurrentCellBase();
3189 MarkBit::CellType* cell = it.CurrentCell();
3190 int live_objects = MarkWordToObjectStarts(*cell, offsets);
3192 for (; live_objects != 0; live_objects--) {
3193 Address free_end = cell_base + offsets[live_index++] * kPointerSize;
3194 if (free_end != free_start) {
3195 int size = static_cast<int>(free_end - free_start);
3196 if (free_space_mode == ZAP_FREE_SPACE) {
3197 memset(free_start, 0xcc, size);
3199 freed_bytes = Free<parallelism>(space, free_list, free_start, size);
3200 max_freed_bytes = Max(freed_bytes, max_freed_bytes);
3201 #ifdef ENABLE_GDB_JIT_INTERFACE
3202 if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3203 GDBJITInterface::RemoveCodeRange(free_start, free_end);
3207 HeapObject* live_object = HeapObject::FromAddress(free_end);
3208 DCHECK(Marking::IsBlack(Marking::MarkBitFrom(live_object)));
3209 Map* map = live_object->synchronized_map();
3210 int size = live_object->SizeFromMap(map);
3211 if (sweeping_mode == SWEEP_AND_VISIT_LIVE_OBJECTS) {
3212 live_object->IterateBody(map->instance_type(), size, v);
3214 if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list != NULL) {
3215 int new_region_start = SkipList::RegionNumber(free_end);
3216 int new_region_end =
3217 SkipList::RegionNumber(free_end + size - kPointerSize);
3218 if (new_region_start != curr_region || new_region_end != curr_region) {
3219 skip_list->AddObject(free_end, size);
3220 curr_region = new_region_end;
3223 free_start = free_end + size;
3225 // Clear marking bits for current cell.
3228 if (free_start != p->area_end()) {
3229 int size = static_cast<int>(p->area_end() - free_start);
3230 if (free_space_mode == ZAP_FREE_SPACE) {
3231 memset(free_start, 0xcc, size);
3233 freed_bytes = Free<parallelism>(space, free_list, free_start, size);
3234 max_freed_bytes = Max(freed_bytes, max_freed_bytes);
3235 #ifdef ENABLE_GDB_JIT_INTERFACE
3236 if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3237 GDBJITInterface::RemoveCodeRange(free_start, p->area_end());
3241 p->ResetLiveBytes();
3243 if (parallelism == MarkCompactCollector::SWEEP_IN_PARALLEL) {
3244 // When concurrent sweeping is active, the page will be marked after
3245 // sweeping by the main thread.
3246 p->set_parallel_sweeping(MemoryChunk::SWEEPING_FINALIZE);
3250 return FreeList::GuaranteedAllocatable(static_cast<int>(max_freed_bytes));
3254 static bool SetMarkBitsUnderInvalidatedCode(Code* code, bool value) {
3255 Page* p = Page::FromAddress(code->address());
3257 if (p->IsEvacuationCandidate() || p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3261 Address code_start = code->address();
3262 Address code_end = code_start + code->Size();
3264 uint32_t start_index = MemoryChunk::FastAddressToMarkbitIndex(code_start);
3265 uint32_t end_index =
3266 MemoryChunk::FastAddressToMarkbitIndex(code_end - kPointerSize);
3268 Bitmap* b = p->markbits();
3270 MarkBit start_mark_bit = b->MarkBitFromIndex(start_index);
3271 MarkBit end_mark_bit = b->MarkBitFromIndex(end_index);
3273 MarkBit::CellType* start_cell = start_mark_bit.cell();
3274 MarkBit::CellType* end_cell = end_mark_bit.cell();
3277 MarkBit::CellType start_mask = ~(start_mark_bit.mask() - 1);
3278 MarkBit::CellType end_mask = (end_mark_bit.mask() << 1) - 1;
3280 if (start_cell == end_cell) {
3281 *start_cell |= start_mask & end_mask;
3283 *start_cell |= start_mask;
3284 for (MarkBit::CellType* cell = start_cell + 1; cell < end_cell; cell++) {
3287 *end_cell |= end_mask;
3290 for (MarkBit::CellType* cell = start_cell; cell <= end_cell; cell++) {
3299 static bool IsOnInvalidatedCodeObject(Address addr) {
3300 // We did not record any slots in large objects thus
3301 // we can safely go to the page from the slot address.
3302 Page* p = Page::FromAddress(addr);
3304 // First check owner's identity because old pointer and old data spaces
3305 // are swept lazily and might still have non-zero mark-bits on some
3307 if (p->owner()->identity() != CODE_SPACE) return false;
3309 // In code space only bits on evacuation candidates (but we don't record
3310 // any slots on them) and under invalidated code objects are non-zero.
3312 p->markbits()->MarkBitFromIndex(Page::FastAddressToMarkbitIndex(addr));
3314 return mark_bit.Get();
3318 void MarkCompactCollector::InvalidateCode(Code* code) {
3319 if (heap_->incremental_marking()->IsCompacting() &&
3320 !ShouldSkipEvacuationSlotRecording(code)) {
3321 DCHECK(compacting_);
3323 // If the object is white than no slots were recorded on it yet.
3324 MarkBit mark_bit = Marking::MarkBitFrom(code);
3325 if (Marking::IsWhite(mark_bit)) return;
3327 invalidated_code_.Add(code);
3332 // Return true if the given code is deoptimized or will be deoptimized.
3333 bool MarkCompactCollector::WillBeDeoptimized(Code* code) {
3334 return code->is_optimized_code() && code->marked_for_deoptimization();
3338 bool MarkCompactCollector::MarkInvalidatedCode() {
3339 bool code_marked = false;
3341 int length = invalidated_code_.length();
3342 for (int i = 0; i < length; i++) {
3343 Code* code = invalidated_code_[i];
3345 if (SetMarkBitsUnderInvalidatedCode(code, true)) {
3354 void MarkCompactCollector::RemoveDeadInvalidatedCode() {
3355 int length = invalidated_code_.length();
3356 for (int i = 0; i < length; i++) {
3357 if (!IsMarked(invalidated_code_[i])) invalidated_code_[i] = NULL;
3362 void MarkCompactCollector::ProcessInvalidatedCode(ObjectVisitor* visitor) {
3363 int length = invalidated_code_.length();
3364 for (int i = 0; i < length; i++) {
3365 Code* code = invalidated_code_[i];
3367 code->Iterate(visitor);
3368 SetMarkBitsUnderInvalidatedCode(code, false);
3371 invalidated_code_.Rewind(0);
3375 void MarkCompactCollector::EvacuateNewSpaceAndCandidates() {
3376 Heap::RelocationLock relocation_lock(heap());
3378 bool code_slots_filtering_required;
3380 GCTracer::Scope gc_scope(heap()->tracer(),
3381 GCTracer::Scope::MC_SWEEP_NEWSPACE);
3382 code_slots_filtering_required = MarkInvalidatedCode();
3387 GCTracer::Scope gc_scope(heap()->tracer(),
3388 GCTracer::Scope::MC_EVACUATE_PAGES);
3389 EvacuationScope evacuation_scope(this);
3393 // Second pass: find pointers to new space and update them.
3394 PointersUpdatingVisitor updating_visitor(heap());
3397 GCTracer::Scope gc_scope(heap()->tracer(),
3398 GCTracer::Scope::MC_UPDATE_NEW_TO_NEW_POINTERS);
3399 // Update pointers in to space.
3400 SemiSpaceIterator to_it(heap()->new_space()->bottom(),
3401 heap()->new_space()->top());
3402 for (HeapObject* object = to_it.Next(); object != NULL;
3403 object = to_it.Next()) {
3404 Map* map = object->map();
3405 object->IterateBody(map->instance_type(), object->SizeFromMap(map),
3411 GCTracer::Scope gc_scope(heap()->tracer(),
3412 GCTracer::Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS);
3414 heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_SWEEP_NEWSPACE);
3418 GCTracer::Scope gc_scope(heap()->tracer(),
3419 GCTracer::Scope::MC_UPDATE_OLD_TO_NEW_POINTERS);
3420 StoreBufferRebuildScope scope(heap_, heap_->store_buffer(),
3421 &Heap::ScavengeStoreBufferCallback);
3422 heap_->store_buffer()->IteratePointersToNewSpaceAndClearMaps(
3427 GCTracer::Scope gc_scope(heap()->tracer(),
3428 GCTracer::Scope::MC_UPDATE_POINTERS_TO_EVACUATED);
3429 SlotsBuffer::UpdateSlotsRecordedIn(heap_, migration_slots_buffer_,
3430 code_slots_filtering_required);
3431 if (FLAG_trace_fragmentation) {
3432 PrintF(" migration slots buffer: %d\n",
3433 SlotsBuffer::SizeOfChain(migration_slots_buffer_));
3436 if (compacting_ && was_marked_incrementally_) {
3437 // It's difficult to filter out slots recorded for large objects.
3438 LargeObjectIterator it(heap_->lo_space());
3439 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
3440 // LargeObjectSpace is not swept yet thus we have to skip
3441 // dead objects explicitly.
3442 if (!IsMarked(obj)) continue;
3444 Page* p = Page::FromAddress(obj->address());
3445 if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3446 obj->Iterate(&updating_visitor);
3447 p->ClearFlag(Page::RESCAN_ON_EVACUATION);
3453 int npages = evacuation_candidates_.length();
3455 GCTracer::Scope gc_scope(
3457 GCTracer::Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED);
3458 for (int i = 0; i < npages; i++) {
3459 Page* p = evacuation_candidates_[i];
3460 DCHECK(p->IsEvacuationCandidate() ||
3461 p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3463 if (p->IsEvacuationCandidate()) {
3464 SlotsBuffer::UpdateSlotsRecordedIn(heap_, p->slots_buffer(),
3465 code_slots_filtering_required);
3466 if (FLAG_trace_fragmentation) {
3467 PrintF(" page %p slots buffer: %d\n", reinterpret_cast<void*>(p),
3468 SlotsBuffer::SizeOfChain(p->slots_buffer()));
3471 // Important: skip list should be cleared only after roots were updated
3472 // because root iteration traverses the stack and might have to find
3473 // code objects from non-updated pc pointing into evacuation candidate.
3474 SkipList* list = p->skip_list();
3475 if (list != NULL) list->Clear();
3477 if (FLAG_gc_verbose) {
3478 PrintF("Sweeping 0x%" V8PRIxPTR " during evacuation.\n",
3479 reinterpret_cast<intptr_t>(p));
3481 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3482 p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
3484 switch (space->identity()) {
3485 case OLD_DATA_SPACE:
3486 Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3487 IGNORE_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3490 case OLD_POINTER_SPACE:
3491 Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3492 IGNORE_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3496 if (FLAG_zap_code_space) {
3497 Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3498 REBUILD_SKIP_LIST, ZAP_FREE_SPACE>(space, NULL, p,
3501 Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3502 REBUILD_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3514 GCTracer::Scope gc_scope(heap()->tracer(),
3515 GCTracer::Scope::MC_UPDATE_MISC_POINTERS);
3517 // Update pointers from cells.
3518 HeapObjectIterator cell_iterator(heap_->cell_space());
3519 for (HeapObject* cell = cell_iterator.Next(); cell != NULL;
3520 cell = cell_iterator.Next()) {
3521 if (cell->IsCell()) {
3522 Cell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3526 HeapObjectIterator js_global_property_cell_iterator(
3527 heap_->property_cell_space());
3528 for (HeapObject* cell = js_global_property_cell_iterator.Next(); cell != NULL;
3529 cell = js_global_property_cell_iterator.Next()) {
3530 if (cell->IsPropertyCell()) {
3531 PropertyCell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3535 heap_->string_table()->Iterate(&updating_visitor);
3536 updating_visitor.VisitPointer(heap_->weak_object_to_code_table_address());
3537 if (heap_->weak_object_to_code_table()->IsHashTable()) {
3538 WeakHashTable* table =
3539 WeakHashTable::cast(heap_->weak_object_to_code_table());
3540 table->Iterate(&updating_visitor);
3541 table->Rehash(heap_->isolate()->factory()->undefined_value());
3544 // Update pointers from external string table.
3545 heap_->UpdateReferencesInExternalStringTable(
3546 &UpdateReferenceInExternalStringTableEntry);
3548 EvacuationWeakObjectRetainer evacuation_object_retainer;
3549 heap()->ProcessWeakReferences(&evacuation_object_retainer);
3551 // Visit invalidated code (we ignored all slots on it) and clear mark-bits
3553 ProcessInvalidatedCode(&updating_visitor);
3555 heap_->isolate()->inner_pointer_to_code_cache()->Flush();
3557 slots_buffer_allocator_.DeallocateChain(&migration_slots_buffer_);
3558 DCHECK(migration_slots_buffer_ == NULL);
3562 void MarkCompactCollector::MoveEvacuationCandidatesToEndOfPagesList() {
3563 int npages = evacuation_candidates_.length();
3564 for (int i = 0; i < npages; i++) {
3565 Page* p = evacuation_candidates_[i];
3566 if (!p->IsEvacuationCandidate()) continue;
3568 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3569 p->InsertAfter(space->LastPage());
3574 void MarkCompactCollector::ReleaseEvacuationCandidates() {
3575 int npages = evacuation_candidates_.length();
3576 for (int i = 0; i < npages; i++) {
3577 Page* p = evacuation_candidates_[i];
3578 if (!p->IsEvacuationCandidate()) continue;
3579 PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3580 space->Free(p->area_start(), p->area_size());
3581 p->set_scan_on_scavenge(false);
3582 slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
3583 p->ResetLiveBytes();
3584 space->ReleasePage(p);
3586 evacuation_candidates_.Rewind(0);
3587 compacting_ = false;
3588 heap()->FreeQueuedChunks();
3592 static const int kStartTableEntriesPerLine = 5;
3593 static const int kStartTableLines = 171;
3594 static const int kStartTableInvalidLine = 127;
3595 static const int kStartTableUnusedEntry = 126;
3597 #define _ kStartTableUnusedEntry
3598 #define X kStartTableInvalidLine
3599 // Mark-bit to object start offset table.
3601 // The line is indexed by the mark bits in a byte. The first number on
3602 // the line describes the number of live object starts for the line and the
3603 // other numbers on the line describe the offsets (in words) of the object
3606 // Since objects are at least 2 words large we don't have entries for two
3607 // consecutive 1 bits. All entries after 170 have at least 2 consecutive bits.
3608 char kStartTable[kStartTableLines * kStartTableEntriesPerLine] = {
3956 // Takes a word of mark bits. Returns the number of objects that start in the
3957 // range. Puts the offsets of the words in the supplied array.
3958 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts) {
3962 // No consecutive 1 bits.
3963 DCHECK((mark_bits & 0x180) != 0x180);
3964 DCHECK((mark_bits & 0x18000) != 0x18000);
3965 DCHECK((mark_bits & 0x1800000) != 0x1800000);
3967 while (mark_bits != 0) {
3968 int byte = (mark_bits & 0xff);
3971 DCHECK(byte < kStartTableLines); // No consecutive 1 bits.
3972 char* table = kStartTable + byte * kStartTableEntriesPerLine;
3973 int objects_in_these_8_words = table[0];
3974 DCHECK(objects_in_these_8_words != kStartTableInvalidLine);
3975 DCHECK(objects_in_these_8_words < kStartTableEntriesPerLine);
3976 for (int i = 0; i < objects_in_these_8_words; i++) {
3977 starts[objects++] = offset + table[1 + i];
3986 int MarkCompactCollector::SweepInParallel(PagedSpace* space,
3987 int required_freed_bytes) {
3989 int max_freed_overall = 0;
3990 PageIterator it(space);
3991 while (it.has_next()) {
3992 Page* p = it.next();
3993 max_freed = SweepInParallel(p, space);
3994 DCHECK(max_freed >= 0);
3995 if (required_freed_bytes > 0 && max_freed >= required_freed_bytes) {
3998 max_freed_overall = Max(max_freed, max_freed_overall);
3999 if (p == space->end_of_unswept_pages()) break;
4001 return max_freed_overall;
4005 int MarkCompactCollector::SweepInParallel(Page* page, PagedSpace* space) {
4007 if (page->TryParallelSweeping()) {
4008 FreeList* free_list = space == heap()->old_pointer_space()
4009 ? free_list_old_pointer_space_.get()
4010 : free_list_old_data_space_.get();
4011 FreeList private_free_list(space);
4012 max_freed = Sweep<SWEEP_ONLY, SWEEP_IN_PARALLEL, IGNORE_SKIP_LIST,
4013 IGNORE_FREE_SPACE>(space, &private_free_list, page, NULL);
4014 free_list->Concatenate(&private_free_list);
4020 void MarkCompactCollector::SweepSpace(PagedSpace* space, SweeperType sweeper) {
4021 space->ClearStats();
4023 // We defensively initialize end_of_unswept_pages_ here with the first page
4024 // of the pages list.
4025 space->set_end_of_unswept_pages(space->FirstPage());
4027 PageIterator it(space);
4029 int pages_swept = 0;
4030 bool unused_page_present = false;
4031 bool parallel_sweeping_active = false;
4033 while (it.has_next()) {
4034 Page* p = it.next();
4035 DCHECK(p->parallel_sweeping() == MemoryChunk::SWEEPING_DONE);
4037 // Clear sweeping flags indicating that marking bits are still intact.
4040 if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION) ||
4041 p->IsEvacuationCandidate()) {
4042 // Will be processed in EvacuateNewSpaceAndCandidates.
4043 DCHECK(evacuation_candidates_.length() > 0);
4047 // One unused page is kept, all further are released before sweeping them.
4048 if (p->LiveBytes() == 0) {
4049 if (unused_page_present) {
4050 if (FLAG_gc_verbose) {
4051 PrintF("Sweeping 0x%" V8PRIxPTR " released page.\n",
4052 reinterpret_cast<intptr_t>(p));
4054 // Adjust unswept free bytes because releasing a page expects said
4055 // counter to be accurate for unswept pages.
4056 space->IncreaseUnsweptFreeBytes(p);
4057 space->ReleasePage(p);
4060 unused_page_present = true;
4064 case CONCURRENT_SWEEPING:
4065 if (!parallel_sweeping_active) {
4066 if (FLAG_gc_verbose) {
4067 PrintF("Sweeping 0x%" V8PRIxPTR ".\n",
4068 reinterpret_cast<intptr_t>(p));
4070 Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, IGNORE_SKIP_LIST,
4071 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4073 parallel_sweeping_active = true;
4075 if (FLAG_gc_verbose) {
4076 PrintF("Sweeping 0x%" V8PRIxPTR " in parallel.\n",
4077 reinterpret_cast<intptr_t>(p));
4079 p->set_parallel_sweeping(MemoryChunk::SWEEPING_PENDING);
4080 space->IncreaseUnsweptFreeBytes(p);
4082 space->set_end_of_unswept_pages(p);
4084 case SEQUENTIAL_SWEEPING: {
4085 if (FLAG_gc_verbose) {
4086 PrintF("Sweeping 0x%" V8PRIxPTR ".\n", reinterpret_cast<intptr_t>(p));
4088 if (space->identity() == CODE_SPACE && FLAG_zap_code_space) {
4089 Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, REBUILD_SKIP_LIST,
4090 ZAP_FREE_SPACE>(space, NULL, p, NULL);
4091 } else if (space->identity() == CODE_SPACE) {
4092 Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, REBUILD_SKIP_LIST,
4093 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4095 Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, IGNORE_SKIP_LIST,
4096 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4101 default: { UNREACHABLE(); }
4105 if (FLAG_gc_verbose) {
4106 PrintF("SweepSpace: %s (%d pages swept)\n",
4107 AllocationSpaceName(space->identity()), pages_swept);
4110 // Give pages that are queued to be freed back to the OS.
4111 heap()->FreeQueuedChunks();
4115 void MarkCompactCollector::SweepSpaces() {
4116 GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_SWEEP);
4117 double start_time = 0.0;
4118 if (FLAG_print_cumulative_gc_stat) {
4119 start_time = base::OS::TimeCurrentMillis();
4123 state_ = SWEEP_SPACES;
4125 MoveEvacuationCandidatesToEndOfPagesList();
4127 // Noncompacting collections simply sweep the spaces to clear the mark
4128 // bits and free the nonlive blocks (for old and map spaces). We sweep
4129 // the map space last because freeing non-live maps overwrites them and
4130 // the other spaces rely on possibly non-live maps to get the sizes for
4131 // non-live objects.
4133 GCTracer::Scope sweep_scope(heap()->tracer(),
4134 GCTracer::Scope::MC_SWEEP_OLDSPACE);
4136 SweepSpace(heap()->old_pointer_space(), CONCURRENT_SWEEPING);
4137 SweepSpace(heap()->old_data_space(), CONCURRENT_SWEEPING);
4139 sweeping_in_progress_ = true;
4140 if (FLAG_concurrent_sweeping) {
4141 StartSweeperThreads();
4144 RemoveDeadInvalidatedCode();
4147 GCTracer::Scope sweep_scope(heap()->tracer(),
4148 GCTracer::Scope::MC_SWEEP_CODE);
4149 SweepSpace(heap()->code_space(), SEQUENTIAL_SWEEPING);
4153 GCTracer::Scope sweep_scope(heap()->tracer(),
4154 GCTracer::Scope::MC_SWEEP_CELL);
4155 SweepSpace(heap()->cell_space(), SEQUENTIAL_SWEEPING);
4156 SweepSpace(heap()->property_cell_space(), SEQUENTIAL_SWEEPING);
4159 EvacuateNewSpaceAndCandidates();
4161 // ClearNonLiveTransitions depends on precise sweeping of map space to
4162 // detect whether unmarked map became dead in this collection or in one
4163 // of the previous ones.
4165 GCTracer::Scope sweep_scope(heap()->tracer(),
4166 GCTracer::Scope::MC_SWEEP_MAP);
4167 SweepSpace(heap()->map_space(), SEQUENTIAL_SWEEPING);
4170 // Deallocate unmarked objects and clear marked bits for marked objects.
4171 heap_->lo_space()->FreeUnmarkedObjects();
4173 // Deallocate evacuated candidate pages.
4174 ReleaseEvacuationCandidates();
4175 CodeRange* code_range = heap()->isolate()->code_range();
4176 if (code_range != NULL && code_range->valid()) {
4177 code_range->ReserveEmergencyBlock();
4180 if (FLAG_print_cumulative_gc_stat) {
4181 heap_->tracer()->AddSweepingTime(base::OS::TimeCurrentMillis() -
4187 void MarkCompactCollector::ParallelSweepSpaceComplete(PagedSpace* space) {
4188 PageIterator it(space);
4189 while (it.has_next()) {
4190 Page* p = it.next();
4191 if (p->parallel_sweeping() == MemoryChunk::SWEEPING_FINALIZE) {
4192 p->set_parallel_sweeping(MemoryChunk::SWEEPING_DONE);
4195 DCHECK(p->parallel_sweeping() == MemoryChunk::SWEEPING_DONE);
4200 void MarkCompactCollector::ParallelSweepSpacesComplete() {
4201 ParallelSweepSpaceComplete(heap()->old_pointer_space());
4202 ParallelSweepSpaceComplete(heap()->old_data_space());
4206 void MarkCompactCollector::EnableCodeFlushing(bool enable) {
4207 if (isolate()->debug()->is_loaded() ||
4208 isolate()->debug()->has_break_points()) {
4213 if (code_flusher_ != NULL) return;
4214 code_flusher_ = new CodeFlusher(isolate());
4216 if (code_flusher_ == NULL) return;
4217 code_flusher_->EvictAllCandidates();
4218 delete code_flusher_;
4219 code_flusher_ = NULL;
4222 if (FLAG_trace_code_flushing) {
4223 PrintF("[code-flushing is now %s]\n", enable ? "on" : "off");
4228 // TODO(1466) ReportDeleteIfNeeded is not called currently.
4229 // Our profiling tools do not expect intersections between
4230 // code objects. We should either reenable it or change our tools.
4231 void MarkCompactCollector::ReportDeleteIfNeeded(HeapObject* obj,
4233 if (obj->IsCode()) {
4234 PROFILE(isolate, CodeDeleteEvent(obj->address()));
4239 Isolate* MarkCompactCollector::isolate() const { return heap_->isolate(); }
4242 void MarkCompactCollector::Initialize() {
4243 MarkCompactMarkingVisitor::Initialize();
4244 IncrementalMarking::Initialize();
4248 bool SlotsBuffer::IsTypedSlot(ObjectSlot slot) {
4249 return reinterpret_cast<uintptr_t>(slot) < NUMBER_OF_SLOT_TYPES;
4253 bool SlotsBuffer::AddTo(SlotsBufferAllocator* allocator,
4254 SlotsBuffer** buffer_address, SlotType type,
4255 Address addr, AdditionMode mode) {
4256 SlotsBuffer* buffer = *buffer_address;
4257 if (buffer == NULL || !buffer->HasSpaceForTypedSlot()) {
4258 if (mode == FAIL_ON_OVERFLOW && ChainLengthThresholdReached(buffer)) {
4259 allocator->DeallocateChain(buffer_address);
4262 buffer = allocator->AllocateBuffer(buffer);
4263 *buffer_address = buffer;
4265 DCHECK(buffer->HasSpaceForTypedSlot());
4266 buffer->Add(reinterpret_cast<ObjectSlot>(type));
4267 buffer->Add(reinterpret_cast<ObjectSlot>(addr));
4272 static inline SlotsBuffer::SlotType SlotTypeForRMode(RelocInfo::Mode rmode) {
4273 if (RelocInfo::IsCodeTarget(rmode)) {
4274 return SlotsBuffer::CODE_TARGET_SLOT;
4275 } else if (RelocInfo::IsEmbeddedObject(rmode)) {
4276 return SlotsBuffer::EMBEDDED_OBJECT_SLOT;
4277 } else if (RelocInfo::IsDebugBreakSlot(rmode)) {
4278 return SlotsBuffer::DEBUG_TARGET_SLOT;
4279 } else if (RelocInfo::IsJSReturn(rmode)) {
4280 return SlotsBuffer::JS_RETURN_SLOT;
4283 return SlotsBuffer::NUMBER_OF_SLOT_TYPES;
4287 void MarkCompactCollector::RecordRelocSlot(RelocInfo* rinfo, Object* target) {
4288 Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4289 RelocInfo::Mode rmode = rinfo->rmode();
4290 if (target_page->IsEvacuationCandidate() &&
4291 (rinfo->host() == NULL ||
4292 !ShouldSkipEvacuationSlotRecording(rinfo->host()))) {
4294 if (RelocInfo::IsEmbeddedObject(rmode) && rinfo->IsInConstantPool()) {
4295 // This doesn't need to be typed since it is just a normal heap pointer.
4296 Object** target_pointer =
4297 reinterpret_cast<Object**>(rinfo->constant_pool_entry_address());
4298 success = SlotsBuffer::AddTo(
4299 &slots_buffer_allocator_, target_page->slots_buffer_address(),
4300 target_pointer, SlotsBuffer::FAIL_ON_OVERFLOW);
4301 } else if (RelocInfo::IsCodeTarget(rmode) && rinfo->IsInConstantPool()) {
4302 success = SlotsBuffer::AddTo(
4303 &slots_buffer_allocator_, target_page->slots_buffer_address(),
4304 SlotsBuffer::CODE_ENTRY_SLOT, rinfo->constant_pool_entry_address(),
4305 SlotsBuffer::FAIL_ON_OVERFLOW);
4307 success = SlotsBuffer::AddTo(
4308 &slots_buffer_allocator_, target_page->slots_buffer_address(),
4309 SlotTypeForRMode(rmode), rinfo->pc(), SlotsBuffer::FAIL_ON_OVERFLOW);
4312 EvictEvacuationCandidate(target_page);
4318 void MarkCompactCollector::RecordCodeEntrySlot(Address slot, Code* target) {
4319 Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4320 if (target_page->IsEvacuationCandidate() &&
4321 !ShouldSkipEvacuationSlotRecording(reinterpret_cast<Object**>(slot))) {
4322 if (!SlotsBuffer::AddTo(&slots_buffer_allocator_,
4323 target_page->slots_buffer_address(),
4324 SlotsBuffer::CODE_ENTRY_SLOT, slot,
4325 SlotsBuffer::FAIL_ON_OVERFLOW)) {
4326 EvictEvacuationCandidate(target_page);
4332 void MarkCompactCollector::RecordCodeTargetPatch(Address pc, Code* target) {
4333 DCHECK(heap()->gc_state() == Heap::MARK_COMPACT);
4334 if (is_compacting()) {
4336 isolate()->inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(
4338 MarkBit mark_bit = Marking::MarkBitFrom(host);
4339 if (Marking::IsBlack(mark_bit)) {
4340 RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
4341 RecordRelocSlot(&rinfo, target);
4347 static inline SlotsBuffer::SlotType DecodeSlotType(
4348 SlotsBuffer::ObjectSlot slot) {
4349 return static_cast<SlotsBuffer::SlotType>(reinterpret_cast<intptr_t>(slot));
4353 void SlotsBuffer::UpdateSlots(Heap* heap) {
4354 PointersUpdatingVisitor v(heap);
4356 for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4357 ObjectSlot slot = slots_[slot_idx];
4358 if (!IsTypedSlot(slot)) {
4359 PointersUpdatingVisitor::UpdateSlot(heap, slot);
4362 DCHECK(slot_idx < idx_);
4363 UpdateSlot(heap->isolate(), &v, DecodeSlotType(slot),
4364 reinterpret_cast<Address>(slots_[slot_idx]));
4370 void SlotsBuffer::UpdateSlotsWithFilter(Heap* heap) {
4371 PointersUpdatingVisitor v(heap);
4373 for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4374 ObjectSlot slot = slots_[slot_idx];
4375 if (!IsTypedSlot(slot)) {
4376 if (!IsOnInvalidatedCodeObject(reinterpret_cast<Address>(slot))) {
4377 PointersUpdatingVisitor::UpdateSlot(heap, slot);
4381 DCHECK(slot_idx < idx_);
4382 Address pc = reinterpret_cast<Address>(slots_[slot_idx]);
4383 if (!IsOnInvalidatedCodeObject(pc)) {
4384 UpdateSlot(heap->isolate(), &v, DecodeSlotType(slot),
4385 reinterpret_cast<Address>(slots_[slot_idx]));
4392 SlotsBuffer* SlotsBufferAllocator::AllocateBuffer(SlotsBuffer* next_buffer) {
4393 return new SlotsBuffer(next_buffer);
4397 void SlotsBufferAllocator::DeallocateBuffer(SlotsBuffer* buffer) {
4402 void SlotsBufferAllocator::DeallocateChain(SlotsBuffer** buffer_address) {
4403 SlotsBuffer* buffer = *buffer_address;
4404 while (buffer != NULL) {
4405 SlotsBuffer* next_buffer = buffer->next();
4406 DeallocateBuffer(buffer);
4407 buffer = next_buffer;
4409 *buffer_address = NULL;
4412 } // namespace v8::internal