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/accessors.h"
9 #include "src/base/bits.h"
10 #include "src/base/once.h"
11 #include "src/base/utils/random-number-generator.h"
12 #include "src/bootstrapper.h"
13 #include "src/codegen.h"
14 #include "src/compilation-cache.h"
15 #include "src/conversions.h"
16 #include "src/cpu-profiler.h"
17 #include "src/debug/debug.h"
18 #include "src/deoptimizer.h"
19 #include "src/global-handles.h"
20 #include "src/heap/gc-idle-time-handler.h"
21 #include "src/heap/incremental-marking.h"
22 #include "src/heap/mark-compact-inl.h"
23 #include "src/heap/mark-compact.h"
24 #include "src/heap/memory-reducer.h"
25 #include "src/heap/objects-visiting-inl.h"
26 #include "src/heap/objects-visiting.h"
27 #include "src/heap/store-buffer.h"
28 #include "src/heap-profiler.h"
29 #include "src/interpreter/interpreter.h"
30 #include "src/runtime-profiler.h"
31 #include "src/scopeinfo.h"
32 #include "src/snapshot/natives.h"
33 #include "src/snapshot/serialize.h"
34 #include "src/snapshot/snapshot.h"
35 #include "src/utils.h"
36 #include "src/v8threads.h"
37 #include "src/vm-state-inl.h"
39 #if V8_TARGET_ARCH_PPC && !V8_INTERPRETED_REGEXP
40 #include "src/regexp-macro-assembler.h" // NOLINT
41 #include "src/ppc/regexp-macro-assembler-ppc.h" // NOLINT
43 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
44 #include "src/regexp-macro-assembler.h" // NOLINT
45 #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
47 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
48 #include "src/regexp-macro-assembler.h" // NOLINT
49 #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
51 #if V8_TARGET_ARCH_MIPS64 && !V8_INTERPRETED_REGEXP
52 #include "src/regexp-macro-assembler.h"
53 #include "src/mips64/regexp-macro-assembler-mips64.h"
60 struct Heap::StrongRootsList {
63 StrongRootsList* next;
68 : amount_of_external_allocated_memory_(0),
69 amount_of_external_allocated_memory_at_last_global_gc_(0),
72 // semispace_size_ should be a power of 2 and old_generation_size_ should
73 // be a multiple of Page::kPageSize.
74 reserved_semispace_size_(8 * (kPointerSize / 4) * MB),
75 max_semi_space_size_(8 * (kPointerSize / 4) * MB),
76 initial_semispace_size_(Page::kPageSize),
77 target_semispace_size_(Page::kPageSize),
78 max_old_generation_size_(700ul * (kPointerSize / 4) * MB),
79 initial_old_generation_size_(max_old_generation_size_ /
80 kInitalOldGenerationLimitFactor),
81 old_generation_size_configured_(false),
82 max_executable_size_(256ul * (kPointerSize / 4) * MB),
83 // Variables set based on semispace_size_ and old_generation_size_ in
85 // Will be 4 * reserved_semispace_size_ to ensure that young
86 // generation can be aligned to its size.
87 maximum_committed_(0),
88 survived_since_last_expansion_(0),
89 survived_last_scavenge_(0),
91 always_allocate_scope_depth_(0),
92 contexts_disposed_(0),
94 scan_on_scavenge_pages_(0),
100 gc_state_(NOT_IN_GC),
101 gc_post_processing_depth_(0),
102 allocations_count_(0),
103 raw_allocations_hash_(0),
104 dump_allocations_hash_countdown_(FLAG_dump_allocations_digest_at_alloc),
107 remembered_unmapped_pages_index_(0),
108 unflattened_strings_length_(0),
110 allocation_timeout_(0),
112 old_generation_allocation_limit_(initial_old_generation_size_),
113 old_gen_exhausted_(false),
114 optimize_for_memory_usage_(false),
115 inline_allocation_disabled_(false),
116 store_buffer_rebuilder_(store_buffer()),
117 hidden_string_(NULL),
118 total_regexp_code_generated_(0),
120 high_survival_rate_period_length_(0),
121 promoted_objects_size_(0),
123 semi_space_copied_object_size_(0),
124 previous_semi_space_copied_object_size_(0),
125 semi_space_copied_rate_(0),
126 nodes_died_in_new_space_(0),
127 nodes_copied_in_new_space_(0),
129 maximum_size_scavenges_(0),
131 total_gc_time_ms_(0.0),
132 max_alive_after_gc_(0),
133 min_in_mutator_(kMaxInt),
136 last_idle_notification_time_(0.0),
138 mark_compact_collector_(this),
140 incremental_marking_(this),
141 memory_reducer_(this),
142 full_codegen_bytes_generated_(0),
143 crankshaft_codegen_bytes_generated_(0),
144 new_space_allocation_counter_(0),
145 old_generation_allocation_counter_(0),
146 old_generation_size_at_last_gc_(0),
147 gcs_since_last_deopt_(0),
148 allocation_sites_scratchpad_length_(0),
149 ring_buffer_full_(false),
151 promotion_queue_(this),
153 external_string_table_(this),
154 chunks_queued_for_free_(NULL),
155 gc_callbacks_depth_(0),
156 deserialization_complete_(false),
157 concurrent_sweeping_enabled_(false),
158 strong_roots_list_(NULL) {
159 // Allow build-time customization of the max semispace size. Building
160 // V8 with snapshots and a non-default max semispace size is much
161 // easier if you can define it as part of the build environment.
162 #if defined(V8_MAX_SEMISPACE_SIZE)
163 max_semi_space_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
166 // Ensure old_generation_size_ is a multiple of kPageSize.
167 DCHECK((max_old_generation_size_ & (Page::kPageSize - 1)) == 0);
169 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
170 set_native_contexts_list(NULL);
171 set_allocation_sites_list(Smi::FromInt(0));
172 set_encountered_weak_collections(Smi::FromInt(0));
173 set_encountered_weak_cells(Smi::FromInt(0));
174 // Put a dummy entry in the remembered pages so we can find the list the
175 // minidump even if there are no real unmapped pages.
176 RememberUnmappedPage(NULL, false);
178 ClearObjectStats(true);
182 intptr_t Heap::Capacity() {
183 if (!HasBeenSetUp()) return 0;
185 return new_space_.Capacity() + old_space_->Capacity() +
186 code_space_->Capacity() + map_space_->Capacity();
190 intptr_t Heap::CommittedOldGenerationMemory() {
191 if (!HasBeenSetUp()) return 0;
193 return old_space_->CommittedMemory() + code_space_->CommittedMemory() +
194 map_space_->CommittedMemory() + lo_space_->Size();
198 intptr_t Heap::CommittedMemory() {
199 if (!HasBeenSetUp()) return 0;
201 return new_space_.CommittedMemory() + CommittedOldGenerationMemory();
205 size_t Heap::CommittedPhysicalMemory() {
206 if (!HasBeenSetUp()) return 0;
208 return new_space_.CommittedPhysicalMemory() +
209 old_space_->CommittedPhysicalMemory() +
210 code_space_->CommittedPhysicalMemory() +
211 map_space_->CommittedPhysicalMemory() +
212 lo_space_->CommittedPhysicalMemory();
216 intptr_t Heap::CommittedMemoryExecutable() {
217 if (!HasBeenSetUp()) return 0;
219 return isolate()->memory_allocator()->SizeExecutable();
223 void Heap::UpdateMaximumCommitted() {
224 if (!HasBeenSetUp()) return;
226 intptr_t current_committed_memory = CommittedMemory();
227 if (current_committed_memory > maximum_committed_) {
228 maximum_committed_ = current_committed_memory;
233 intptr_t Heap::Available() {
234 if (!HasBeenSetUp()) return 0;
237 AllSpaces spaces(this);
238 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
239 total += space->Available();
245 bool Heap::HasBeenSetUp() {
246 return old_space_ != NULL && code_space_ != NULL && map_space_ != NULL &&
251 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
252 const char** reason) {
253 // Is global GC requested?
254 if (space != NEW_SPACE) {
255 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
256 *reason = "GC in old space requested";
257 return MARK_COMPACTOR;
260 if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
261 *reason = "GC in old space forced by flags";
262 return MARK_COMPACTOR;
265 // Is enough data promoted to justify a global GC?
266 if (OldGenerationAllocationLimitReached()) {
267 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
268 *reason = "promotion limit reached";
269 return MARK_COMPACTOR;
272 // Have allocation in OLD and LO failed?
273 if (old_gen_exhausted_) {
275 ->gc_compactor_caused_by_oldspace_exhaustion()
277 *reason = "old generations exhausted";
278 return MARK_COMPACTOR;
281 // Is there enough space left in OLD to guarantee that a scavenge can
284 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
285 // for object promotion. It counts only the bytes that the memory
286 // allocator has not yet allocated from the OS and assigned to any space,
287 // and does not count available bytes already in the old space or code
288 // space. Undercounting is safe---we may get an unrequested full GC when
289 // a scavenge would have succeeded.
290 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
292 ->gc_compactor_caused_by_oldspace_exhaustion()
294 *reason = "scavenge might not succeed";
295 return MARK_COMPACTOR;
304 // TODO(1238405): Combine the infrastructure for --heap-stats and
305 // --log-gc to avoid the complicated preprocessor and flag testing.
306 void Heap::ReportStatisticsBeforeGC() {
307 // Heap::ReportHeapStatistics will also log NewSpace statistics when
308 // compiled --log-gc is set. The following logic is used to avoid
311 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
312 if (FLAG_heap_stats) {
313 ReportHeapStatistics("Before GC");
314 } else if (FLAG_log_gc) {
315 new_space_.ReportStatistics();
317 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
320 new_space_.CollectStatistics();
321 new_space_.ReportStatistics();
322 new_space_.ClearHistograms();
328 void Heap::PrintShortHeapStatistics() {
329 if (!FLAG_trace_gc_verbose) return;
330 PrintIsolate(isolate_, "Memory allocator, used: %6" V8_PTR_PREFIX
332 ", available: %6" V8_PTR_PREFIX "d KB\n",
333 isolate_->memory_allocator()->Size() / KB,
334 isolate_->memory_allocator()->Available() / KB);
335 PrintIsolate(isolate_, "New space, used: %6" V8_PTR_PREFIX
337 ", available: %6" V8_PTR_PREFIX
339 ", committed: %6" V8_PTR_PREFIX "d KB\n",
340 new_space_.Size() / KB, new_space_.Available() / KB,
341 new_space_.CommittedMemory() / KB);
342 PrintIsolate(isolate_, "Old space, used: %6" V8_PTR_PREFIX
344 ", available: %6" V8_PTR_PREFIX
346 ", committed: %6" V8_PTR_PREFIX "d KB\n",
347 old_space_->SizeOfObjects() / KB, old_space_->Available() / KB,
348 old_space_->CommittedMemory() / KB);
349 PrintIsolate(isolate_, "Code space, used: %6" V8_PTR_PREFIX
351 ", available: %6" V8_PTR_PREFIX
353 ", committed: %6" V8_PTR_PREFIX "d KB\n",
354 code_space_->SizeOfObjects() / KB, code_space_->Available() / KB,
355 code_space_->CommittedMemory() / KB);
356 PrintIsolate(isolate_, "Map space, used: %6" V8_PTR_PREFIX
358 ", available: %6" V8_PTR_PREFIX
360 ", committed: %6" V8_PTR_PREFIX "d KB\n",
361 map_space_->SizeOfObjects() / KB, map_space_->Available() / KB,
362 map_space_->CommittedMemory() / KB);
363 PrintIsolate(isolate_, "Large object space, used: %6" V8_PTR_PREFIX
365 ", available: %6" V8_PTR_PREFIX
367 ", committed: %6" V8_PTR_PREFIX "d KB\n",
368 lo_space_->SizeOfObjects() / KB, lo_space_->Available() / KB,
369 lo_space_->CommittedMemory() / KB);
370 PrintIsolate(isolate_, "All spaces, used: %6" V8_PTR_PREFIX
372 ", available: %6" V8_PTR_PREFIX
374 ", committed: %6" V8_PTR_PREFIX "d KB\n",
375 this->SizeOfObjects() / KB, this->Available() / KB,
376 this->CommittedMemory() / KB);
378 isolate_, "External memory reported: %6" V8_PTR_PREFIX "d KB\n",
379 static_cast<intptr_t>(amount_of_external_allocated_memory_ / KB));
380 PrintIsolate(isolate_, "Total time spent in GC : %.1f ms\n",
385 // TODO(1238405): Combine the infrastructure for --heap-stats and
386 // --log-gc to avoid the complicated preprocessor and flag testing.
387 void Heap::ReportStatisticsAfterGC() {
388 // Similar to the before GC, we use some complicated logic to ensure that
389 // NewSpace statistics are logged exactly once when --log-gc is turned on.
391 if (FLAG_heap_stats) {
392 new_space_.CollectStatistics();
393 ReportHeapStatistics("After GC");
394 } else if (FLAG_log_gc) {
395 new_space_.ReportStatistics();
398 if (FLAG_log_gc) new_space_.ReportStatistics();
400 for (int i = 0; i < static_cast<int>(v8::Isolate::kUseCounterFeatureCount);
402 int count = deferred_counters_[i];
403 deferred_counters_[i] = 0;
406 isolate()->CountUsage(static_cast<v8::Isolate::UseCounterFeature>(i));
412 void Heap::IncrementDeferredCount(v8::Isolate::UseCounterFeature feature) {
413 deferred_counters_[feature]++;
417 void Heap::GarbageCollectionPrologue() {
419 AllowHeapAllocation for_the_first_part_of_prologue;
421 unflattened_strings_length_ = 0;
423 if (FLAG_flush_code) {
424 mark_compact_collector()->EnableCodeFlushing(true);
428 if (FLAG_verify_heap) {
434 // Reset GC statistics.
435 promoted_objects_size_ = 0;
436 previous_semi_space_copied_object_size_ = semi_space_copied_object_size_;
437 semi_space_copied_object_size_ = 0;
438 nodes_died_in_new_space_ = 0;
439 nodes_copied_in_new_space_ = 0;
442 UpdateMaximumCommitted();
445 DCHECK(!AllowHeapAllocation::IsAllowed() && gc_state_ == NOT_IN_GC);
447 if (FLAG_gc_verbose) Print();
449 ReportStatisticsBeforeGC();
452 store_buffer()->GCPrologue();
454 if (isolate()->concurrent_osr_enabled()) {
455 isolate()->optimizing_compile_dispatcher()->AgeBufferedOsrJobs();
458 if (new_space_.IsAtMaximumCapacity()) {
459 maximum_size_scavenges_++;
461 maximum_size_scavenges_ = 0;
463 CheckNewSpaceExpansionCriteria();
464 UpdateNewSpaceAllocationCounter();
468 intptr_t Heap::SizeOfObjects() {
470 AllSpaces spaces(this);
471 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
472 total += space->SizeOfObjects();
478 const char* Heap::GetSpaceName(int idx) {
489 return "large_object_space";
497 void Heap::ClearAllICsByKind(Code::Kind kind) {
498 // TODO(mvstanton): Do not iterate the heap.
499 HeapObjectIterator it(code_space());
501 for (Object* object = it.Next(); object != NULL; object = it.Next()) {
502 Code* code = Code::cast(object);
503 Code::Kind current_kind = code->kind();
504 if (current_kind == Code::FUNCTION ||
505 current_kind == Code::OPTIMIZED_FUNCTION) {
506 code->ClearInlineCaches(kind);
512 void Heap::RepairFreeListsAfterDeserialization() {
513 PagedSpaces spaces(this);
514 for (PagedSpace* space = spaces.next(); space != NULL;
515 space = spaces.next()) {
516 space->RepairFreeListsAfterDeserialization();
521 bool Heap::ProcessPretenuringFeedback() {
522 bool trigger_deoptimization = false;
523 if (FLAG_allocation_site_pretenuring) {
524 int tenure_decisions = 0;
525 int dont_tenure_decisions = 0;
526 int allocation_mementos_found = 0;
527 int allocation_sites = 0;
528 int active_allocation_sites = 0;
530 // If the scratchpad overflowed, we have to iterate over the allocation
532 // TODO(hpayer): We iterate over the whole list of allocation sites when
533 // we grew to the maximum semi-space size to deopt maybe tenured
534 // allocation sites. We could hold the maybe tenured allocation sites
535 // in a seperate data structure if this is a performance problem.
536 bool deopt_maybe_tenured = DeoptMaybeTenuredAllocationSites();
537 bool use_scratchpad =
538 allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize &&
539 !deopt_maybe_tenured;
542 Object* list_element = allocation_sites_list();
543 bool maximum_size_scavenge = MaximumSizeScavenge();
544 while (use_scratchpad ? i < allocation_sites_scratchpad_length_
545 : list_element->IsAllocationSite()) {
546 AllocationSite* site =
548 ? AllocationSite::cast(allocation_sites_scratchpad()->get(i))
549 : AllocationSite::cast(list_element);
550 allocation_mementos_found += site->memento_found_count();
551 if (site->memento_found_count() > 0) {
552 active_allocation_sites++;
553 if (site->DigestPretenuringFeedback(maximum_size_scavenge)) {
554 trigger_deoptimization = true;
556 if (site->GetPretenureMode() == TENURED) {
559 dont_tenure_decisions++;
564 if (deopt_maybe_tenured && site->IsMaybeTenure()) {
565 site->set_deopt_dependent_code(true);
566 trigger_deoptimization = true;
569 if (use_scratchpad) {
572 list_element = site->weak_next();
576 if (trigger_deoptimization) {
577 isolate_->stack_guard()->RequestDeoptMarkedAllocationSites();
580 FlushAllocationSitesScratchpad();
582 if (FLAG_trace_pretenuring_statistics &&
583 (allocation_mementos_found > 0 || tenure_decisions > 0 ||
584 dont_tenure_decisions > 0)) {
586 "GC: (mode, #visited allocation sites, #active allocation sites, "
587 "#mementos, #tenure decisions, #donttenure decisions) "
588 "(%s, %d, %d, %d, %d, %d)\n",
589 use_scratchpad ? "use scratchpad" : "use list", allocation_sites,
590 active_allocation_sites, allocation_mementos_found, tenure_decisions,
591 dont_tenure_decisions);
594 return trigger_deoptimization;
598 void Heap::DeoptMarkedAllocationSites() {
599 // TODO(hpayer): If iterating over the allocation sites list becomes a
600 // performance issue, use a cache heap data structure instead (similar to the
601 // allocation sites scratchpad).
602 Object* list_element = allocation_sites_list();
603 while (list_element->IsAllocationSite()) {
604 AllocationSite* site = AllocationSite::cast(list_element);
605 if (site->deopt_dependent_code()) {
606 site->dependent_code()->MarkCodeForDeoptimization(
607 isolate_, DependentCode::kAllocationSiteTenuringChangedGroup);
608 site->set_deopt_dependent_code(false);
610 list_element = site->weak_next();
612 Deoptimizer::DeoptimizeMarkedCode(isolate_);
616 void Heap::GarbageCollectionEpilogue() {
617 store_buffer()->GCEpilogue();
619 // In release mode, we only zap the from space under heap verification.
620 if (Heap::ShouldZapGarbage()) {
625 if (FLAG_verify_heap) {
630 AllowHeapAllocation for_the_rest_of_the_epilogue;
633 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
634 if (FLAG_print_handles) PrintHandles();
635 if (FLAG_gc_verbose) Print();
636 if (FLAG_code_stats) ReportCodeStatistics("After GC");
637 if (FLAG_check_handle_count) CheckHandleCount();
639 if (FLAG_deopt_every_n_garbage_collections > 0) {
640 // TODO(jkummerow/ulan/jarin): This is not safe! We can't assume that
641 // the topmost optimized frame can be deoptimized safely, because it
642 // might not have a lazy bailout point right after its current PC.
643 if (++gcs_since_last_deopt_ == FLAG_deopt_every_n_garbage_collections) {
644 Deoptimizer::DeoptimizeAll(isolate());
645 gcs_since_last_deopt_ = 0;
649 UpdateMaximumCommitted();
651 isolate_->counters()->alive_after_last_gc()->Set(
652 static_cast<int>(SizeOfObjects()));
654 isolate_->counters()->string_table_capacity()->Set(
655 string_table()->Capacity());
656 isolate_->counters()->number_of_symbols()->Set(
657 string_table()->NumberOfElements());
659 if (full_codegen_bytes_generated_ + crankshaft_codegen_bytes_generated_ > 0) {
660 isolate_->counters()->codegen_fraction_crankshaft()->AddSample(
661 static_cast<int>((crankshaft_codegen_bytes_generated_ * 100.0) /
662 (crankshaft_codegen_bytes_generated_ +
663 full_codegen_bytes_generated_)));
666 if (CommittedMemory() > 0) {
667 isolate_->counters()->external_fragmentation_total()->AddSample(
668 static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory()));
670 isolate_->counters()->heap_fraction_new_space()->AddSample(static_cast<int>(
671 (new_space()->CommittedMemory() * 100.0) / CommittedMemory()));
672 isolate_->counters()->heap_fraction_old_space()->AddSample(static_cast<int>(
673 (old_space()->CommittedMemory() * 100.0) / CommittedMemory()));
674 isolate_->counters()->heap_fraction_code_space()->AddSample(
675 static_cast<int>((code_space()->CommittedMemory() * 100.0) /
677 isolate_->counters()->heap_fraction_map_space()->AddSample(static_cast<int>(
678 (map_space()->CommittedMemory() * 100.0) / CommittedMemory()));
679 isolate_->counters()->heap_fraction_lo_space()->AddSample(static_cast<int>(
680 (lo_space()->CommittedMemory() * 100.0) / CommittedMemory()));
682 isolate_->counters()->heap_sample_total_committed()->AddSample(
683 static_cast<int>(CommittedMemory() / KB));
684 isolate_->counters()->heap_sample_total_used()->AddSample(
685 static_cast<int>(SizeOfObjects() / KB));
686 isolate_->counters()->heap_sample_map_space_committed()->AddSample(
687 static_cast<int>(map_space()->CommittedMemory() / KB));
688 isolate_->counters()->heap_sample_code_space_committed()->AddSample(
689 static_cast<int>(code_space()->CommittedMemory() / KB));
691 isolate_->counters()->heap_sample_maximum_committed()->AddSample(
692 static_cast<int>(MaximumCommittedMemory() / KB));
695 #define UPDATE_COUNTERS_FOR_SPACE(space) \
696 isolate_->counters()->space##_bytes_available()->Set( \
697 static_cast<int>(space()->Available())); \
698 isolate_->counters()->space##_bytes_committed()->Set( \
699 static_cast<int>(space()->CommittedMemory())); \
700 isolate_->counters()->space##_bytes_used()->Set( \
701 static_cast<int>(space()->SizeOfObjects()));
702 #define UPDATE_FRAGMENTATION_FOR_SPACE(space) \
703 if (space()->CommittedMemory() > 0) { \
704 isolate_->counters()->external_fragmentation_##space()->AddSample( \
705 static_cast<int>(100 - \
706 (space()->SizeOfObjects() * 100.0) / \
707 space()->CommittedMemory())); \
709 #define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space) \
710 UPDATE_COUNTERS_FOR_SPACE(space) \
711 UPDATE_FRAGMENTATION_FOR_SPACE(space)
713 UPDATE_COUNTERS_FOR_SPACE(new_space)
714 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_space)
715 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space)
716 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space)
717 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space)
718 #undef UPDATE_COUNTERS_FOR_SPACE
719 #undef UPDATE_FRAGMENTATION_FOR_SPACE
720 #undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE
723 ReportStatisticsAfterGC();
726 // Remember the last top pointer so that we can later find out
727 // whether we allocated in new space since the last GC.
728 new_space_top_after_last_gc_ = new_space()->top();
729 last_gc_time_ = MonotonicallyIncreasingTimeInMs();
731 ReduceNewSpaceSize();
735 void Heap::PreprocessStackTraces() {
736 if (!weak_stack_trace_list()->IsWeakFixedArray()) return;
737 WeakFixedArray* array = WeakFixedArray::cast(weak_stack_trace_list());
738 int length = array->Length();
739 for (int i = 0; i < length; i++) {
740 if (array->IsEmptySlot(i)) continue;
741 FixedArray* elements = FixedArray::cast(array->Get(i));
742 for (int j = 1; j < elements->length(); j += 4) {
743 Object* maybe_code = elements->get(j + 2);
744 // If GC happens while adding a stack trace to the weak fixed array,
745 // which has been copied into a larger backing store, we may run into
746 // a stack trace that has already been preprocessed. Guard against this.
747 if (!maybe_code->IsCode()) break;
748 Code* code = Code::cast(maybe_code);
749 int offset = Smi::cast(elements->get(j + 3))->value();
750 Address pc = code->address() + offset;
751 int pos = code->SourcePosition(pc);
752 elements->set(j + 2, Smi::FromInt(pos));
755 // We must not compact the weak fixed list here, as we may be in the middle
756 // of writing to it, when the GC triggered. Instead, we reset the root value.
757 set_weak_stack_trace_list(Smi::FromInt(0));
761 void Heap::HandleGCRequest() {
762 if (incremental_marking()->request_type() ==
763 IncrementalMarking::COMPLETE_MARKING) {
764 CollectAllGarbage(Heap::kNoGCFlags, "GC interrupt",
765 incremental_marking()->CallbackFlags());
768 DCHECK(FLAG_overapproximate_weak_closure);
769 if (!incremental_marking()->weak_closure_was_overapproximated()) {
770 OverApproximateWeakClosure("GC interrupt");
775 void Heap::OverApproximateWeakClosure(const char* gc_reason) {
776 if (FLAG_trace_incremental_marking) {
777 PrintF("[IncrementalMarking] Overapproximate weak closure (%s).\n",
781 GCTracer::Scope gc_scope(tracer(),
782 GCTracer::Scope::MC_INCREMENTAL_WEAKCLOSURE);
785 GCCallbacksScope scope(this);
786 if (scope.CheckReenter()) {
787 AllowHeapAllocation allow_allocation;
788 GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
789 VMState<EXTERNAL> state(isolate_);
790 HandleScope handle_scope(isolate_);
791 CallGCPrologueCallbacks(kGCTypeMarkSweepCompact, kNoGCCallbackFlags);
794 incremental_marking()->MarkObjectGroups();
796 GCCallbacksScope scope(this);
797 if (scope.CheckReenter()) {
798 AllowHeapAllocation allow_allocation;
799 GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
800 VMState<EXTERNAL> state(isolate_);
801 HandleScope handle_scope(isolate_);
802 CallGCEpilogueCallbacks(kGCTypeMarkSweepCompact, kNoGCCallbackFlags);
808 void Heap::CollectAllGarbage(int flags, const char* gc_reason,
809 const v8::GCCallbackFlags gc_callback_flags) {
810 // Since we are ignoring the return value, the exact choice of space does
811 // not matter, so long as we do not specify NEW_SPACE, which would not
813 mark_compact_collector_.SetFlags(flags);
814 CollectGarbage(OLD_SPACE, gc_reason, gc_callback_flags);
815 mark_compact_collector_.SetFlags(kNoGCFlags);
819 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
820 // Since we are ignoring the return value, the exact choice of space does
821 // not matter, so long as we do not specify NEW_SPACE, which would not
823 // Major GC would invoke weak handle callbacks on weakly reachable
824 // handles, but won't collect weakly reachable objects until next
825 // major GC. Therefore if we collect aggressively and weak handle callback
826 // has been invoked, we rerun major GC to release objects which become
828 // Note: as weak callbacks can execute arbitrary code, we cannot
829 // hope that eventually there will be no weak callbacks invocations.
830 // Therefore stop recollecting after several attempts.
831 if (isolate()->concurrent_recompilation_enabled()) {
832 // The optimizing compiler may be unnecessarily holding on to memory.
833 DisallowHeapAllocation no_recursive_gc;
834 isolate()->optimizing_compile_dispatcher()->Flush();
836 isolate()->ClearSerializerData();
837 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
838 kReduceMemoryFootprintMask);
839 isolate_->compilation_cache()->Clear();
840 const int kMaxNumberOfAttempts = 7;
841 const int kMinNumberOfAttempts = 2;
842 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
843 if (!CollectGarbage(MARK_COMPACTOR, gc_reason, NULL,
844 v8::kGCCallbackFlagForced) &&
845 attempt + 1 >= kMinNumberOfAttempts) {
849 mark_compact_collector()->SetFlags(kNoGCFlags);
855 void Heap::EnsureFillerObjectAtTop() {
856 // There may be an allocation memento behind every object in new space.
857 // If we evacuate a not full new space or if we are on the last page of
858 // the new space, then there may be uninitialized memory behind the top
859 // pointer of the new space page. We store a filler object there to
860 // identify the unused space.
861 Address from_top = new_space_.top();
862 // Check that from_top is inside its page (i.e., not at the end).
863 Address space_end = new_space_.ToSpaceEnd();
864 if (from_top < space_end) {
865 Page* page = Page::FromAddress(from_top);
866 if (page->Contains(from_top)) {
867 int remaining_in_page = static_cast<int>(page->area_end() - from_top);
868 CreateFillerObjectAt(from_top, remaining_in_page);
874 bool Heap::CollectGarbage(GarbageCollector collector, const char* gc_reason,
875 const char* collector_reason,
876 const v8::GCCallbackFlags gc_callback_flags) {
877 // The VM is in the GC state until exiting this function.
878 VMState<GC> state(isolate_);
881 // Reset the allocation timeout to the GC interval, but make sure to
882 // allow at least a few allocations after a collection. The reason
883 // for this is that we have a lot of allocation sequences and we
884 // assume that a garbage collection will allow the subsequent
885 // allocation attempts to go through.
886 allocation_timeout_ = Max(6, FLAG_gc_interval);
889 EnsureFillerObjectAtTop();
891 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
892 if (FLAG_trace_incremental_marking) {
893 PrintF("[IncrementalMarking] Scavenge during marking.\n");
897 if (collector == MARK_COMPACTOR &&
898 !mark_compact_collector()->finalize_incremental_marking() &&
899 !mark_compact_collector()->abort_incremental_marking() &&
900 !incremental_marking()->IsStopped() &&
901 !incremental_marking()->should_hurry() && FLAG_incremental_marking) {
902 // Make progress in incremental marking.
903 const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
904 incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
905 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
906 if (!incremental_marking()->IsComplete() &&
907 !mark_compact_collector_.marking_deque_.IsEmpty() && !FLAG_gc_global) {
908 if (FLAG_trace_incremental_marking) {
909 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
911 collector = SCAVENGER;
912 collector_reason = "incremental marking delaying mark-sweep";
916 bool next_gc_likely_to_collect_more = false;
917 intptr_t committed_memory_before = 0;
919 if (collector == MARK_COMPACTOR) {
920 committed_memory_before = CommittedOldGenerationMemory();
924 tracer()->Start(collector, gc_reason, collector_reason);
925 DCHECK(AllowHeapAllocation::IsAllowed());
926 DisallowHeapAllocation no_allocation_during_gc;
927 GarbageCollectionPrologue();
930 HistogramTimerScope histogram_timer_scope(
931 (collector == SCAVENGER) ? isolate_->counters()->gc_scavenger()
932 : isolate_->counters()->gc_compactor());
933 next_gc_likely_to_collect_more =
934 PerformGarbageCollection(collector, gc_callback_flags);
937 GarbageCollectionEpilogue();
938 if (collector == MARK_COMPACTOR && FLAG_track_detached_contexts) {
939 isolate()->CheckDetachedContextsAfterGC();
942 if (collector == MARK_COMPACTOR) {
943 intptr_t committed_memory_after = CommittedOldGenerationMemory();
944 intptr_t used_memory_after = PromotedSpaceSizeOfObjects();
945 MemoryReducer::Event event;
946 event.type = MemoryReducer::kMarkCompact;
947 event.time_ms = MonotonicallyIncreasingTimeInMs();
948 // Trigger one more GC if
949 // - this GC decreased committed memory,
950 // - there is high fragmentation,
951 // - there are live detached contexts.
952 event.next_gc_likely_to_collect_more =
953 (committed_memory_before - committed_memory_after) > MB ||
954 HasHighFragmentation(used_memory_after, committed_memory_after) ||
955 (detached_contexts()->length() > 0);
956 if (deserialization_complete_) {
957 memory_reducer_.NotifyMarkCompact(event);
961 tracer()->Stop(collector);
964 if (collector == MARK_COMPACTOR &&
965 (gc_callback_flags & kGCCallbackFlagForced) != 0) {
966 isolate()->CountUsage(v8::Isolate::kForcedGC);
969 // Start incremental marking for the next cycle. The heap snapshot
970 // generator needs incremental marking to stay off after it aborted.
971 if (!mark_compact_collector()->abort_incremental_marking() &&
972 incremental_marking()->IsStopped() &&
973 incremental_marking()->ShouldActivateEvenWithoutIdleNotification()) {
974 incremental_marking()->Start(kNoGCFlags, kNoGCCallbackFlags, "GC epilogue");
977 return next_gc_likely_to_collect_more;
981 int Heap::NotifyContextDisposed(bool dependant_context) {
982 if (!dependant_context) {
983 tracer()->ResetSurvivalEvents();
984 old_generation_size_configured_ = false;
986 if (isolate()->concurrent_recompilation_enabled()) {
987 // Flush the queued recompilation tasks.
988 isolate()->optimizing_compile_dispatcher()->Flush();
991 set_retained_maps(ArrayList::cast(empty_fixed_array()));
992 tracer()->AddContextDisposalTime(base::OS::TimeCurrentMillis());
993 MemoryReducer::Event event;
994 event.type = MemoryReducer::kContextDisposed;
995 event.time_ms = MonotonicallyIncreasingTimeInMs();
996 memory_reducer_.NotifyContextDisposed(event);
997 return ++contexts_disposed_;
1001 void Heap::StartIncrementalMarking(int gc_flags,
1002 const GCCallbackFlags gc_callback_flags,
1003 const char* reason) {
1004 DCHECK(incremental_marking()->IsStopped());
1005 incremental_marking()->Start(gc_flags, gc_callback_flags, reason);
1009 void Heap::StartIdleIncrementalMarking() {
1010 gc_idle_time_handler_.ResetNoProgressCounter();
1011 StartIncrementalMarking(kReduceMemoryFootprintMask, kNoGCCallbackFlags,
1016 void Heap::MoveElements(FixedArray* array, int dst_index, int src_index,
1018 if (len == 0) return;
1020 DCHECK(array->map() != fixed_cow_array_map());
1021 Object** dst_objects = array->data_start() + dst_index;
1022 MemMove(dst_objects, array->data_start() + src_index, len * kPointerSize);
1023 if (!InNewSpace(array)) {
1024 for (int i = 0; i < len; i++) {
1025 // TODO(hpayer): check store buffer for entries
1026 if (InNewSpace(dst_objects[i])) {
1027 RecordWrite(array->address(), array->OffsetOfElementAt(dst_index + i));
1031 incremental_marking()->RecordWrites(array);
1036 // Helper class for verifying the string table.
1037 class StringTableVerifier : public ObjectVisitor {
1039 void VisitPointers(Object** start, Object** end) {
1040 // Visit all HeapObject pointers in [start, end).
1041 for (Object** p = start; p < end; p++) {
1042 if ((*p)->IsHeapObject()) {
1043 // Check that the string is actually internalized.
1044 CHECK((*p)->IsTheHole() || (*p)->IsUndefined() ||
1045 (*p)->IsInternalizedString());
1052 static void VerifyStringTable(Heap* heap) {
1053 StringTableVerifier verifier;
1054 heap->string_table()->IterateElements(&verifier);
1056 #endif // VERIFY_HEAP
1059 bool Heap::ReserveSpace(Reservation* reservations) {
1060 bool gc_performed = true;
1062 static const int kThreshold = 20;
1063 while (gc_performed && counter++ < kThreshold) {
1064 gc_performed = false;
1065 for (int space = NEW_SPACE; space < Serializer::kNumberOfSpaces; space++) {
1066 Reservation* reservation = &reservations[space];
1067 DCHECK_LE(1, reservation->length());
1068 if (reservation->at(0).size == 0) continue;
1069 bool perform_gc = false;
1070 if (space == LO_SPACE) {
1071 DCHECK_EQ(1, reservation->length());
1072 perform_gc = !CanExpandOldGeneration(reservation->at(0).size);
1074 for (auto& chunk : *reservation) {
1075 AllocationResult allocation;
1076 int size = chunk.size;
1077 DCHECK_LE(size, MemoryAllocator::PageAreaSize(
1078 static_cast<AllocationSpace>(space)));
1079 if (space == NEW_SPACE) {
1080 allocation = new_space()->AllocateRawUnaligned(size);
1082 allocation = paged_space(space)->AllocateRawUnaligned(size);
1084 HeapObject* free_space;
1085 if (allocation.To(&free_space)) {
1086 // Mark with a free list node, in case we have a GC before
1088 Address free_space_address = free_space->address();
1089 CreateFillerObjectAt(free_space_address, size);
1090 DCHECK(space < Serializer::kNumberOfPreallocatedSpaces);
1091 chunk.start = free_space_address;
1092 chunk.end = free_space_address + size;
1100 if (space == NEW_SPACE) {
1101 CollectGarbage(NEW_SPACE, "failed to reserve space in the new space");
1105 kReduceMemoryFootprintMask | kAbortIncrementalMarkingMask,
1106 "failed to reserve space in paged or large "
1107 "object space, trying to reduce memory footprint");
1110 kAbortIncrementalMarkingMask,
1111 "failed to reserve space in paged or large object space");
1114 gc_performed = true;
1115 break; // Abort for-loop over spaces and retry.
1120 return !gc_performed;
1124 void Heap::EnsureFromSpaceIsCommitted() {
1125 if (new_space_.CommitFromSpaceIfNeeded()) return;
1127 // Committing memory to from space failed.
1128 // Memory is exhausted and we will die.
1129 V8::FatalProcessOutOfMemory("Committing semi space failed.");
1133 void Heap::ClearNormalizedMapCaches() {
1134 if (isolate_->bootstrapper()->IsActive() &&
1135 !incremental_marking()->IsMarking()) {
1139 Object* context = native_contexts_list();
1140 while (!context->IsUndefined()) {
1141 // GC can happen when the context is not fully initialized,
1142 // so the cache can be undefined.
1144 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
1145 if (!cache->IsUndefined()) {
1146 NormalizedMapCache::cast(cache)->Clear();
1148 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
1153 void Heap::UpdateSurvivalStatistics(int start_new_space_size) {
1154 if (start_new_space_size == 0) return;
1156 promotion_ratio_ = (static_cast<double>(promoted_objects_size_) /
1157 static_cast<double>(start_new_space_size) * 100);
1159 if (previous_semi_space_copied_object_size_ > 0) {
1161 (static_cast<double>(promoted_objects_size_) /
1162 static_cast<double>(previous_semi_space_copied_object_size_) * 100);
1164 promotion_rate_ = 0;
1167 semi_space_copied_rate_ =
1168 (static_cast<double>(semi_space_copied_object_size_) /
1169 static_cast<double>(start_new_space_size) * 100);
1171 double survival_rate = promotion_ratio_ + semi_space_copied_rate_;
1172 tracer()->AddSurvivalRatio(survival_rate);
1173 if (survival_rate > kYoungSurvivalRateHighThreshold) {
1174 high_survival_rate_period_length_++;
1176 high_survival_rate_period_length_ = 0;
1180 bool Heap::PerformGarbageCollection(
1181 GarbageCollector collector, const v8::GCCallbackFlags gc_callback_flags) {
1182 int freed_global_handles = 0;
1184 if (collector != SCAVENGER) {
1185 PROFILE(isolate_, CodeMovingGCEvent());
1189 if (FLAG_verify_heap) {
1190 VerifyStringTable(this);
1195 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
1198 GCCallbacksScope scope(this);
1199 if (scope.CheckReenter()) {
1200 AllowHeapAllocation allow_allocation;
1201 GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1202 VMState<EXTERNAL> state(isolate_);
1203 HandleScope handle_scope(isolate_);
1204 CallGCPrologueCallbacks(gc_type, kNoGCCallbackFlags);
1208 EnsureFromSpaceIsCommitted();
1210 int start_new_space_size = Heap::new_space()->SizeAsInt();
1212 if (IsHighSurvivalRate()) {
1213 // We speed up the incremental marker if it is running so that it
1214 // does not fall behind the rate of promotion, which would cause a
1215 // constantly growing old space.
1216 incremental_marking()->NotifyOfHighPromotionRate();
1219 if (collector == MARK_COMPACTOR) {
1220 UpdateOldGenerationAllocationCounter();
1221 // Perform mark-sweep with optional compaction.
1223 sweep_generation_++;
1224 old_gen_exhausted_ = false;
1225 old_generation_size_configured_ = true;
1226 // This should be updated before PostGarbageCollectionProcessing, which can
1227 // cause another GC. Take into account the objects promoted during GC.
1228 old_generation_allocation_counter_ +=
1229 static_cast<size_t>(promoted_objects_size_);
1230 old_generation_size_at_last_gc_ = PromotedSpaceSizeOfObjects();
1235 ProcessPretenuringFeedback();
1236 UpdateSurvivalStatistics(start_new_space_size);
1237 ConfigureInitialOldGenerationSize();
1239 isolate_->counters()->objs_since_last_young()->Set(0);
1241 if (collector != SCAVENGER) {
1242 // Callbacks that fire after this point might trigger nested GCs and
1243 // restart incremental marking, the assertion can't be moved down.
1244 DCHECK(incremental_marking()->IsStopped());
1246 // We finished a marking cycle. We can uncommit the marking deque until
1247 // we start marking again.
1248 mark_compact_collector_.marking_deque()->Uninitialize();
1249 mark_compact_collector_.EnsureMarkingDequeIsCommitted(
1250 MarkCompactCollector::kMinMarkingDequeSize);
1253 gc_post_processing_depth_++;
1255 AllowHeapAllocation allow_allocation;
1256 GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1257 freed_global_handles =
1258 isolate_->global_handles()->PostGarbageCollectionProcessing(
1259 collector, gc_callback_flags);
1261 gc_post_processing_depth_--;
1263 isolate_->eternal_handles()->PostGarbageCollectionProcessing(this);
1265 // Update relocatables.
1266 Relocatable::PostGarbageCollectionProcessing(isolate_);
1268 double gc_speed = tracer()->CombinedMarkCompactSpeedInBytesPerMillisecond();
1269 double mutator_speed = static_cast<double>(
1271 ->CurrentOldGenerationAllocationThroughputInBytesPerMillisecond());
1272 intptr_t old_gen_size = PromotedSpaceSizeOfObjects();
1273 if (collector == MARK_COMPACTOR) {
1274 // Register the amount of external allocated memory.
1275 amount_of_external_allocated_memory_at_last_global_gc_ =
1276 amount_of_external_allocated_memory_;
1277 SetOldGenerationAllocationLimit(old_gen_size, gc_speed, mutator_speed);
1278 } else if (HasLowYoungGenerationAllocationRate() &&
1279 old_generation_size_configured_) {
1280 DampenOldGenerationAllocationLimit(old_gen_size, gc_speed, mutator_speed);
1284 GCCallbacksScope scope(this);
1285 if (scope.CheckReenter()) {
1286 AllowHeapAllocation allow_allocation;
1287 GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1288 VMState<EXTERNAL> state(isolate_);
1289 HandleScope handle_scope(isolate_);
1290 CallGCEpilogueCallbacks(gc_type, gc_callback_flags);
1295 if (FLAG_verify_heap) {
1296 VerifyStringTable(this);
1300 return freed_global_handles > 0;
1304 void Heap::CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags) {
1305 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
1306 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
1307 if (!gc_prologue_callbacks_[i].pass_isolate_) {
1308 v8::GCPrologueCallback callback =
1309 reinterpret_cast<v8::GCPrologueCallback>(
1310 gc_prologue_callbacks_[i].callback);
1311 callback(gc_type, flags);
1313 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate());
1314 gc_prologue_callbacks_[i].callback(isolate, gc_type, flags);
1321 void Heap::CallGCEpilogueCallbacks(GCType gc_type,
1322 GCCallbackFlags gc_callback_flags) {
1323 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
1324 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
1325 if (!gc_epilogue_callbacks_[i].pass_isolate_) {
1326 v8::GCPrologueCallback callback =
1327 reinterpret_cast<v8::GCPrologueCallback>(
1328 gc_epilogue_callbacks_[i].callback);
1329 callback(gc_type, gc_callback_flags);
1331 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate());
1332 gc_epilogue_callbacks_[i].callback(isolate, gc_type, gc_callback_flags);
1339 void Heap::MarkCompact() {
1340 gc_state_ = MARK_COMPACT;
1341 LOG(isolate_, ResourceEvent("markcompact", "begin"));
1343 uint64_t size_of_objects_before_gc = SizeOfObjects();
1345 mark_compact_collector_.Prepare();
1349 MarkCompactPrologue();
1351 mark_compact_collector_.CollectGarbage();
1353 LOG(isolate_, ResourceEvent("markcompact", "end"));
1355 MarkCompactEpilogue();
1357 if (FLAG_allocation_site_pretenuring) {
1358 EvaluateOldSpaceLocalPretenuring(size_of_objects_before_gc);
1363 void Heap::MarkCompactEpilogue() {
1364 gc_state_ = NOT_IN_GC;
1366 isolate_->counters()->objs_since_last_full()->Set(0);
1368 incremental_marking()->Epilogue();
1370 PreprocessStackTraces();
1374 void Heap::MarkCompactPrologue() {
1375 // At any old GC clear the keyed lookup cache to enable collection of unused
1377 isolate_->keyed_lookup_cache()->Clear();
1378 isolate_->context_slot_cache()->Clear();
1379 isolate_->descriptor_lookup_cache()->Clear();
1380 RegExpResultsCache::Clear(string_split_cache());
1381 RegExpResultsCache::Clear(regexp_multiple_cache());
1383 isolate_->compilation_cache()->MarkCompactPrologue();
1385 CompletelyClearInstanceofCache();
1387 FlushNumberStringCache();
1388 if (FLAG_cleanup_code_caches_at_gc) {
1389 polymorphic_code_cache()->set_cache(undefined_value());
1392 ClearNormalizedMapCaches();
1396 // Helper class for copying HeapObjects
1397 class ScavengeVisitor : public ObjectVisitor {
1399 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
1401 void VisitPointer(Object** p) { ScavengePointer(p); }
1403 void VisitPointers(Object** start, Object** end) {
1404 // Copy all HeapObject pointers in [start, end)
1405 for (Object** p = start; p < end; p++) ScavengePointer(p);
1409 void ScavengePointer(Object** p) {
1410 Object* object = *p;
1411 if (!heap_->InNewSpace(object)) return;
1412 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1413 reinterpret_cast<HeapObject*>(object));
1421 // Visitor class to verify pointers in code or data space do not point into
1423 class VerifyNonPointerSpacePointersVisitor : public ObjectVisitor {
1425 explicit VerifyNonPointerSpacePointersVisitor(Heap* heap) : heap_(heap) {}
1426 void VisitPointers(Object** start, Object** end) {
1427 for (Object** current = start; current < end; current++) {
1428 if ((*current)->IsHeapObject()) {
1429 CHECK(!heap_->InNewSpace(HeapObject::cast(*current)));
1439 static void VerifyNonPointerSpacePointers(Heap* heap) {
1440 // Verify that there are no pointers to new space in spaces where we
1441 // do not expect them.
1442 VerifyNonPointerSpacePointersVisitor v(heap);
1443 HeapObjectIterator code_it(heap->code_space());
1444 for (HeapObject* object = code_it.Next(); object != NULL;
1445 object = code_it.Next())
1446 object->Iterate(&v);
1448 #endif // VERIFY_HEAP
1451 void Heap::CheckNewSpaceExpansionCriteria() {
1452 if (FLAG_experimental_new_space_growth_heuristic) {
1453 if (new_space_.TotalCapacity() < new_space_.MaximumCapacity() &&
1454 survived_last_scavenge_ * 100 / new_space_.TotalCapacity() >= 10) {
1455 // Grow the size of new space if there is room to grow, and more than 10%
1456 // have survived the last scavenge.
1458 survived_since_last_expansion_ = 0;
1460 } else if (new_space_.TotalCapacity() < new_space_.MaximumCapacity() &&
1461 survived_since_last_expansion_ > new_space_.TotalCapacity()) {
1462 // Grow the size of new space if there is room to grow, and enough data
1463 // has survived scavenge since the last expansion.
1465 survived_since_last_expansion_ = 0;
1470 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1471 return heap->InNewSpace(*p) &&
1472 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1476 void Heap::ScavengeStoreBufferCallback(Heap* heap, MemoryChunk* page,
1477 StoreBufferEvent event) {
1478 heap->store_buffer_rebuilder_.Callback(page, event);
1482 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1483 if (event == kStoreBufferStartScanningPagesEvent) {
1484 start_of_current_page_ = NULL;
1485 current_page_ = NULL;
1486 } else if (event == kStoreBufferScanningPageEvent) {
1487 if (current_page_ != NULL) {
1488 // If this page already overflowed the store buffer during this iteration.
1489 if (current_page_->scan_on_scavenge()) {
1490 // Then we should wipe out the entries that have been added for it.
1491 store_buffer_->SetTop(start_of_current_page_);
1492 } else if (store_buffer_->Top() - start_of_current_page_ >=
1493 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1494 // Did we find too many pointers in the previous page? The heuristic is
1495 // that no page can take more then 1/5 the remaining slots in the store
1497 current_page_->set_scan_on_scavenge(true);
1498 store_buffer_->SetTop(start_of_current_page_);
1500 // In this case the page we scanned took a reasonable number of slots in
1501 // the store buffer. It has now been rehabilitated and is no longer
1502 // marked scan_on_scavenge.
1503 DCHECK(!current_page_->scan_on_scavenge());
1506 start_of_current_page_ = store_buffer_->Top();
1507 current_page_ = page;
1508 } else if (event == kStoreBufferFullEvent) {
1509 // The current page overflowed the store buffer again. Wipe out its entries
1510 // in the store buffer and mark it scan-on-scavenge again. This may happen
1511 // several times while scanning.
1512 if (current_page_ == NULL) {
1513 // Store Buffer overflowed while scanning promoted objects. These are not
1514 // in any particular page, though they are likely to be clustered by the
1515 // allocation routines.
1516 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize / 2);
1518 // Store Buffer overflowed while scanning a particular old space page for
1519 // pointers to new space.
1520 DCHECK(current_page_ == page);
1521 DCHECK(page != NULL);
1522 current_page_->set_scan_on_scavenge(true);
1523 DCHECK(start_of_current_page_ != store_buffer_->Top());
1524 store_buffer_->SetTop(start_of_current_page_);
1532 void PromotionQueue::Initialize() {
1533 // The last to-space page may be used for promotion queue. On promotion
1534 // conflict, we use the emergency stack.
1535 DCHECK((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize) ==
1538 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1539 limit_ = reinterpret_cast<intptr_t*>(
1540 Page::FromAllocationTop(reinterpret_cast<Address>(rear_))->area_start());
1541 emergency_stack_ = NULL;
1545 void PromotionQueue::RelocateQueueHead() {
1546 DCHECK(emergency_stack_ == NULL);
1548 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1549 intptr_t* head_start = rear_;
1550 intptr_t* head_end = Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1553 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1555 emergency_stack_ = new List<Entry>(2 * entries_count);
1557 while (head_start != head_end) {
1558 int size = static_cast<int>(*(head_start++));
1559 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1560 // New space allocation in SemiSpaceCopyObject marked the region
1561 // overlapping with promotion queue as uninitialized.
1562 MSAN_MEMORY_IS_INITIALIZED(&size, sizeof(size));
1563 MSAN_MEMORY_IS_INITIALIZED(&obj, sizeof(obj));
1564 emergency_stack_->Add(Entry(obj, size));
1570 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1572 explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) {}
1574 virtual Object* RetainAs(Object* object) {
1575 if (!heap_->InFromSpace(object)) {
1579 MapWord map_word = HeapObject::cast(object)->map_word();
1580 if (map_word.IsForwardingAddress()) {
1581 return map_word.ToForwardingAddress();
1591 void Heap::Scavenge() {
1592 GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_SCAVENGE);
1593 RelocationLock relocation_lock(this);
1594 // There are soft limits in the allocation code, designed to trigger a mark
1595 // sweep collection by failing allocations. There is no sense in trying to
1596 // trigger one during scavenge: scavenges allocation should always succeed.
1597 AlwaysAllocateScope scope(isolate());
1600 if (FLAG_verify_heap) VerifyNonPointerSpacePointers(this);
1603 gc_state_ = SCAVENGE;
1605 // Implements Cheney's copying algorithm
1606 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1608 // Clear descriptor cache.
1609 isolate_->descriptor_lookup_cache()->Clear();
1611 // Used for updating survived_since_last_expansion_ at function end.
1612 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1614 SelectScavengingVisitorsTable();
1616 PrepareArrayBufferDiscoveryInNewSpace();
1618 // Flip the semispaces. After flipping, to space is empty, from space has
1621 new_space_.ResetAllocationInfo();
1623 // We need to sweep newly copied objects which can be either in the
1624 // to space or promoted to the old generation. For to-space
1625 // objects, we treat the bottom of the to space as a queue. Newly
1626 // copied and unswept objects lie between a 'front' mark and the
1627 // allocation pointer.
1629 // Promoted objects can go into various old-generation spaces, and
1630 // can be allocated internally in the spaces (from the free list).
1631 // We treat the top of the to space as a queue of addresses of
1632 // promoted objects. The addresses of newly promoted and unswept
1633 // objects lie between a 'front' mark and a 'rear' mark that is
1634 // updated as a side effect of promoting an object.
1636 // There is guaranteed to be enough room at the top of the to space
1637 // for the addresses of promoted objects: every object promoted
1638 // frees up its size in bytes from the top of the new space, and
1639 // objects are at least one pointer in size.
1640 Address new_space_front = new_space_.ToSpaceStart();
1641 promotion_queue_.Initialize();
1643 ScavengeVisitor scavenge_visitor(this);
1646 GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_ROOTS);
1647 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1651 // Copy objects reachable from the old generation.
1652 GCTracer::Scope gc_scope(tracer(),
1653 GCTracer::Scope::SCAVENGER_OLD_TO_NEW_POINTERS);
1654 StoreBufferRebuildScope scope(this, store_buffer(),
1655 &ScavengeStoreBufferCallback);
1656 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1660 GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_WEAK);
1661 // Copy objects reachable from the encountered weak collections list.
1662 scavenge_visitor.VisitPointer(&encountered_weak_collections_);
1663 // Copy objects reachable from the encountered weak cells.
1664 scavenge_visitor.VisitPointer(&encountered_weak_cells_);
1668 // Copy objects reachable from the code flushing candidates list.
1669 GCTracer::Scope gc_scope(tracer(),
1670 GCTracer::Scope::SCAVENGER_CODE_FLUSH_CANDIDATES);
1671 MarkCompactCollector* collector = mark_compact_collector();
1672 if (collector->is_code_flushing_enabled()) {
1673 collector->code_flusher()->IteratePointersToFromSpace(&scavenge_visitor);
1678 GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_SEMISPACE);
1679 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1683 GCTracer::Scope gc_scope(tracer(),
1684 GCTracer::Scope::SCAVENGER_OBJECT_GROUPS);
1685 while (isolate()->global_handles()->IterateObjectGroups(
1686 &scavenge_visitor, &IsUnscavengedHeapObject)) {
1687 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1689 isolate()->global_handles()->RemoveObjectGroups();
1690 isolate()->global_handles()->RemoveImplicitRefGroups();
1693 isolate()->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1694 &IsUnscavengedHeapObject);
1696 isolate()->global_handles()->IterateNewSpaceWeakIndependentRoots(
1698 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1700 UpdateNewSpaceReferencesInExternalStringTable(
1701 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1703 promotion_queue_.Destroy();
1705 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1707 ScavengeWeakObjectRetainer weak_object_retainer(this);
1708 ProcessYoungWeakReferences(&weak_object_retainer);
1710 DCHECK(new_space_front == new_space_.top());
1713 new_space_.set_age_mark(new_space_.top());
1715 new_space_.LowerInlineAllocationLimit(
1716 new_space_.inline_allocation_limit_step());
1718 FreeDeadArrayBuffers(true);
1720 // Update how much has survived scavenge.
1721 IncrementYoungSurvivorsCounter(static_cast<int>(
1722 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1724 LOG(isolate_, ResourceEvent("scavenge", "end"));
1726 gc_state_ = NOT_IN_GC;
1730 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1732 MapWord first_word = HeapObject::cast(*p)->map_word();
1734 if (!first_word.IsForwardingAddress()) {
1735 // Unreachable external string can be finalized.
1736 heap->FinalizeExternalString(String::cast(*p));
1740 // String is still reachable.
1741 return String::cast(first_word.ToForwardingAddress());
1745 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1746 ExternalStringTableUpdaterCallback updater_func) {
1748 if (FLAG_verify_heap) {
1749 external_string_table_.Verify();
1753 if (external_string_table_.new_space_strings_.is_empty()) return;
1755 Object** start = &external_string_table_.new_space_strings_[0];
1756 Object** end = start + external_string_table_.new_space_strings_.length();
1757 Object** last = start;
1759 for (Object** p = start; p < end; ++p) {
1760 DCHECK(InFromSpace(*p));
1761 String* target = updater_func(this, p);
1763 if (target == NULL) continue;
1765 DCHECK(target->IsExternalString());
1767 if (InNewSpace(target)) {
1768 // String is still in new space. Update the table entry.
1772 // String got promoted. Move it to the old string list.
1773 external_string_table_.AddOldString(target);
1777 DCHECK(last <= end);
1778 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1782 void Heap::UpdateReferencesInExternalStringTable(
1783 ExternalStringTableUpdaterCallback updater_func) {
1784 // Update old space string references.
1785 if (external_string_table_.old_space_strings_.length() > 0) {
1786 Object** start = &external_string_table_.old_space_strings_[0];
1787 Object** end = start + external_string_table_.old_space_strings_.length();
1788 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1791 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1795 void Heap::ProcessAllWeakReferences(WeakObjectRetainer* retainer) {
1796 ProcessNativeContexts(retainer);
1797 ProcessAllocationSites(retainer);
1801 void Heap::ProcessYoungWeakReferences(WeakObjectRetainer* retainer) {
1802 ProcessNativeContexts(retainer);
1806 void Heap::ProcessNativeContexts(WeakObjectRetainer* retainer) {
1807 Object* head = VisitWeakList<Context>(this, native_contexts_list(), retainer);
1808 // Update the head of the list of contexts.
1809 set_native_contexts_list(head);
1813 void Heap::RegisterNewArrayBufferHelper(std::map<void*, size_t>& live_buffers,
1814 void* data, size_t length) {
1815 live_buffers[data] = length;
1819 void Heap::UnregisterArrayBufferHelper(
1820 std::map<void*, size_t>& live_buffers,
1821 std::map<void*, size_t>& not_yet_discovered_buffers, void* data) {
1822 DCHECK(live_buffers.count(data) > 0);
1823 live_buffers.erase(data);
1824 not_yet_discovered_buffers.erase(data);
1828 void Heap::RegisterLiveArrayBufferHelper(
1829 std::map<void*, size_t>& not_yet_discovered_buffers, void* data) {
1830 not_yet_discovered_buffers.erase(data);
1834 size_t Heap::FreeDeadArrayBuffersHelper(
1835 Isolate* isolate, std::map<void*, size_t>& live_buffers,
1836 std::map<void*, size_t>& not_yet_discovered_buffers) {
1837 size_t freed_memory = 0;
1838 for (auto buffer = not_yet_discovered_buffers.begin();
1839 buffer != not_yet_discovered_buffers.end(); ++buffer) {
1840 isolate->array_buffer_allocator()->Free(buffer->first, buffer->second);
1841 freed_memory += buffer->second;
1842 live_buffers.erase(buffer->first);
1844 not_yet_discovered_buffers = live_buffers;
1845 return freed_memory;
1849 void Heap::TearDownArrayBuffersHelper(
1850 Isolate* isolate, std::map<void*, size_t>& live_buffers,
1851 std::map<void*, size_t>& not_yet_discovered_buffers) {
1852 for (auto buffer = live_buffers.begin(); buffer != live_buffers.end();
1854 isolate->array_buffer_allocator()->Free(buffer->first, buffer->second);
1856 live_buffers.clear();
1857 not_yet_discovered_buffers.clear();
1861 void Heap::RegisterNewArrayBuffer(bool in_new_space, void* data,
1864 RegisterNewArrayBufferHelper(live_array_buffers_, data, length);
1866 RegisterNewArrayBufferHelper(live_array_buffers_for_scavenge_, data,
1869 reinterpret_cast<v8::Isolate*>(isolate_)
1870 ->AdjustAmountOfExternalAllocatedMemory(length);
1874 void Heap::UnregisterArrayBuffer(bool in_new_space, void* data) {
1876 UnregisterArrayBufferHelper(live_array_buffers_,
1877 not_yet_discovered_array_buffers_, data);
1879 UnregisterArrayBufferHelper(live_array_buffers_for_scavenge_,
1880 not_yet_discovered_array_buffers_for_scavenge_,
1886 void Heap::RegisterLiveArrayBuffer(bool from_scavenge, void* data) {
1887 // ArrayBuffer might be in the middle of being constructed.
1888 if (data == undefined_value()) return;
1889 RegisterLiveArrayBufferHelper(
1890 from_scavenge ? not_yet_discovered_array_buffers_for_scavenge_
1891 : not_yet_discovered_array_buffers_,
1896 void Heap::FreeDeadArrayBuffers(bool from_scavenge) {
1897 if (from_scavenge) {
1898 for (auto& buffer : not_yet_discovered_array_buffers_for_scavenge_) {
1899 not_yet_discovered_array_buffers_.erase(buffer.first);
1900 live_array_buffers_.erase(buffer.first);
1903 for (auto& buffer : not_yet_discovered_array_buffers_) {
1904 // Scavenge can't happend during evacuation, so we only need to update
1905 // live_array_buffers_for_scavenge_.
1906 // not_yet_discovered_array_buffers_for_scanvenge_ will be reset before
1907 // the next scavenge run in PrepareArrayBufferDiscoveryInNewSpace.
1908 live_array_buffers_for_scavenge_.erase(buffer.first);
1911 size_t freed_memory = FreeDeadArrayBuffersHelper(
1913 from_scavenge ? live_array_buffers_for_scavenge_ : live_array_buffers_,
1914 from_scavenge ? not_yet_discovered_array_buffers_for_scavenge_
1915 : not_yet_discovered_array_buffers_);
1917 reinterpret_cast<v8::Isolate*>(isolate_)
1918 ->AdjustAmountOfExternalAllocatedMemory(
1919 -static_cast<int64_t>(freed_memory));
1924 void Heap::TearDownArrayBuffers() {
1925 TearDownArrayBuffersHelper(isolate_, live_array_buffers_,
1926 not_yet_discovered_array_buffers_);
1930 void Heap::PrepareArrayBufferDiscoveryInNewSpace() {
1931 not_yet_discovered_array_buffers_for_scavenge_ =
1932 live_array_buffers_for_scavenge_;
1936 void Heap::PromoteArrayBuffer(Object* obj) {
1937 JSArrayBuffer* buffer = JSArrayBuffer::cast(obj);
1938 if (buffer->is_external()) return;
1939 void* data = buffer->backing_store();
1941 // ArrayBuffer might be in the middle of being constructed.
1942 if (data == undefined_value()) return;
1943 DCHECK(live_array_buffers_for_scavenge_.count(data) > 0);
1944 DCHECK(live_array_buffers_.count(data) > 0);
1945 live_array_buffers_for_scavenge_.erase(data);
1946 not_yet_discovered_array_buffers_for_scavenge_.erase(data);
1950 void Heap::ProcessAllocationSites(WeakObjectRetainer* retainer) {
1951 Object* allocation_site_obj =
1952 VisitWeakList<AllocationSite>(this, allocation_sites_list(), retainer);
1953 set_allocation_sites_list(allocation_site_obj);
1957 void Heap::ResetAllAllocationSitesDependentCode(PretenureFlag flag) {
1958 DisallowHeapAllocation no_allocation_scope;
1959 Object* cur = allocation_sites_list();
1960 bool marked = false;
1961 while (cur->IsAllocationSite()) {
1962 AllocationSite* casted = AllocationSite::cast(cur);
1963 if (casted->GetPretenureMode() == flag) {
1964 casted->ResetPretenureDecision();
1965 casted->set_deopt_dependent_code(true);
1968 cur = casted->weak_next();
1970 if (marked) isolate_->stack_guard()->RequestDeoptMarkedAllocationSites();
1974 void Heap::EvaluateOldSpaceLocalPretenuring(
1975 uint64_t size_of_objects_before_gc) {
1976 uint64_t size_of_objects_after_gc = SizeOfObjects();
1977 double old_generation_survival_rate =
1978 (static_cast<double>(size_of_objects_after_gc) * 100) /
1979 static_cast<double>(size_of_objects_before_gc);
1981 if (old_generation_survival_rate < kOldSurvivalRateLowThreshold) {
1982 // Too many objects died in the old generation, pretenuring of wrong
1983 // allocation sites may be the cause for that. We have to deopt all
1984 // dependent code registered in the allocation sites to re-evaluate
1985 // our pretenuring decisions.
1986 ResetAllAllocationSitesDependentCode(TENURED);
1987 if (FLAG_trace_pretenuring) {
1989 "Deopt all allocation sites dependent code due to low survival "
1990 "rate in the old generation %f\n",
1991 old_generation_survival_rate);
1997 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1998 DisallowHeapAllocation no_allocation;
1999 // All external strings are listed in the external string table.
2001 class ExternalStringTableVisitorAdapter : public ObjectVisitor {
2003 explicit ExternalStringTableVisitorAdapter(
2004 v8::ExternalResourceVisitor* visitor)
2005 : visitor_(visitor) {}
2006 virtual void VisitPointers(Object** start, Object** end) {
2007 for (Object** p = start; p < end; p++) {
2008 DCHECK((*p)->IsExternalString());
2009 visitor_->VisitExternalString(
2010 Utils::ToLocal(Handle<String>(String::cast(*p))));
2015 v8::ExternalResourceVisitor* visitor_;
2016 } external_string_table_visitor(visitor);
2018 external_string_table_.Iterate(&external_string_table_visitor);
2022 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
2024 static inline void VisitPointer(Heap* heap, Object** p) {
2025 Object* object = *p;
2026 if (!heap->InNewSpace(object)) return;
2027 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
2028 reinterpret_cast<HeapObject*>(object));
2033 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
2034 Address new_space_front) {
2036 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
2037 // The addresses new_space_front and new_space_.top() define a
2038 // queue of unprocessed copied objects. Process them until the
2040 while (new_space_front != new_space_.top()) {
2041 if (!NewSpacePage::IsAtEnd(new_space_front)) {
2042 HeapObject* object = HeapObject::FromAddress(new_space_front);
2044 NewSpaceScavenger::IterateBody(object->map(), object);
2047 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
2051 // Promote and process all the to-be-promoted objects.
2053 StoreBufferRebuildScope scope(this, store_buffer(),
2054 &ScavengeStoreBufferCallback);
2055 while (!promotion_queue()->is_empty()) {
2058 promotion_queue()->remove(&target, &size);
2060 // Promoted object might be already partially visited
2061 // during old space pointer iteration. Thus we search specifically
2062 // for pointers to from semispace instead of looking for pointers
2064 DCHECK(!target->IsMap());
2065 Address obj_address = target->address();
2067 // We are not collecting slots on new space objects during mutation
2068 // thus we have to scan for pointers to evacuation candidates when we
2069 // promote objects. But we should not record any slots in non-black
2070 // objects. Grey object's slots would be rescanned.
2071 // White object might not survive until the end of collection
2072 // it would be a violation of the invariant to record it's slots.
2073 bool record_slots = false;
2074 if (incremental_marking()->IsCompacting()) {
2075 MarkBit mark_bit = Marking::MarkBitFrom(target);
2076 record_slots = Marking::IsBlack(mark_bit);
2078 #if V8_DOUBLE_FIELDS_UNBOXING
2079 LayoutDescriptorHelper helper(target->map());
2080 bool has_only_tagged_fields = helper.all_fields_tagged();
2082 if (!has_only_tagged_fields) {
2083 for (int offset = 0; offset < size;) {
2084 int end_of_region_offset;
2085 if (helper.IsTagged(offset, size, &end_of_region_offset)) {
2086 IterateAndMarkPointersToFromSpace(
2087 target, obj_address + offset,
2088 obj_address + end_of_region_offset, record_slots,
2091 offset = end_of_region_offset;
2095 IterateAndMarkPointersToFromSpace(target, obj_address,
2096 obj_address + size, record_slots,
2098 #if V8_DOUBLE_FIELDS_UNBOXING
2104 // Take another spin if there are now unswept objects in new space
2105 // (there are currently no more unswept promoted objects).
2106 } while (new_space_front != new_space_.top());
2108 return new_space_front;
2112 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) ==
2114 STATIC_ASSERT((FixedTypedArrayBase::kDataOffset & kDoubleAlignmentMask) ==
2116 #ifdef V8_HOST_ARCH_32_BIT
2117 STATIC_ASSERT((HeapNumber::kValueOffset & kDoubleAlignmentMask) !=
2122 int Heap::GetMaximumFillToAlign(AllocationAlignment alignment) {
2123 switch (alignment) {
2126 case kDoubleAligned:
2127 case kDoubleUnaligned:
2128 return kDoubleSize - kPointerSize;
2129 case kSimd128Unaligned:
2130 return kSimd128Size - kPointerSize;
2138 int Heap::GetFillToAlign(Address address, AllocationAlignment alignment) {
2139 intptr_t offset = OffsetFrom(address);
2140 if (alignment == kDoubleAligned && (offset & kDoubleAlignmentMask) != 0)
2141 return kPointerSize;
2142 if (alignment == kDoubleUnaligned && (offset & kDoubleAlignmentMask) == 0)
2143 return kDoubleSize - kPointerSize; // No fill if double is always aligned.
2144 if (alignment == kSimd128Unaligned) {
2145 return (kSimd128Size - (static_cast<int>(offset) + kPointerSize)) &
2146 kSimd128AlignmentMask;
2152 HeapObject* Heap::PrecedeWithFiller(HeapObject* object, int filler_size) {
2153 CreateFillerObjectAt(object->address(), filler_size);
2154 return HeapObject::FromAddress(object->address() + filler_size);
2158 HeapObject* Heap::AlignWithFiller(HeapObject* object, int object_size,
2159 int allocation_size,
2160 AllocationAlignment alignment) {
2161 int filler_size = allocation_size - object_size;
2162 DCHECK(filler_size > 0);
2163 int pre_filler = GetFillToAlign(object->address(), alignment);
2165 object = PrecedeWithFiller(object, pre_filler);
2166 filler_size -= pre_filler;
2169 CreateFillerObjectAt(object->address() + object_size, filler_size);
2174 HeapObject* Heap::DoubleAlignForDeserialization(HeapObject* object, int size) {
2175 return AlignWithFiller(object, size - kPointerSize, size, kDoubleAligned);
2179 enum LoggingAndProfiling {
2180 LOGGING_AND_PROFILING_ENABLED,
2181 LOGGING_AND_PROFILING_DISABLED
2185 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
2188 template <MarksHandling marks_handling,
2189 LoggingAndProfiling logging_and_profiling_mode>
2190 class ScavengingVisitor : public StaticVisitorBase {
2192 static void Initialize() {
2193 table_.Register(kVisitSeqOneByteString, &EvacuateSeqOneByteString);
2194 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
2195 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
2196 table_.Register(kVisitByteArray, &EvacuateByteArray);
2197 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
2198 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
2199 table_.Register(kVisitFixedTypedArray, &EvacuateFixedTypedArray);
2200 table_.Register(kVisitFixedFloat64Array, &EvacuateFixedFloat64Array);
2201 table_.Register(kVisitJSArrayBuffer, &EvacuateJSArrayBuffer);
2204 kVisitNativeContext,
2205 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2210 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2211 ConsString::kSize>);
2215 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2216 SlicedString::kSize>);
2220 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2224 kVisitSharedFunctionInfo,
2225 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2226 SharedFunctionInfo::kSize>);
2228 table_.Register(kVisitJSWeakCollection,
2229 &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2231 table_.Register(kVisitJSTypedArray,
2232 &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2234 table_.Register(kVisitJSDataView,
2235 &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2237 table_.Register(kVisitJSRegExp,
2238 &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2240 if (marks_handling == IGNORE_MARKS) {
2243 &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2244 JSFunction::kSize>);
2246 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
2249 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
2250 kVisitDataObject, kVisitDataObjectGeneric>();
2252 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
2253 kVisitJSObject, kVisitJSObjectGeneric>();
2255 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
2256 kVisitStruct, kVisitStructGeneric>();
2259 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
2264 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
2266 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
2267 bool should_record = false;
2269 should_record = FLAG_heap_stats;
2271 should_record = should_record || FLAG_log_gc;
2272 if (should_record) {
2273 if (heap->new_space()->Contains(obj)) {
2274 heap->new_space()->RecordAllocation(obj);
2276 heap->new_space()->RecordPromotion(obj);
2281 // Helper function used by CopyObject to copy a source object to an
2282 // allocated target object and update the forwarding pointer in the source
2283 // object. Returns the target object.
2284 INLINE(static void MigrateObject(Heap* heap, HeapObject* source,
2285 HeapObject* target, int size)) {
2286 // If we migrate into to-space, then the to-space top pointer should be
2287 // right after the target object. Incorporate double alignment
2289 DCHECK(!heap->InToSpace(target) ||
2290 target->address() + size == heap->new_space()->top() ||
2291 target->address() + size + kPointerSize == heap->new_space()->top());
2293 // Make sure that we do not overwrite the promotion queue which is at
2294 // the end of to-space.
2295 DCHECK(!heap->InToSpace(target) ||
2296 heap->promotion_queue()->IsBelowPromotionQueue(
2297 heap->new_space()->top()));
2299 // Copy the content of source to target.
2300 heap->CopyBlock(target->address(), source->address(), size);
2302 // Set the forwarding address.
2303 source->set_map_word(MapWord::FromForwardingAddress(target));
2305 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
2306 // Update NewSpace stats if necessary.
2307 RecordCopiedObject(heap, target);
2308 heap->OnMoveEvent(target, source, size);
2311 if (marks_handling == TRANSFER_MARKS) {
2312 if (Marking::TransferColor(source, target)) {
2313 MemoryChunk::IncrementLiveBytesFromGC(target, size);
2318 template <AllocationAlignment alignment>
2319 static inline bool SemiSpaceCopyObject(Map* map, HeapObject** slot,
2320 HeapObject* object, int object_size) {
2321 Heap* heap = map->GetHeap();
2323 DCHECK(heap->AllowedToBeMigrated(object, NEW_SPACE));
2324 AllocationResult allocation =
2325 heap->new_space()->AllocateRaw(object_size, alignment);
2327 HeapObject* target = NULL; // Initialization to please compiler.
2328 if (allocation.To(&target)) {
2329 // Order is important here: Set the promotion limit before storing a
2330 // filler for double alignment or migrating the object. Otherwise we
2331 // may end up overwriting promotion queue entries when we migrate the
2333 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
2335 MigrateObject(heap, object, target, object_size);
2337 // Update slot to new target.
2340 heap->IncrementSemiSpaceCopiedObjectSize(object_size);
2347 template <ObjectContents object_contents, AllocationAlignment alignment>
2348 static inline bool PromoteObject(Map* map, HeapObject** slot,
2349 HeapObject* object, int object_size) {
2350 Heap* heap = map->GetHeap();
2352 AllocationResult allocation =
2353 heap->old_space()->AllocateRaw(object_size, alignment);
2355 HeapObject* target = NULL; // Initialization to please compiler.
2356 if (allocation.To(&target)) {
2357 MigrateObject(heap, object, target, object_size);
2359 // Update slot to new target.
2362 if (object_contents == POINTER_OBJECT) {
2363 if (map->instance_type() == JS_FUNCTION_TYPE) {
2364 heap->promotion_queue()->insert(target,
2365 JSFunction::kNonWeakFieldsEndOffset);
2367 heap->promotion_queue()->insert(target, object_size);
2370 heap->IncrementPromotedObjectsSize(object_size);
2377 template <ObjectContents object_contents, AllocationAlignment alignment>
2378 static inline void EvacuateObject(Map* map, HeapObject** slot,
2379 HeapObject* object, int object_size) {
2380 SLOW_DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
2381 SLOW_DCHECK(object->Size() == object_size);
2382 Heap* heap = map->GetHeap();
2384 if (!heap->ShouldBePromoted(object->address(), object_size)) {
2385 // A semi-space copy may fail due to fragmentation. In that case, we
2386 // try to promote the object.
2387 if (SemiSpaceCopyObject<alignment>(map, slot, object, object_size)) {
2392 if (PromoteObject<object_contents, alignment>(map, slot, object,
2397 // If promotion failed, we try to copy the object to the other semi-space
2398 if (SemiSpaceCopyObject<alignment>(map, slot, object, object_size)) return;
2404 static inline void EvacuateJSFunction(Map* map, HeapObject** slot,
2405 HeapObject* object) {
2406 ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2407 JSFunction::kSize>(map, slot, object);
2409 MapWord map_word = object->map_word();
2410 DCHECK(map_word.IsForwardingAddress());
2411 HeapObject* target = map_word.ToForwardingAddress();
2413 MarkBit mark_bit = Marking::MarkBitFrom(target);
2414 if (Marking::IsBlack(mark_bit)) {
2415 // This object is black and it might not be rescanned by marker.
2416 // We should explicitly record code entry slot for compaction because
2417 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
2418 // miss it as it is not HeapObject-tagged.
2419 Address code_entry_slot =
2420 target->address() + JSFunction::kCodeEntryOffset;
2421 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
2422 map->GetHeap()->mark_compact_collector()->RecordCodeEntrySlot(
2423 target, code_entry_slot, code);
2428 static inline void EvacuateFixedArray(Map* map, HeapObject** slot,
2429 HeapObject* object) {
2430 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
2431 EvacuateObject<POINTER_OBJECT, kWordAligned>(map, slot, object,
2436 static inline void EvacuateFixedDoubleArray(Map* map, HeapObject** slot,
2437 HeapObject* object) {
2438 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
2439 int object_size = FixedDoubleArray::SizeFor(length);
2440 EvacuateObject<DATA_OBJECT, kDoubleAligned>(map, slot, object, object_size);
2444 static inline void EvacuateFixedTypedArray(Map* map, HeapObject** slot,
2445 HeapObject* object) {
2446 int object_size = reinterpret_cast<FixedTypedArrayBase*>(object)->size();
2447 EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2449 MapWord map_word = object->map_word();
2450 DCHECK(map_word.IsForwardingAddress());
2451 FixedTypedArrayBase* target =
2452 reinterpret_cast<FixedTypedArrayBase*>(map_word.ToForwardingAddress());
2453 if (target->base_pointer() != Smi::FromInt(0))
2454 target->set_base_pointer(target, SKIP_WRITE_BARRIER);
2458 static inline void EvacuateFixedFloat64Array(Map* map, HeapObject** slot,
2459 HeapObject* object) {
2460 int object_size = reinterpret_cast<FixedFloat64Array*>(object)->size();
2461 EvacuateObject<DATA_OBJECT, kDoubleAligned>(map, slot, object, object_size);
2463 MapWord map_word = object->map_word();
2464 DCHECK(map_word.IsForwardingAddress());
2465 FixedTypedArrayBase* target =
2466 reinterpret_cast<FixedTypedArrayBase*>(map_word.ToForwardingAddress());
2467 if (target->base_pointer() != Smi::FromInt(0))
2468 target->set_base_pointer(target, SKIP_WRITE_BARRIER);
2472 static inline void EvacuateJSArrayBuffer(Map* map, HeapObject** slot,
2473 HeapObject* object) {
2474 ObjectEvacuationStrategy<POINTER_OBJECT>::Visit(map, slot, object);
2476 Heap* heap = map->GetHeap();
2477 MapWord map_word = object->map_word();
2478 DCHECK(map_word.IsForwardingAddress());
2479 HeapObject* target = map_word.ToForwardingAddress();
2480 if (!heap->InNewSpace(target)) heap->PromoteArrayBuffer(target);
2484 static inline void EvacuateByteArray(Map* map, HeapObject** slot,
2485 HeapObject* object) {
2486 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
2487 EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2491 static inline void EvacuateSeqOneByteString(Map* map, HeapObject** slot,
2492 HeapObject* object) {
2493 int object_size = SeqOneByteString::cast(object)
2494 ->SeqOneByteStringSize(map->instance_type());
2495 EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2499 static inline void EvacuateSeqTwoByteString(Map* map, HeapObject** slot,
2500 HeapObject* object) {
2501 int object_size = SeqTwoByteString::cast(object)
2502 ->SeqTwoByteStringSize(map->instance_type());
2503 EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2507 static inline void EvacuateShortcutCandidate(Map* map, HeapObject** slot,
2508 HeapObject* object) {
2509 DCHECK(IsShortcutCandidate(map->instance_type()));
2511 Heap* heap = map->GetHeap();
2513 if (marks_handling == IGNORE_MARKS &&
2514 ConsString::cast(object)->unchecked_second() == heap->empty_string()) {
2516 HeapObject::cast(ConsString::cast(object)->unchecked_first());
2520 if (!heap->InNewSpace(first)) {
2521 object->set_map_word(MapWord::FromForwardingAddress(first));
2525 MapWord first_word = first->map_word();
2526 if (first_word.IsForwardingAddress()) {
2527 HeapObject* target = first_word.ToForwardingAddress();
2530 object->set_map_word(MapWord::FromForwardingAddress(target));
2534 heap->DoScavengeObject(first->map(), slot, first);
2535 object->set_map_word(MapWord::FromForwardingAddress(*slot));
2539 int object_size = ConsString::kSize;
2540 EvacuateObject<POINTER_OBJECT, kWordAligned>(map, slot, object,
2544 template <ObjectContents object_contents>
2545 class ObjectEvacuationStrategy {
2547 template <int object_size>
2548 static inline void VisitSpecialized(Map* map, HeapObject** slot,
2549 HeapObject* object) {
2550 EvacuateObject<object_contents, kWordAligned>(map, slot, object,
2554 static inline void Visit(Map* map, HeapObject** slot, HeapObject* object) {
2555 int object_size = map->instance_size();
2556 EvacuateObject<object_contents, kWordAligned>(map, slot, object,
2561 static VisitorDispatchTable<ScavengingCallback> table_;
2565 template <MarksHandling marks_handling,
2566 LoggingAndProfiling logging_and_profiling_mode>
2567 VisitorDispatchTable<ScavengingCallback>
2568 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
2571 static void InitializeScavengingVisitorsTables() {
2572 ScavengingVisitor<TRANSFER_MARKS,
2573 LOGGING_AND_PROFILING_DISABLED>::Initialize();
2574 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
2575 ScavengingVisitor<TRANSFER_MARKS,
2576 LOGGING_AND_PROFILING_ENABLED>::Initialize();
2577 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
2581 void Heap::SelectScavengingVisitorsTable() {
2582 bool logging_and_profiling =
2583 FLAG_verify_predictable || isolate()->logger()->is_logging() ||
2584 isolate()->cpu_profiler()->is_profiling() ||
2585 (isolate()->heap_profiler() != NULL &&
2586 isolate()->heap_profiler()->is_tracking_object_moves());
2588 if (!incremental_marking()->IsMarking()) {
2589 if (!logging_and_profiling) {
2590 scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2591 IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable());
2593 scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2594 IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable());
2597 if (!logging_and_profiling) {
2598 scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2599 TRANSFER_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable());
2601 scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2602 TRANSFER_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable());
2605 if (incremental_marking()->IsCompacting()) {
2606 // When compacting forbid short-circuiting of cons-strings.
2607 // Scavenging code relies on the fact that new space object
2608 // can't be evacuated into evacuation candidate but
2609 // short-circuiting violates this assumption.
2610 scavenging_visitors_table_.Register(
2611 StaticVisitorBase::kVisitShortcutCandidate,
2612 scavenging_visitors_table_.GetVisitorById(
2613 StaticVisitorBase::kVisitConsString));
2619 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
2620 SLOW_DCHECK(object->GetIsolate()->heap()->InFromSpace(object));
2621 MapWord first_word = object->map_word();
2622 SLOW_DCHECK(!first_word.IsForwardingAddress());
2623 Map* map = first_word.ToMap();
2624 map->GetHeap()->DoScavengeObject(map, p, object);
2628 void Heap::ConfigureInitialOldGenerationSize() {
2629 if (!old_generation_size_configured_ && tracer()->SurvivalEventsRecorded()) {
2630 old_generation_allocation_limit_ =
2631 Max(kMinimumOldGenerationAllocationLimit,
2632 static_cast<intptr_t>(
2633 static_cast<double>(old_generation_allocation_limit_) *
2634 (tracer()->AverageSurvivalRatio() / 100)));
2639 AllocationResult Heap::AllocatePartialMap(InstanceType instance_type,
2640 int instance_size) {
2641 Object* result = nullptr;
2642 AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE);
2643 if (!allocation.To(&result)) return allocation;
2645 // Map::cast cannot be used due to uninitialized map field.
2646 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
2647 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
2648 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2649 // Initialize to only containing tagged fields.
2650 reinterpret_cast<Map*>(result)->set_visitor_id(
2651 StaticVisitorBase::GetVisitorId(instance_type, instance_size, false));
2652 if (FLAG_unbox_double_fields) {
2653 reinterpret_cast<Map*>(result)
2654 ->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2656 reinterpret_cast<Map*>(result)->clear_unused();
2657 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2658 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2659 reinterpret_cast<Map*>(result)->set_bit_field(0);
2660 reinterpret_cast<Map*>(result)->set_bit_field2(0);
2661 int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
2662 Map::OwnsDescriptors::encode(true) |
2663 Map::Counter::encode(Map::kRetainingCounterStart);
2664 reinterpret_cast<Map*>(result)->set_bit_field3(bit_field3);
2665 reinterpret_cast<Map*>(result)->set_weak_cell_cache(Smi::FromInt(0));
2670 AllocationResult Heap::AllocateMap(InstanceType instance_type,
2672 ElementsKind elements_kind) {
2674 AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE);
2675 if (!allocation.To(&result)) return allocation;
2677 result->set_map_no_write_barrier(meta_map());
2678 Map* map = Map::cast(result);
2679 map->set_instance_type(instance_type);
2680 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2681 map->set_constructor_or_backpointer(null_value(), SKIP_WRITE_BARRIER);
2682 map->set_instance_size(instance_size);
2683 map->clear_unused();
2684 map->set_inobject_properties(0);
2685 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2686 map->set_dependent_code(DependentCode::cast(empty_fixed_array()),
2687 SKIP_WRITE_BARRIER);
2688 map->set_weak_cell_cache(Smi::FromInt(0));
2689 map->set_raw_transitions(Smi::FromInt(0));
2690 map->set_unused_property_fields(0);
2691 map->set_instance_descriptors(empty_descriptor_array());
2692 if (FLAG_unbox_double_fields) {
2693 map->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2695 // Must be called only after |instance_type|, |instance_size| and
2696 // |layout_descriptor| are set.
2697 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
2698 map->set_bit_field(0);
2699 map->set_bit_field2(1 << Map::kIsExtensible);
2700 int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
2701 Map::OwnsDescriptors::encode(true) |
2702 Map::Counter::encode(Map::kRetainingCounterStart);
2703 map->set_bit_field3(bit_field3);
2704 map->set_elements_kind(elements_kind);
2710 AllocationResult Heap::AllocateFillerObject(int size, bool double_align,
2711 AllocationSpace space) {
2714 AllocationAlignment align = double_align ? kDoubleAligned : kWordAligned;
2715 AllocationResult allocation = AllocateRaw(size, space, space, align);
2716 if (!allocation.To(&obj)) return allocation;
2719 MemoryChunk* chunk = MemoryChunk::FromAddress(obj->address());
2720 DCHECK(chunk->owner()->identity() == space);
2722 CreateFillerObjectAt(obj->address(), size);
2727 const Heap::StringTypeTable Heap::string_type_table[] = {
2728 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
2729 { type, size, k##camel_name##MapRootIndex } \
2731 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2732 #undef STRING_TYPE_ELEMENT
2736 const Heap::ConstantStringTable Heap::constant_string_table[] = {
2737 {"", kempty_stringRootIndex},
2738 #define CONSTANT_STRING_ELEMENT(name, contents) \
2739 { contents, k##name##RootIndex } \
2741 INTERNALIZED_STRING_LIST(CONSTANT_STRING_ELEMENT)
2742 #undef CONSTANT_STRING_ELEMENT
2746 const Heap::StructTable Heap::struct_table[] = {
2747 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
2748 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex } \
2750 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2751 #undef STRUCT_TABLE_ELEMENT
2755 bool Heap::CreateInitialMaps() {
2758 AllocationResult allocation = AllocatePartialMap(MAP_TYPE, Map::kSize);
2759 if (!allocation.To(&obj)) return false;
2761 // Map::cast cannot be used due to uninitialized map field.
2762 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2763 set_meta_map(new_meta_map);
2764 new_meta_map->set_map(new_meta_map);
2766 { // Partial map allocation
2767 #define ALLOCATE_PARTIAL_MAP(instance_type, size, field_name) \
2770 if (!AllocatePartialMap((instance_type), (size)).To(&map)) return false; \
2771 set_##field_name##_map(map); \
2774 ALLOCATE_PARTIAL_MAP(FIXED_ARRAY_TYPE, kVariableSizeSentinel, fixed_array);
2775 ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, undefined);
2776 ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, null);
2778 #undef ALLOCATE_PARTIAL_MAP
2781 // Allocate the empty array.
2783 AllocationResult allocation = AllocateEmptyFixedArray();
2784 if (!allocation.To(&obj)) return false;
2786 set_empty_fixed_array(FixedArray::cast(obj));
2789 AllocationResult allocation = Allocate(null_map(), OLD_SPACE);
2790 if (!allocation.To(&obj)) return false;
2792 set_null_value(Oddball::cast(obj));
2793 Oddball::cast(obj)->set_kind(Oddball::kNull);
2796 AllocationResult allocation = Allocate(undefined_map(), OLD_SPACE);
2797 if (!allocation.To(&obj)) return false;
2799 set_undefined_value(Oddball::cast(obj));
2800 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2801 DCHECK(!InNewSpace(undefined_value()));
2803 // Set preliminary exception sentinel value before actually initializing it.
2804 set_exception(null_value());
2806 // Allocate the empty descriptor array.
2808 AllocationResult allocation = AllocateEmptyFixedArray();
2809 if (!allocation.To(&obj)) return false;
2811 set_empty_descriptor_array(DescriptorArray::cast(obj));
2813 // Fix the instance_descriptors for the existing maps.
2814 meta_map()->set_code_cache(empty_fixed_array());
2815 meta_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2816 meta_map()->set_raw_transitions(Smi::FromInt(0));
2817 meta_map()->set_instance_descriptors(empty_descriptor_array());
2818 if (FLAG_unbox_double_fields) {
2819 meta_map()->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2822 fixed_array_map()->set_code_cache(empty_fixed_array());
2823 fixed_array_map()->set_dependent_code(
2824 DependentCode::cast(empty_fixed_array()));
2825 fixed_array_map()->set_raw_transitions(Smi::FromInt(0));
2826 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
2827 if (FLAG_unbox_double_fields) {
2828 fixed_array_map()->set_layout_descriptor(
2829 LayoutDescriptor::FastPointerLayout());
2832 undefined_map()->set_code_cache(empty_fixed_array());
2833 undefined_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2834 undefined_map()->set_raw_transitions(Smi::FromInt(0));
2835 undefined_map()->set_instance_descriptors(empty_descriptor_array());
2836 if (FLAG_unbox_double_fields) {
2837 undefined_map()->set_layout_descriptor(
2838 LayoutDescriptor::FastPointerLayout());
2841 null_map()->set_code_cache(empty_fixed_array());
2842 null_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2843 null_map()->set_raw_transitions(Smi::FromInt(0));
2844 null_map()->set_instance_descriptors(empty_descriptor_array());
2845 if (FLAG_unbox_double_fields) {
2846 null_map()->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2849 // Fix prototype object for existing maps.
2850 meta_map()->set_prototype(null_value());
2851 meta_map()->set_constructor_or_backpointer(null_value());
2853 fixed_array_map()->set_prototype(null_value());
2854 fixed_array_map()->set_constructor_or_backpointer(null_value());
2856 undefined_map()->set_prototype(null_value());
2857 undefined_map()->set_constructor_or_backpointer(null_value());
2859 null_map()->set_prototype(null_value());
2860 null_map()->set_constructor_or_backpointer(null_value());
2863 #define ALLOCATE_MAP(instance_type, size, field_name) \
2866 if (!AllocateMap((instance_type), size).To(&map)) return false; \
2867 set_##field_name##_map(map); \
2870 #define ALLOCATE_VARSIZE_MAP(instance_type, field_name) \
2871 ALLOCATE_MAP(instance_type, kVariableSizeSentinel, field_name)
2873 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, fixed_cow_array)
2874 DCHECK(fixed_array_map() != fixed_cow_array_map());
2876 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, scope_info)
2877 ALLOCATE_MAP(HEAP_NUMBER_TYPE, HeapNumber::kSize, heap_number)
2878 ALLOCATE_MAP(MUTABLE_HEAP_NUMBER_TYPE, HeapNumber::kSize,
2879 mutable_heap_number)
2880 ALLOCATE_MAP(SYMBOL_TYPE, Symbol::kSize, symbol)
2881 #define ALLOCATE_SIMD128_MAP(TYPE, Type, type, lane_count, lane_type) \
2882 ALLOCATE_MAP(SIMD128_VALUE_TYPE, Type::kSize, type)
2883 SIMD128_TYPES(ALLOCATE_SIMD128_MAP)
2884 #undef ALLOCATE_SIMD128_MAP
2885 ALLOCATE_MAP(FOREIGN_TYPE, Foreign::kSize, foreign)
2887 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, the_hole);
2888 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, boolean);
2889 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, uninitialized);
2890 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, arguments_marker);
2891 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, no_interceptor_result_sentinel);
2892 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, exception);
2893 ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, termination_exception);
2895 for (unsigned i = 0; i < arraysize(string_type_table); i++) {
2896 const StringTypeTable& entry = string_type_table[i];
2898 AllocationResult allocation = AllocateMap(entry.type, entry.size);
2899 if (!allocation.To(&obj)) return false;
2901 // Mark cons string maps as unstable, because their objects can change
2903 Map* map = Map::cast(obj);
2904 if (StringShape(entry.type).IsCons()) map->mark_unstable();
2905 roots_[entry.index] = map;
2908 { // Create a separate external one byte string map for native sources.
2909 AllocationResult allocation = AllocateMap(EXTERNAL_ONE_BYTE_STRING_TYPE,
2910 ExternalOneByteString::kSize);
2911 if (!allocation.To(&obj)) return false;
2912 set_native_source_string_map(Map::cast(obj));
2915 ALLOCATE_VARSIZE_MAP(FIXED_DOUBLE_ARRAY_TYPE, fixed_double_array)
2916 ALLOCATE_VARSIZE_MAP(BYTE_ARRAY_TYPE, byte_array)
2917 ALLOCATE_VARSIZE_MAP(BYTECODE_ARRAY_TYPE, bytecode_array)
2918 ALLOCATE_VARSIZE_MAP(FREE_SPACE_TYPE, free_space)
2920 #define ALLOCATE_FIXED_TYPED_ARRAY_MAP(Type, type, TYPE, ctype, size) \
2921 ALLOCATE_VARSIZE_MAP(FIXED_##TYPE##_ARRAY_TYPE, fixed_##type##_array)
2923 TYPED_ARRAYS(ALLOCATE_FIXED_TYPED_ARRAY_MAP)
2924 #undef ALLOCATE_FIXED_TYPED_ARRAY_MAP
2926 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, sloppy_arguments_elements)
2928 ALLOCATE_VARSIZE_MAP(CODE_TYPE, code)
2930 ALLOCATE_MAP(CELL_TYPE, Cell::kSize, cell)
2931 ALLOCATE_MAP(PROPERTY_CELL_TYPE, PropertyCell::kSize, global_property_cell)
2932 ALLOCATE_MAP(WEAK_CELL_TYPE, WeakCell::kSize, weak_cell)
2933 ALLOCATE_MAP(FILLER_TYPE, kPointerSize, one_pointer_filler)
2934 ALLOCATE_MAP(FILLER_TYPE, 2 * kPointerSize, two_pointer_filler)
2937 for (unsigned i = 0; i < arraysize(struct_table); i++) {
2938 const StructTable& entry = struct_table[i];
2940 if (!AllocateMap(entry.type, entry.size).To(&map)) return false;
2941 roots_[entry.index] = map;
2944 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, hash_table)
2945 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, ordered_hash_table)
2947 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, function_context)
2948 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, catch_context)
2949 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, with_context)
2950 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, block_context)
2951 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, module_context)
2952 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, script_context)
2953 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, script_context_table)
2955 ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, native_context)
2956 native_context_map()->set_dictionary_map(true);
2957 native_context_map()->set_visitor_id(
2958 StaticVisitorBase::kVisitNativeContext);
2960 ALLOCATE_MAP(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kAlignedSize,
2961 shared_function_info)
2963 ALLOCATE_MAP(JS_MESSAGE_OBJECT_TYPE, JSMessageObject::kSize, message_object)
2964 ALLOCATE_MAP(JS_OBJECT_TYPE, JSObject::kHeaderSize + kPointerSize, external)
2965 external_map()->set_is_extensible(false);
2966 #undef ALLOCATE_VARSIZE_MAP
2972 ByteArray* byte_array;
2973 if (!AllocateByteArray(0, TENURED).To(&byte_array)) return false;
2974 set_empty_byte_array(byte_array);
2976 BytecodeArray* bytecode_array;
2977 AllocationResult allocation =
2978 AllocateBytecodeArray(0, nullptr, kPointerSize);
2979 if (!allocation.To(&bytecode_array)) {
2982 set_empty_bytecode_array(bytecode_array);
2985 #define ALLOCATE_EMPTY_FIXED_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
2987 FixedTypedArrayBase* obj; \
2988 if (!AllocateEmptyFixedTypedArray(kExternal##Type##Array).To(&obj)) \
2990 set_empty_fixed_##type##_array(obj); \
2993 TYPED_ARRAYS(ALLOCATE_EMPTY_FIXED_TYPED_ARRAY)
2994 #undef ALLOCATE_EMPTY_FIXED_TYPED_ARRAY
2996 DCHECK(!InNewSpace(empty_fixed_array()));
3001 AllocationResult Heap::AllocateHeapNumber(double value, MutableMode mode,
3002 PretenureFlag pretenure) {
3003 // Statically ensure that it is safe to allocate heap numbers in paged
3005 int size = HeapNumber::kSize;
3006 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxRegularHeapObjectSize);
3008 AllocationSpace space = SelectSpace(size, pretenure);
3012 AllocationResult allocation =
3013 AllocateRaw(size, space, OLD_SPACE, kDoubleUnaligned);
3014 if (!allocation.To(&result)) return allocation;
3017 Map* map = mode == MUTABLE ? mutable_heap_number_map() : heap_number_map();
3018 HeapObject::cast(result)->set_map_no_write_barrier(map);
3019 HeapNumber::cast(result)->set_value(value);
3023 #define SIMD_ALLOCATE_DEFINITION(TYPE, Type, type, lane_count, lane_type) \
3024 AllocationResult Heap::Allocate##Type(lane_type lanes[lane_count], \
3025 PretenureFlag pretenure) { \
3026 int size = Type::kSize; \
3027 STATIC_ASSERT(Type::kSize <= Page::kMaxRegularHeapObjectSize); \
3029 AllocationSpace space = SelectSpace(size, pretenure); \
3031 HeapObject* result; \
3033 AllocationResult allocation = \
3034 AllocateRaw(size, space, OLD_SPACE, kSimd128Unaligned); \
3035 if (!allocation.To(&result)) return allocation; \
3038 result->set_map_no_write_barrier(type##_map()); \
3039 Type* instance = Type::cast(result); \
3040 for (int i = 0; i < lane_count; i++) { \
3041 instance->set_lane(i, lanes[i]); \
3045 SIMD128_TYPES(SIMD_ALLOCATE_DEFINITION)
3046 #undef SIMD_ALLOCATE_DEFINITION
3049 AllocationResult Heap::AllocateCell(Object* value) {
3050 int size = Cell::kSize;
3051 STATIC_ASSERT(Cell::kSize <= Page::kMaxRegularHeapObjectSize);
3055 AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3056 if (!allocation.To(&result)) return allocation;
3058 result->set_map_no_write_barrier(cell_map());
3059 Cell::cast(result)->set_value(value);
3064 AllocationResult Heap::AllocatePropertyCell() {
3065 int size = PropertyCell::kSize;
3066 STATIC_ASSERT(PropertyCell::kSize <= Page::kMaxRegularHeapObjectSize);
3069 AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3070 if (!allocation.To(&result)) return allocation;
3072 result->set_map_no_write_barrier(global_property_cell_map());
3073 PropertyCell* cell = PropertyCell::cast(result);
3074 cell->set_dependent_code(DependentCode::cast(empty_fixed_array()),
3075 SKIP_WRITE_BARRIER);
3076 cell->set_property_details(PropertyDetails(Smi::FromInt(0)));
3077 cell->set_value(the_hole_value());
3082 AllocationResult Heap::AllocateWeakCell(HeapObject* value) {
3083 int size = WeakCell::kSize;
3084 STATIC_ASSERT(WeakCell::kSize <= Page::kMaxRegularHeapObjectSize);
3085 HeapObject* result = NULL;
3087 AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3088 if (!allocation.To(&result)) return allocation;
3090 result->set_map_no_write_barrier(weak_cell_map());
3091 WeakCell::cast(result)->initialize(value);
3092 WeakCell::cast(result)->clear_next(this);
3097 void Heap::CreateApiObjects() {
3098 HandleScope scope(isolate());
3099 Factory* factory = isolate()->factory();
3100 Handle<Map> new_neander_map =
3101 factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
3103 // Don't use Smi-only elements optimizations for objects with the neander
3104 // map. There are too many cases where element values are set directly with a
3105 // bottleneck to trap the Smi-only -> fast elements transition, and there
3106 // appears to be no benefit for optimize this case.
3107 new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
3108 set_neander_map(*new_neander_map);
3110 Handle<JSObject> listeners = factory->NewNeanderObject();
3111 Handle<FixedArray> elements = factory->NewFixedArray(2);
3112 elements->set(0, Smi::FromInt(0));
3113 listeners->set_elements(*elements);
3114 set_message_listeners(*listeners);
3118 void Heap::CreateJSEntryStub() {
3119 JSEntryStub stub(isolate(), StackFrame::ENTRY);
3120 set_js_entry_code(*stub.GetCode());
3124 void Heap::CreateJSConstructEntryStub() {
3125 JSEntryStub stub(isolate(), StackFrame::ENTRY_CONSTRUCT);
3126 set_js_construct_entry_code(*stub.GetCode());
3130 void Heap::CreateFixedStubs() {
3131 // Here we create roots for fixed stubs. They are needed at GC
3132 // for cooking and uncooking (check out frames.cc).
3133 // The eliminates the need for doing dictionary lookup in the
3134 // stub cache for these stubs.
3135 HandleScope scope(isolate());
3137 // Create stubs that should be there, so we don't unexpectedly have to
3138 // create them if we need them during the creation of another stub.
3139 // Stub creation mixes raw pointers and handles in an unsafe manner so
3140 // we cannot create stubs while we are creating stubs.
3141 CodeStub::GenerateStubsAheadOfTime(isolate());
3143 // MacroAssembler::Abort calls (usually enabled with --debug-code) depend on
3144 // CEntryStub, so we need to call GenerateStubsAheadOfTime before JSEntryStub
3147 // gcc-4.4 has problem generating correct code of following snippet:
3148 // { JSEntryStub stub;
3149 // js_entry_code_ = *stub.GetCode();
3151 // { JSConstructEntryStub stub;
3152 // js_construct_entry_code_ = *stub.GetCode();
3154 // To workaround the problem, make separate functions without inlining.
3155 Heap::CreateJSEntryStub();
3156 Heap::CreateJSConstructEntryStub();
3160 void Heap::CreateInitialObjects() {
3161 HandleScope scope(isolate());
3162 Factory* factory = isolate()->factory();
3164 // The -0 value must be set before NewNumber works.
3165 set_minus_zero_value(*factory->NewHeapNumber(-0.0, IMMUTABLE, TENURED));
3166 DCHECK(std::signbit(minus_zero_value()->Number()) != 0);
3168 set_nan_value(*factory->NewHeapNumber(
3169 std::numeric_limits<double>::quiet_NaN(), IMMUTABLE, TENURED));
3170 set_infinity_value(*factory->NewHeapNumber(V8_INFINITY, IMMUTABLE, TENURED));
3171 set_minus_infinity_value(
3172 *factory->NewHeapNumber(-V8_INFINITY, IMMUTABLE, TENURED));
3174 // The hole has not been created yet, but we want to put something
3175 // predictable in the gaps in the string table, so lets make that Smi zero.
3176 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
3178 // Allocate initial string table.
3179 set_string_table(*StringTable::New(isolate(), kInitialStringTableSize));
3181 // Finish initializing oddballs after creating the string table.
3182 Oddball::Initialize(isolate(), factory->undefined_value(), "undefined",
3183 factory->nan_value(), "undefined", Oddball::kUndefined);
3185 // Initialize the null_value.
3186 Oddball::Initialize(isolate(), factory->null_value(), "null",
3187 handle(Smi::FromInt(0), isolate()), "object",
3190 set_true_value(*factory->NewOddball(factory->boolean_map(), "true",
3191 handle(Smi::FromInt(1), isolate()),
3192 "boolean", Oddball::kTrue));
3194 set_false_value(*factory->NewOddball(factory->boolean_map(), "false",
3195 handle(Smi::FromInt(0), isolate()),
3196 "boolean", Oddball::kFalse));
3198 set_the_hole_value(*factory->NewOddball(factory->the_hole_map(), "hole",
3199 handle(Smi::FromInt(-1), isolate()),
3200 "undefined", Oddball::kTheHole));
3202 set_uninitialized_value(
3203 *factory->NewOddball(factory->uninitialized_map(), "uninitialized",
3204 handle(Smi::FromInt(-1), isolate()), "undefined",
3205 Oddball::kUninitialized));
3207 set_arguments_marker(
3208 *factory->NewOddball(factory->arguments_marker_map(), "arguments_marker",
3209 handle(Smi::FromInt(-4), isolate()), "undefined",
3210 Oddball::kArgumentMarker));
3212 set_no_interceptor_result_sentinel(*factory->NewOddball(
3213 factory->no_interceptor_result_sentinel_map(),
3214 "no_interceptor_result_sentinel", handle(Smi::FromInt(-2), isolate()),
3215 "undefined", Oddball::kOther));
3217 set_termination_exception(*factory->NewOddball(
3218 factory->termination_exception_map(), "termination_exception",
3219 handle(Smi::FromInt(-3), isolate()), "undefined", Oddball::kOther));
3221 set_exception(*factory->NewOddball(factory->exception_map(), "exception",
3222 handle(Smi::FromInt(-5), isolate()),
3223 "undefined", Oddball::kException));
3225 for (unsigned i = 0; i < arraysize(constant_string_table); i++) {
3226 Handle<String> str =
3227 factory->InternalizeUtf8String(constant_string_table[i].contents);
3228 roots_[constant_string_table[i].index] = *str;
3231 // Allocate the hidden string which is used to identify the hidden properties
3232 // in JSObjects. The hash code has a special value so that it will not match
3233 // the empty string when searching for the property. It cannot be part of the
3234 // loop above because it needs to be allocated manually with the special
3235 // hash code in place. The hash code for the hidden_string is zero to ensure
3236 // that it will always be at the first entry in property descriptors.
3237 hidden_string_ = *factory->NewOneByteInternalizedString(
3238 OneByteVector("", 0), String::kEmptyStringHash);
3240 // Create the code_stubs dictionary. The initial size is set to avoid
3241 // expanding the dictionary during bootstrapping.
3242 set_code_stubs(*UnseededNumberDictionary::New(isolate(), 128));
3244 // Create the non_monomorphic_cache used in stub-cache.cc. The initial size
3245 // is set to avoid expanding the dictionary during bootstrapping.
3246 set_non_monomorphic_cache(*UnseededNumberDictionary::New(isolate(), 64));
3248 set_polymorphic_code_cache(PolymorphicCodeCache::cast(
3249 *factory->NewStruct(POLYMORPHIC_CODE_CACHE_TYPE)));
3251 set_instanceof_cache_function(Smi::FromInt(0));
3252 set_instanceof_cache_map(Smi::FromInt(0));
3253 set_instanceof_cache_answer(Smi::FromInt(0));
3256 HandleScope scope(isolate());
3257 #define SYMBOL_INIT(name) \
3259 Handle<String> name##d = factory->NewStringFromStaticChars(#name); \
3260 Handle<Object> symbol(isolate()->factory()->NewPrivateSymbol(name##d)); \
3261 roots_[k##name##RootIndex] = *symbol; \
3263 PRIVATE_SYMBOL_LIST(SYMBOL_INIT)
3268 HandleScope scope(isolate());
3269 #define SYMBOL_INIT(name, varname, description) \
3270 Handle<Symbol> name = factory->NewSymbol(); \
3271 Handle<String> name##d = factory->NewStringFromStaticChars(#description); \
3272 name->set_name(*name##d); \
3273 roots_[k##name##RootIndex] = *name;
3274 PUBLIC_SYMBOL_LIST(SYMBOL_INIT)
3280 // Allocate the dictionary of intrinsic function names.
3281 Handle<NameDictionary> intrinsic_names =
3282 NameDictionary::New(isolate(), Runtime::kNumFunctions, TENURED);
3283 Runtime::InitializeIntrinsicFunctionNames(isolate(), intrinsic_names);
3284 set_intrinsic_function_names(*intrinsic_names);
3286 set_number_string_cache(
3287 *factory->NewFixedArray(kInitialNumberStringCacheSize * 2, TENURED));
3289 // Allocate cache for single character one byte strings.
3290 set_single_character_string_cache(
3291 *factory->NewFixedArray(String::kMaxOneByteCharCode + 1, TENURED));
3293 // Allocate cache for string split and regexp-multiple.
3294 set_string_split_cache(*factory->NewFixedArray(
3295 RegExpResultsCache::kRegExpResultsCacheSize, TENURED));
3296 set_regexp_multiple_cache(*factory->NewFixedArray(
3297 RegExpResultsCache::kRegExpResultsCacheSize, TENURED));
3299 // Allocate cache for external strings pointing to native source code.
3300 set_natives_source_cache(
3301 *factory->NewFixedArray(Natives::GetBuiltinsCount()));
3303 set_experimental_natives_source_cache(
3304 *factory->NewFixedArray(ExperimentalNatives::GetBuiltinsCount()));
3306 set_extra_natives_source_cache(
3307 *factory->NewFixedArray(ExtraNatives::GetBuiltinsCount()));
3309 set_code_stub_natives_source_cache(
3310 *factory->NewFixedArray(CodeStubNatives::GetBuiltinsCount()));
3312 set_undefined_cell(*factory->NewCell(factory->undefined_value()));
3314 // The symbol registry is initialized lazily.
3315 set_symbol_registry(Smi::FromInt(0));
3317 // Allocate object to hold object observation state.
3318 set_observation_state(*factory->NewJSObjectFromMap(
3319 factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize)));
3321 // Microtask queue uses the empty fixed array as a sentinel for "empty".
3322 // Number of queued microtasks stored in Isolate::pending_microtask_count().
3323 set_microtask_queue(empty_fixed_array());
3326 Code::Kind kinds[] = {Code::LOAD_IC, Code::KEYED_LOAD_IC, Code::STORE_IC,
3327 Code::KEYED_STORE_IC};
3328 FeedbackVectorSpec spec(0, 4, kinds);
3329 Handle<TypeFeedbackVector> dummy_vector =
3330 factory->NewTypeFeedbackVector(&spec);
3331 for (int i = 0; i < 4; i++) {
3332 dummy_vector->Set(FeedbackVectorICSlot(0),
3333 *TypeFeedbackVector::MegamorphicSentinel(isolate()),
3334 SKIP_WRITE_BARRIER);
3336 set_dummy_vector(*dummy_vector);
3339 set_detached_contexts(empty_fixed_array());
3340 set_retained_maps(ArrayList::cast(empty_fixed_array()));
3342 set_weak_object_to_code_table(
3343 *WeakHashTable::New(isolate(), 16, USE_DEFAULT_MINIMUM_CAPACITY,
3346 Handle<SeededNumberDictionary> slow_element_dictionary =
3347 SeededNumberDictionary::New(isolate(), 0, TENURED);
3348 slow_element_dictionary->set_requires_slow_elements();
3349 set_empty_slow_element_dictionary(*slow_element_dictionary);
3351 set_materialized_objects(*factory->NewFixedArray(0, TENURED));
3353 // Handling of script id generation is in Factory::NewScript.
3354 set_last_script_id(Smi::FromInt(v8::UnboundScript::kNoScriptId));
3356 Handle<PropertyCell> cell = factory->NewPropertyCell();
3357 cell->set_value(Smi::FromInt(Isolate::kArrayProtectorValid));
3358 set_array_protector(*cell);
3360 cell = factory->NewPropertyCell();
3361 cell->set_value(the_hole_value());
3362 set_empty_property_cell(*cell);
3364 set_weak_stack_trace_list(Smi::FromInt(0));
3366 // Will be filled in by Interpreter::Initialize().
3367 set_interpreter_table(
3368 *interpreter::Interpreter::CreateUninitializedInterpreterTable(
3371 set_allocation_sites_scratchpad(
3372 *factory->NewFixedArray(kAllocationSiteScratchpadSize, TENURED));
3373 InitializeAllocationSitesScratchpad();
3375 // Initialize keyed lookup cache.
3376 isolate_->keyed_lookup_cache()->Clear();
3378 // Initialize context slot cache.
3379 isolate_->context_slot_cache()->Clear();
3381 // Initialize descriptor cache.
3382 isolate_->descriptor_lookup_cache()->Clear();
3384 // Initialize compilation cache.
3385 isolate_->compilation_cache()->Clear();
3389 void Heap::AddPrivateGlobalSymbols(Handle<Object> private_intern_table) {
3390 #define ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE(name_arg) \
3392 Handle<Symbol> symbol(Symbol::cast(roots_[k##name_arg##RootIndex])); \
3393 Handle<String> name_arg##d(String::cast(symbol->name())); \
3394 JSObject::AddProperty(Handle<JSObject>::cast(private_intern_table), \
3395 name_arg##d, symbol, NONE); \
3397 PRIVATE_SYMBOL_LIST(ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE)
3398 #undef ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE
3402 bool Heap::RootCanBeWrittenAfterInitialization(Heap::RootListIndex root_index) {
3403 switch (root_index) {
3404 case kStoreBufferTopRootIndex:
3405 case kNumberStringCacheRootIndex:
3406 case kInstanceofCacheFunctionRootIndex:
3407 case kInstanceofCacheMapRootIndex:
3408 case kInstanceofCacheAnswerRootIndex:
3409 case kCodeStubsRootIndex:
3410 case kNonMonomorphicCacheRootIndex:
3411 case kPolymorphicCodeCacheRootIndex:
3412 case kEmptyScriptRootIndex:
3413 case kSymbolRegistryRootIndex:
3414 case kMaterializedObjectsRootIndex:
3415 case kAllocationSitesScratchpadRootIndex:
3416 case kMicrotaskQueueRootIndex:
3417 case kDetachedContextsRootIndex:
3418 case kWeakObjectToCodeTableRootIndex:
3419 case kRetainedMapsRootIndex:
3420 case kWeakStackTraceListRootIndex:
3422 #define SMI_ENTRY(type, name, Name) case k##Name##RootIndex:
3423 SMI_ROOT_LIST(SMI_ENTRY)
3426 case kStringTableRootIndex:
3435 bool Heap::RootCanBeTreatedAsConstant(RootListIndex root_index) {
3436 return !RootCanBeWrittenAfterInitialization(root_index) &&
3437 !InNewSpace(roots_array_start()[root_index]);
3441 Object* RegExpResultsCache::Lookup(Heap* heap, String* key_string,
3442 Object* key_pattern, ResultsCacheType type) {
3444 if (!key_string->IsInternalizedString()) return Smi::FromInt(0);
3445 if (type == STRING_SPLIT_SUBSTRINGS) {
3446 DCHECK(key_pattern->IsString());
3447 if (!key_pattern->IsInternalizedString()) return Smi::FromInt(0);
3448 cache = heap->string_split_cache();
3450 DCHECK(type == REGEXP_MULTIPLE_INDICES);
3451 DCHECK(key_pattern->IsFixedArray());
3452 cache = heap->regexp_multiple_cache();
3455 uint32_t hash = key_string->Hash();
3456 uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
3457 ~(kArrayEntriesPerCacheEntry - 1));
3458 if (cache->get(index + kStringOffset) == key_string &&
3459 cache->get(index + kPatternOffset) == key_pattern) {
3460 return cache->get(index + kArrayOffset);
3463 ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
3464 if (cache->get(index + kStringOffset) == key_string &&
3465 cache->get(index + kPatternOffset) == key_pattern) {
3466 return cache->get(index + kArrayOffset);
3468 return Smi::FromInt(0);
3472 void RegExpResultsCache::Enter(Isolate* isolate, Handle<String> key_string,
3473 Handle<Object> key_pattern,
3474 Handle<FixedArray> value_array,
3475 ResultsCacheType type) {
3476 Factory* factory = isolate->factory();
3477 Handle<FixedArray> cache;
3478 if (!key_string->IsInternalizedString()) return;
3479 if (type == STRING_SPLIT_SUBSTRINGS) {
3480 DCHECK(key_pattern->IsString());
3481 if (!key_pattern->IsInternalizedString()) return;
3482 cache = factory->string_split_cache();
3484 DCHECK(type == REGEXP_MULTIPLE_INDICES);
3485 DCHECK(key_pattern->IsFixedArray());
3486 cache = factory->regexp_multiple_cache();
3489 uint32_t hash = key_string->Hash();
3490 uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
3491 ~(kArrayEntriesPerCacheEntry - 1));
3492 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
3493 cache->set(index + kStringOffset, *key_string);
3494 cache->set(index + kPatternOffset, *key_pattern);
3495 cache->set(index + kArrayOffset, *value_array);
3498 ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
3499 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
3500 cache->set(index2 + kStringOffset, *key_string);
3501 cache->set(index2 + kPatternOffset, *key_pattern);
3502 cache->set(index2 + kArrayOffset, *value_array);
3504 cache->set(index2 + kStringOffset, Smi::FromInt(0));
3505 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
3506 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
3507 cache->set(index + kStringOffset, *key_string);
3508 cache->set(index + kPatternOffset, *key_pattern);
3509 cache->set(index + kArrayOffset, *value_array);
3512 // If the array is a reasonably short list of substrings, convert it into a
3513 // list of internalized strings.
3514 if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) {
3515 for (int i = 0; i < value_array->length(); i++) {
3516 Handle<String> str(String::cast(value_array->get(i)), isolate);
3517 Handle<String> internalized_str = factory->InternalizeString(str);
3518 value_array->set(i, *internalized_str);
3521 // Convert backing store to a copy-on-write array.
3522 value_array->set_map_no_write_barrier(*factory->fixed_cow_array_map());
3526 void RegExpResultsCache::Clear(FixedArray* cache) {
3527 for (int i = 0; i < kRegExpResultsCacheSize; i++) {
3528 cache->set(i, Smi::FromInt(0));
3533 int Heap::FullSizeNumberStringCacheLength() {
3534 // Compute the size of the number string cache based on the max newspace size.
3535 // The number string cache has a minimum size based on twice the initial cache
3536 // size to ensure that it is bigger after being made 'full size'.
3537 int number_string_cache_size = max_semi_space_size_ / 512;
3538 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
3539 Min(0x4000, number_string_cache_size));
3540 // There is a string and a number per entry so the length is twice the number
3542 return number_string_cache_size * 2;
3546 void Heap::FlushNumberStringCache() {
3547 // Flush the number to string cache.
3548 int len = number_string_cache()->length();
3549 for (int i = 0; i < len; i++) {
3550 number_string_cache()->set_undefined(i);
3555 void Heap::FlushAllocationSitesScratchpad() {
3556 for (int i = 0; i < allocation_sites_scratchpad_length_; i++) {
3557 allocation_sites_scratchpad()->set_undefined(i);
3559 allocation_sites_scratchpad_length_ = 0;
3563 void Heap::InitializeAllocationSitesScratchpad() {
3564 DCHECK(allocation_sites_scratchpad()->length() ==
3565 kAllocationSiteScratchpadSize);
3566 for (int i = 0; i < kAllocationSiteScratchpadSize; i++) {
3567 allocation_sites_scratchpad()->set_undefined(i);
3572 void Heap::AddAllocationSiteToScratchpad(AllocationSite* site,
3573 ScratchpadSlotMode mode) {
3574 if (allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize) {
3575 // We cannot use the normal write-barrier because slots need to be
3576 // recorded with non-incremental marking as well. We have to explicitly
3577 // record the slot to take evacuation candidates into account.
3578 allocation_sites_scratchpad()->set(allocation_sites_scratchpad_length_,
3579 site, SKIP_WRITE_BARRIER);
3580 Object** slot = allocation_sites_scratchpad()->RawFieldOfElementAt(
3581 allocation_sites_scratchpad_length_);
3583 if (mode == RECORD_SCRATCHPAD_SLOT) {
3584 // We need to allow slots buffer overflow here since the evacuation
3585 // candidates are not part of the global list of old space pages and
3586 // releasing an evacuation candidate due to a slots buffer overflow
3587 // results in lost pages.
3588 mark_compact_collector()->RecordSlot(allocation_sites_scratchpad(), slot,
3589 *slot, SlotsBuffer::IGNORE_OVERFLOW);
3591 allocation_sites_scratchpad_length_++;
3597 Map* Heap::MapForFixedTypedArray(ExternalArrayType array_type) {
3598 return Map::cast(roots_[RootIndexForFixedTypedArray(array_type)]);
3602 Heap::RootListIndex Heap::RootIndexForFixedTypedArray(
3603 ExternalArrayType array_type) {
3604 switch (array_type) {
3605 #define ARRAY_TYPE_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \
3606 case kExternal##Type##Array: \
3607 return kFixed##Type##ArrayMapRootIndex;
3609 TYPED_ARRAYS(ARRAY_TYPE_TO_ROOT_INDEX)
3610 #undef ARRAY_TYPE_TO_ROOT_INDEX
3614 return kUndefinedValueRootIndex;
3619 Heap::RootListIndex Heap::RootIndexForEmptyFixedTypedArray(
3620 ElementsKind elementsKind) {
3621 switch (elementsKind) {
3622 #define ELEMENT_KIND_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \
3623 case TYPE##_ELEMENTS: \
3624 return kEmptyFixed##Type##ArrayRootIndex;
3626 TYPED_ARRAYS(ELEMENT_KIND_TO_ROOT_INDEX)
3627 #undef ELEMENT_KIND_TO_ROOT_INDEX
3630 return kUndefinedValueRootIndex;
3635 FixedTypedArrayBase* Heap::EmptyFixedTypedArrayForMap(Map* map) {
3636 return FixedTypedArrayBase::cast(
3637 roots_[RootIndexForEmptyFixedTypedArray(map->elements_kind())]);
3641 AllocationResult Heap::AllocateForeign(Address address,
3642 PretenureFlag pretenure) {
3643 // Statically ensure that it is safe to allocate foreigns in paged spaces.
3644 STATIC_ASSERT(Foreign::kSize <= Page::kMaxRegularHeapObjectSize);
3645 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
3647 AllocationResult allocation = Allocate(foreign_map(), space);
3648 if (!allocation.To(&result)) return allocation;
3649 result->set_foreign_address(address);
3654 AllocationResult Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3655 if (length < 0 || length > ByteArray::kMaxLength) {
3656 v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
3658 int size = ByteArray::SizeFor(length);
3659 AllocationSpace space = SelectSpace(size, pretenure);
3662 AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
3663 if (!allocation.To(&result)) return allocation;
3666 result->set_map_no_write_barrier(byte_array_map());
3667 ByteArray::cast(result)->set_length(length);
3672 AllocationResult Heap::AllocateBytecodeArray(int length,
3673 const byte* const raw_bytecodes,
3675 if (length < 0 || length > BytecodeArray::kMaxLength) {
3676 v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
3679 int size = BytecodeArray::SizeFor(length);
3682 AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3683 if (!allocation.To(&result)) return allocation;
3686 result->set_map_no_write_barrier(bytecode_array_map());
3687 BytecodeArray* instance = BytecodeArray::cast(result);
3688 instance->set_length(length);
3689 instance->set_frame_size(frame_size);
3690 CopyBytes(instance->GetFirstBytecodeAddress(), raw_bytecodes, length);
3696 void Heap::CreateFillerObjectAt(Address addr, int size) {
3697 if (size == 0) return;
3698 HeapObject* filler = HeapObject::FromAddress(addr);
3699 if (size == kPointerSize) {
3700 filler->set_map_no_write_barrier(raw_unchecked_one_pointer_filler_map());
3701 } else if (size == 2 * kPointerSize) {
3702 filler->set_map_no_write_barrier(raw_unchecked_two_pointer_filler_map());
3704 filler->set_map_no_write_barrier(raw_unchecked_free_space_map());
3705 FreeSpace::cast(filler)->nobarrier_set_size(size);
3707 // At this point, we may be deserializing the heap from a snapshot, and
3708 // none of the maps have been created yet and are NULL.
3709 DCHECK((filler->map() == NULL && !deserialization_complete_) ||
3710 filler->map()->IsMap());
3714 bool Heap::CanMoveObjectStart(HeapObject* object) {
3715 Address address = object->address();
3717 if (lo_space()->Contains(object)) return false;
3719 Page* page = Page::FromAddress(address);
3720 // We can move the object start if:
3721 // (1) the object is not in old space,
3722 // (2) the page of the object was already swept,
3723 // (3) the page was already concurrently swept. This case is an optimization
3724 // for concurrent sweeping. The WasSwept predicate for concurrently swept
3725 // pages is set after sweeping all pages.
3726 return !InOldSpace(address) || page->WasSwept() || page->SweepingCompleted();
3730 void Heap::AdjustLiveBytes(HeapObject* object, int by, InvocationMode mode) {
3731 if (incremental_marking()->IsMarking() &&
3732 Marking::IsBlack(Marking::MarkBitFrom(object->address()))) {
3733 if (mode == SEQUENTIAL_TO_SWEEPER) {
3734 MemoryChunk::IncrementLiveBytesFromGC(object, by);
3736 MemoryChunk::IncrementLiveBytesFromMutator(object, by);
3742 FixedArrayBase* Heap::LeftTrimFixedArray(FixedArrayBase* object,
3743 int elements_to_trim) {
3744 DCHECK(!object->IsFixedTypedArrayBase());
3745 const int element_size = object->IsFixedArray() ? kPointerSize : kDoubleSize;
3746 const int bytes_to_trim = elements_to_trim * element_size;
3747 Map* map = object->map();
3749 // For now this trick is only applied to objects in new and paged space.
3750 // In large object space the object's start must coincide with chunk
3751 // and thus the trick is just not applicable.
3752 DCHECK(!lo_space()->Contains(object));
3753 DCHECK(object->map() != fixed_cow_array_map());
3755 STATIC_ASSERT(FixedArrayBase::kMapOffset == 0);
3756 STATIC_ASSERT(FixedArrayBase::kLengthOffset == kPointerSize);
3757 STATIC_ASSERT(FixedArrayBase::kHeaderSize == 2 * kPointerSize);
3759 const int len = object->length();
3760 DCHECK(elements_to_trim <= len);
3762 // Calculate location of new array start.
3763 Address new_start = object->address() + bytes_to_trim;
3765 // Technically in new space this write might be omitted (except for
3766 // debug mode which iterates through the heap), but to play safer
3768 CreateFillerObjectAt(object->address(), bytes_to_trim);
3770 // Initialize header of the trimmed array. Since left trimming is only
3771 // performed on pages which are not concurrently swept creating a filler
3772 // object does not require synchronization.
3773 DCHECK(CanMoveObjectStart(object));
3774 Object** former_start = HeapObject::RawField(object, 0);
3775 int new_start_index = elements_to_trim * (element_size / kPointerSize);
3776 former_start[new_start_index] = map;
3777 former_start[new_start_index + 1] = Smi::FromInt(len - elements_to_trim);
3778 FixedArrayBase* new_object =
3779 FixedArrayBase::cast(HeapObject::FromAddress(new_start));
3781 // Maintain consistency of live bytes during incremental marking
3782 Marking::TransferMark(this, object->address(), new_start);
3783 AdjustLiveBytes(new_object, -bytes_to_trim, Heap::CONCURRENT_TO_SWEEPER);
3785 // Notify the heap profiler of change in object layout.
3786 OnMoveEvent(new_object, object, new_object->Size());
3791 // Force instantiation of templatized method.
3792 template void Heap::RightTrimFixedArray<Heap::SEQUENTIAL_TO_SWEEPER>(
3793 FixedArrayBase*, int);
3794 template void Heap::RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
3795 FixedArrayBase*, int);
3798 template<Heap::InvocationMode mode>
3799 void Heap::RightTrimFixedArray(FixedArrayBase* object, int elements_to_trim) {
3800 const int len = object->length();
3801 DCHECK(elements_to_trim < len);
3804 if (object->IsFixedTypedArrayBase()) {
3805 InstanceType type = object->map()->instance_type();
3807 FixedTypedArrayBase::TypedArraySize(type, len) -
3808 FixedTypedArrayBase::TypedArraySize(type, len - elements_to_trim);
3810 const int element_size =
3811 object->IsFixedArray() ? kPointerSize : kDoubleSize;
3812 bytes_to_trim = elements_to_trim * element_size;
3815 // For now this trick is only applied to objects in new and paged space.
3816 DCHECK(object->map() != fixed_cow_array_map());
3818 if (bytes_to_trim == 0) {
3819 // No need to create filler and update live bytes counters, just initialize
3820 // header of the trimmed array.
3821 object->synchronized_set_length(len - elements_to_trim);
3825 // Calculate location of new array end.
3826 Address new_end = object->address() + object->Size() - bytes_to_trim;
3828 // Technically in new space this write might be omitted (except for
3829 // debug mode which iterates through the heap), but to play safer
3831 // We do not create a filler for objects in large object space.
3832 // TODO(hpayer): We should shrink the large object page if the size
3833 // of the object changed significantly.
3834 if (!lo_space()->Contains(object)) {
3835 CreateFillerObjectAt(new_end, bytes_to_trim);
3838 // Initialize header of the trimmed array. We are storing the new length
3839 // using release store after creating a filler for the left-over space to
3840 // avoid races with the sweeper thread.
3841 object->synchronized_set_length(len - elements_to_trim);
3843 // Maintain consistency of live bytes during incremental marking
3844 AdjustLiveBytes(object, -bytes_to_trim, mode);
3846 // Notify the heap profiler of change in object layout. The array may not be
3847 // moved during GC, and size has to be adjusted nevertheless.
3848 HeapProfiler* profiler = isolate()->heap_profiler();
3849 if (profiler->is_tracking_allocations()) {
3850 profiler->UpdateObjectSizeEvent(object->address(), object->Size());
3855 AllocationResult Heap::AllocateFixedTypedArrayWithExternalPointer(
3856 int length, ExternalArrayType array_type, void* external_pointer,
3857 PretenureFlag pretenure) {
3858 int size = FixedTypedArrayBase::kHeaderSize;
3859 AllocationSpace space = SelectSpace(size, pretenure);
3862 AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
3863 if (!allocation.To(&result)) return allocation;
3866 result->set_map_no_write_barrier(MapForFixedTypedArray(array_type));
3867 FixedTypedArrayBase* elements = FixedTypedArrayBase::cast(result);
3868 elements->set_base_pointer(Smi::FromInt(0), SKIP_WRITE_BARRIER);
3869 elements->set_external_pointer(external_pointer, SKIP_WRITE_BARRIER);
3870 elements->set_length(length);
3874 static void ForFixedTypedArray(ExternalArrayType array_type, int* element_size,
3875 ElementsKind* element_kind) {
3876 switch (array_type) {
3877 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
3878 case kExternal##Type##Array: \
3879 *element_size = size; \
3880 *element_kind = TYPE##_ELEMENTS; \
3883 TYPED_ARRAYS(TYPED_ARRAY_CASE)
3884 #undef TYPED_ARRAY_CASE
3887 *element_size = 0; // Bogus
3888 *element_kind = UINT8_ELEMENTS; // Bogus
3894 AllocationResult Heap::AllocateFixedTypedArray(int length,
3895 ExternalArrayType array_type,
3897 PretenureFlag pretenure) {
3899 ElementsKind elements_kind;
3900 ForFixedTypedArray(array_type, &element_size, &elements_kind);
3901 int size = OBJECT_POINTER_ALIGN(length * element_size +
3902 FixedTypedArrayBase::kDataOffset);
3903 AllocationSpace space = SelectSpace(size, pretenure);
3906 AllocationResult allocation = AllocateRaw(
3907 size, space, OLD_SPACE,
3908 array_type == kExternalFloat64Array ? kDoubleAligned : kWordAligned);
3909 if (!allocation.To(&object)) return allocation;
3911 object->set_map_no_write_barrier(MapForFixedTypedArray(array_type));
3912 FixedTypedArrayBase* elements = FixedTypedArrayBase::cast(object);
3913 elements->set_base_pointer(elements, SKIP_WRITE_BARRIER);
3914 elements->set_external_pointer(
3915 ExternalReference::fixed_typed_array_base_data_offset().address(),
3916 SKIP_WRITE_BARRIER);
3917 elements->set_length(length);
3918 if (initialize) memset(elements->DataPtr(), 0, elements->DataSize());
3923 AllocationResult Heap::AllocateCode(int object_size, bool immovable) {
3924 DCHECK(IsAligned(static_cast<intptr_t>(object_size), kCodeAlignment));
3925 AllocationResult allocation =
3926 AllocateRaw(object_size, CODE_SPACE, CODE_SPACE);
3929 if (!allocation.To(&result)) return allocation;
3932 Address address = result->address();
3933 // Code objects which should stay at a fixed address are allocated either
3934 // in the first page of code space (objects on the first page of each space
3935 // are never moved) or in large object space.
3936 if (!code_space_->FirstPage()->Contains(address) &&
3937 MemoryChunk::FromAddress(address)->owner()->identity() != LO_SPACE) {
3938 // Discard the first code allocation, which was on a page where it could
3940 CreateFillerObjectAt(result->address(), object_size);
3941 allocation = lo_space_->AllocateRaw(object_size, EXECUTABLE);
3942 if (!allocation.To(&result)) return allocation;
3943 OnAllocationEvent(result, object_size);
3947 result->set_map_no_write_barrier(code_map());
3948 Code* code = Code::cast(result);
3949 DCHECK(IsAligned(bit_cast<intptr_t>(code->address()), kCodeAlignment));
3950 DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
3951 isolate_->code_range()->contains(code->address()) ||
3952 object_size <= code_space()->AreaSize());
3953 code->set_gc_metadata(Smi::FromInt(0));
3954 code->set_ic_age(global_ic_age_);
3959 AllocationResult Heap::CopyCode(Code* code) {
3960 AllocationResult allocation;
3962 HeapObject* result = NULL;
3963 // Allocate an object the same size as the code object.
3964 int obj_size = code->Size();
3965 allocation = AllocateRaw(obj_size, CODE_SPACE, CODE_SPACE);
3966 if (!allocation.To(&result)) return allocation;
3968 // Copy code object.
3969 Address old_addr = code->address();
3970 Address new_addr = result->address();
3971 CopyBlock(new_addr, old_addr, obj_size);
3972 Code* new_code = Code::cast(result);
3974 // Relocate the copy.
3975 DCHECK(IsAligned(bit_cast<intptr_t>(new_code->address()), kCodeAlignment));
3976 DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
3977 isolate_->code_range()->contains(code->address()) ||
3978 obj_size <= code_space()->AreaSize());
3979 new_code->Relocate(new_addr - old_addr);
3984 AllocationResult Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3985 // Allocate ByteArray before the Code object, so that we do not risk
3986 // leaving uninitialized Code object (and breaking the heap).
3987 ByteArray* reloc_info_array;
3989 AllocationResult allocation =
3990 AllocateByteArray(reloc_info.length(), TENURED);
3991 if (!allocation.To(&reloc_info_array)) return allocation;
3994 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3996 int new_obj_size = Code::SizeFor(new_body_size);
3998 Address old_addr = code->address();
4000 size_t relocation_offset =
4001 static_cast<size_t>(code->instruction_end() - old_addr);
4004 AllocationResult allocation =
4005 AllocateRaw(new_obj_size, CODE_SPACE, CODE_SPACE);
4006 if (!allocation.To(&result)) return allocation;
4008 // Copy code object.
4009 Address new_addr = result->address();
4011 // Copy header and instructions.
4012 CopyBytes(new_addr, old_addr, relocation_offset);
4014 Code* new_code = Code::cast(result);
4015 new_code->set_relocation_info(reloc_info_array);
4017 // Copy patched rinfo.
4018 CopyBytes(new_code->relocation_start(), reloc_info.start(),
4019 static_cast<size_t>(reloc_info.length()));
4021 // Relocate the copy.
4022 DCHECK(IsAligned(bit_cast<intptr_t>(new_code->address()), kCodeAlignment));
4023 DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
4024 isolate_->code_range()->contains(code->address()) ||
4025 new_obj_size <= code_space()->AreaSize());
4027 new_code->Relocate(new_addr - old_addr);
4030 if (FLAG_verify_heap) code->ObjectVerify();
4036 void Heap::InitializeAllocationMemento(AllocationMemento* memento,
4037 AllocationSite* allocation_site) {
4038 memento->set_map_no_write_barrier(allocation_memento_map());
4039 DCHECK(allocation_site->map() == allocation_site_map());
4040 memento->set_allocation_site(allocation_site, SKIP_WRITE_BARRIER);
4041 if (FLAG_allocation_site_pretenuring) {
4042 allocation_site->IncrementMementoCreateCount();
4047 AllocationResult Heap::Allocate(Map* map, AllocationSpace space,
4048 AllocationSite* allocation_site) {
4049 DCHECK(gc_state_ == NOT_IN_GC);
4050 DCHECK(map->instance_type() != MAP_TYPE);
4051 // If allocation failures are disallowed, we may allocate in a different
4052 // space when new space is full and the object is not a large object.
4053 AllocationSpace retry_space = (space != NEW_SPACE) ? space : OLD_SPACE;
4054 int size = map->instance_size();
4055 if (allocation_site != NULL) {
4056 size += AllocationMemento::kSize;
4059 AllocationResult allocation = AllocateRaw(size, space, retry_space);
4060 if (!allocation.To(&result)) return allocation;
4061 // No need for write barrier since object is white and map is in old space.
4062 result->set_map_no_write_barrier(map);
4063 if (allocation_site != NULL) {
4064 AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>(
4065 reinterpret_cast<Address>(result) + map->instance_size());
4066 InitializeAllocationMemento(alloc_memento, allocation_site);
4072 void Heap::InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties,
4074 obj->set_properties(properties);
4075 obj->initialize_elements();
4076 // TODO(1240798): Initialize the object's body using valid initial values
4077 // according to the object's initial map. For example, if the map's
4078 // instance type is JS_ARRAY_TYPE, the length field should be initialized
4079 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
4080 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
4081 // verification code has to cope with (temporarily) invalid objects. See
4082 // for example, JSArray::JSArrayVerify).
4084 // We cannot always fill with one_pointer_filler_map because objects
4085 // created from API functions expect their internal fields to be initialized
4086 // with undefined_value.
4087 // Pre-allocated fields need to be initialized with undefined_value as well
4088 // so that object accesses before the constructor completes (e.g. in the
4089 // debugger) will not cause a crash.
4090 Object* constructor = map->GetConstructor();
4091 if (constructor->IsJSFunction() &&
4092 JSFunction::cast(constructor)->IsInobjectSlackTrackingInProgress()) {
4093 // We might want to shrink the object later.
4094 DCHECK(obj->GetInternalFieldCount() == 0);
4095 filler = Heap::one_pointer_filler_map();
4097 filler = Heap::undefined_value();
4099 obj->InitializeBody(map, Heap::undefined_value(), filler);
4103 AllocationResult Heap::AllocateJSObjectFromMap(
4104 Map* map, PretenureFlag pretenure, AllocationSite* allocation_site) {
4105 // JSFunctions should be allocated using AllocateFunction to be
4106 // properly initialized.
4107 DCHECK(map->instance_type() != JS_FUNCTION_TYPE);
4109 // Both types of global objects should be allocated using
4110 // AllocateGlobalObject to be properly initialized.
4111 DCHECK(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
4112 DCHECK(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
4114 // Allocate the backing storage for the properties.
4115 FixedArray* properties = empty_fixed_array();
4117 // Allocate the JSObject.
4118 int size = map->instance_size();
4119 AllocationSpace space = SelectSpace(size, pretenure);
4121 AllocationResult allocation = Allocate(map, space, allocation_site);
4122 if (!allocation.To(&js_obj)) return allocation;
4124 // Initialize the JSObject.
4125 InitializeJSObjectFromMap(js_obj, properties, map);
4126 DCHECK(js_obj->HasFastElements() || js_obj->HasFixedTypedArrayElements());
4131 AllocationResult Heap::AllocateJSObject(JSFunction* constructor,
4132 PretenureFlag pretenure,
4133 AllocationSite* allocation_site) {
4134 DCHECK(constructor->has_initial_map());
4136 // Allocate the object based on the constructors initial map.
4137 AllocationResult allocation = AllocateJSObjectFromMap(
4138 constructor->initial_map(), pretenure, allocation_site);
4140 // Make sure result is NOT a global object if valid.
4142 DCHECK(!allocation.To(&obj) || !obj->IsGlobalObject());
4148 AllocationResult Heap::CopyJSObject(JSObject* source, AllocationSite* site) {
4150 Map* map = source->map();
4152 // We can only clone normal objects or arrays. Copying anything else
4153 // will break invariants.
4154 CHECK(map->instance_type() == JS_OBJECT_TYPE ||
4155 map->instance_type() == JS_ARRAY_TYPE);
4157 int object_size = map->instance_size();
4160 DCHECK(site == NULL || AllocationSite::CanTrack(map->instance_type()));
4162 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4164 // If we're forced to always allocate, we use the general allocation
4165 // functions which may leave us with an object in old space.
4166 if (always_allocate()) {
4168 AllocationResult allocation =
4169 AllocateRaw(object_size, NEW_SPACE, OLD_SPACE);
4170 if (!allocation.To(&clone)) return allocation;
4172 Address clone_address = clone->address();
4173 CopyBlock(clone_address, source->address(), object_size);
4175 // Update write barrier for all tagged fields that lie beyond the header.
4176 const int start_offset = JSObject::kHeaderSize;
4177 const int end_offset = object_size;
4179 #if V8_DOUBLE_FIELDS_UNBOXING
4180 LayoutDescriptorHelper helper(map);
4181 bool has_only_tagged_fields = helper.all_fields_tagged();
4183 if (!has_only_tagged_fields) {
4184 for (int offset = start_offset; offset < end_offset;) {
4185 int end_of_region_offset;
4186 if (helper.IsTagged(offset, end_offset, &end_of_region_offset)) {
4187 RecordWrites(clone_address, offset,
4188 (end_of_region_offset - offset) / kPointerSize);
4190 offset = end_of_region_offset;
4194 // Object has only tagged fields.
4195 RecordWrites(clone_address, start_offset,
4196 (end_offset - start_offset) / kPointerSize);
4197 #if V8_DOUBLE_FIELDS_UNBOXING
4202 wb_mode = SKIP_WRITE_BARRIER;
4205 int adjusted_object_size =
4206 site != NULL ? object_size + AllocationMemento::kSize : object_size;
4207 AllocationResult allocation =
4208 AllocateRaw(adjusted_object_size, NEW_SPACE, NEW_SPACE);
4209 if (!allocation.To(&clone)) return allocation;
4211 SLOW_DCHECK(InNewSpace(clone));
4212 // Since we know the clone is allocated in new space, we can copy
4213 // the contents without worrying about updating the write barrier.
4214 CopyBlock(clone->address(), source->address(), object_size);
4217 AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>(
4218 reinterpret_cast<Address>(clone) + object_size);
4219 InitializeAllocationMemento(alloc_memento, site);
4223 SLOW_DCHECK(JSObject::cast(clone)->GetElementsKind() ==
4224 source->GetElementsKind());
4225 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4226 FixedArray* properties = FixedArray::cast(source->properties());
4227 // Update elements if necessary.
4228 if (elements->length() > 0) {
4229 FixedArrayBase* elem;
4231 AllocationResult allocation;
4232 if (elements->map() == fixed_cow_array_map()) {
4233 allocation = FixedArray::cast(elements);
4234 } else if (source->HasFastDoubleElements()) {
4235 allocation = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4237 allocation = CopyFixedArray(FixedArray::cast(elements));
4239 if (!allocation.To(&elem)) return allocation;
4241 JSObject::cast(clone)->set_elements(elem, wb_mode);
4243 // Update properties if necessary.
4244 if (properties->length() > 0) {
4247 AllocationResult allocation = CopyFixedArray(properties);
4248 if (!allocation.To(&prop)) return allocation;
4250 JSObject::cast(clone)->set_properties(prop, wb_mode);
4252 // Return the new clone.
4257 static inline void WriteOneByteData(Vector<const char> vector, uint8_t* chars,
4259 // Only works for one byte strings.
4260 DCHECK(vector.length() == len);
4261 MemCopy(chars, vector.start(), len);
4264 static inline void WriteTwoByteData(Vector<const char> vector, uint16_t* chars,
4266 const uint8_t* stream = reinterpret_cast<const uint8_t*>(vector.start());
4267 size_t stream_length = vector.length();
4268 while (stream_length != 0) {
4269 size_t consumed = 0;
4270 uint32_t c = unibrow::Utf8::ValueOf(stream, stream_length, &consumed);
4271 DCHECK(c != unibrow::Utf8::kBadChar);
4272 DCHECK(consumed <= stream_length);
4273 stream_length -= consumed;
4275 if (c > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4278 *chars++ = unibrow::Utf16::LeadSurrogate(c);
4279 *chars++ = unibrow::Utf16::TrailSurrogate(c);
4286 DCHECK(stream_length == 0);
4291 static inline void WriteOneByteData(String* s, uint8_t* chars, int len) {
4292 DCHECK(s->length() == len);
4293 String::WriteToFlat(s, chars, 0, len);
4297 static inline void WriteTwoByteData(String* s, uint16_t* chars, int len) {
4298 DCHECK(s->length() == len);
4299 String::WriteToFlat(s, chars, 0, len);
4303 template <bool is_one_byte, typename T>
4304 AllocationResult Heap::AllocateInternalizedStringImpl(T t, int chars,
4305 uint32_t hash_field) {
4307 // Compute map and object size.
4311 DCHECK_LE(0, chars);
4312 DCHECK_GE(String::kMaxLength, chars);
4314 map = one_byte_internalized_string_map();
4315 size = SeqOneByteString::SizeFor(chars);
4317 map = internalized_string_map();
4318 size = SeqTwoByteString::SizeFor(chars);
4320 AllocationSpace space = SelectSpace(size, TENURED);
4325 AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4326 if (!allocation.To(&result)) return allocation;
4329 result->set_map_no_write_barrier(map);
4330 // Set length and hash fields of the allocated string.
4331 String* answer = String::cast(result);
4332 answer->set_length(chars);
4333 answer->set_hash_field(hash_field);
4335 DCHECK_EQ(size, answer->Size());
4338 WriteOneByteData(t, SeqOneByteString::cast(answer)->GetChars(), chars);
4340 WriteTwoByteData(t, SeqTwoByteString::cast(answer)->GetChars(), chars);
4346 // Need explicit instantiations.
4347 template AllocationResult Heap::AllocateInternalizedStringImpl<true>(String*,
4350 template AllocationResult Heap::AllocateInternalizedStringImpl<false>(String*,
4353 template AllocationResult Heap::AllocateInternalizedStringImpl<false>(
4354 Vector<const char>, int, uint32_t);
4357 AllocationResult Heap::AllocateRawOneByteString(int length,
4358 PretenureFlag pretenure) {
4359 DCHECK_LE(0, length);
4360 DCHECK_GE(String::kMaxLength, length);
4361 int size = SeqOneByteString::SizeFor(length);
4362 DCHECK(size <= SeqOneByteString::kMaxSize);
4363 AllocationSpace space = SelectSpace(size, pretenure);
4367 AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4368 if (!allocation.To(&result)) return allocation;
4371 // Partially initialize the object.
4372 result->set_map_no_write_barrier(one_byte_string_map());
4373 String::cast(result)->set_length(length);
4374 String::cast(result)->set_hash_field(String::kEmptyHashField);
4375 DCHECK_EQ(size, HeapObject::cast(result)->Size());
4381 AllocationResult Heap::AllocateRawTwoByteString(int length,
4382 PretenureFlag pretenure) {
4383 DCHECK_LE(0, length);
4384 DCHECK_GE(String::kMaxLength, length);
4385 int size = SeqTwoByteString::SizeFor(length);
4386 DCHECK(size <= SeqTwoByteString::kMaxSize);
4387 AllocationSpace space = SelectSpace(size, pretenure);
4391 AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4392 if (!allocation.To(&result)) return allocation;
4395 // Partially initialize the object.
4396 result->set_map_no_write_barrier(string_map());
4397 String::cast(result)->set_length(length);
4398 String::cast(result)->set_hash_field(String::kEmptyHashField);
4399 DCHECK_EQ(size, HeapObject::cast(result)->Size());
4404 AllocationResult Heap::AllocateEmptyFixedArray() {
4405 int size = FixedArray::SizeFor(0);
4408 AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
4409 if (!allocation.To(&result)) return allocation;
4411 // Initialize the object.
4412 result->set_map_no_write_barrier(fixed_array_map());
4413 FixedArray::cast(result)->set_length(0);
4418 AllocationResult Heap::CopyAndTenureFixedCOWArray(FixedArray* src) {
4419 if (!InNewSpace(src)) {
4423 int len = src->length();
4426 AllocationResult allocation = AllocateRawFixedArray(len, TENURED);
4427 if (!allocation.To(&obj)) return allocation;
4429 obj->set_map_no_write_barrier(fixed_array_map());
4430 FixedArray* result = FixedArray::cast(obj);
4431 result->set_length(len);
4433 // Copy the content.
4434 DisallowHeapAllocation no_gc;
4435 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4436 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4438 // TODO(mvstanton): The map is set twice because of protection against calling
4439 // set() on a COW FixedArray. Issue v8:3221 created to track this, and
4440 // we might then be able to remove this whole method.
4441 HeapObject::cast(obj)->set_map_no_write_barrier(fixed_cow_array_map());
4446 AllocationResult Heap::AllocateEmptyFixedTypedArray(
4447 ExternalArrayType array_type) {
4448 return AllocateFixedTypedArray(0, array_type, false, TENURED);
4452 AllocationResult Heap::CopyFixedArrayAndGrow(FixedArray* src, int grow_by,
4453 PretenureFlag pretenure) {
4454 int old_len = src->length();
4455 int new_len = old_len + grow_by;
4456 DCHECK(new_len >= old_len);
4459 AllocationResult allocation = AllocateRawFixedArray(new_len, pretenure);
4460 if (!allocation.To(&obj)) return allocation;
4462 obj->set_map_no_write_barrier(fixed_array_map());
4463 FixedArray* result = FixedArray::cast(obj);
4464 result->set_length(new_len);
4466 // Copy the content.
4467 DisallowHeapAllocation no_gc;
4468 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4469 for (int i = 0; i < old_len; i++) result->set(i, src->get(i), mode);
4470 MemsetPointer(result->data_start() + old_len, undefined_value(), grow_by);
4475 AllocationResult Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4476 int len = src->length();
4479 AllocationResult allocation = AllocateRawFixedArray(len, NOT_TENURED);
4480 if (!allocation.To(&obj)) return allocation;
4482 if (InNewSpace(obj)) {
4483 obj->set_map_no_write_barrier(map);
4484 CopyBlock(obj->address() + kPointerSize, src->address() + kPointerSize,
4485 FixedArray::SizeFor(len) - kPointerSize);
4488 obj->set_map_no_write_barrier(map);
4489 FixedArray* result = FixedArray::cast(obj);
4490 result->set_length(len);
4492 // Copy the content.
4493 DisallowHeapAllocation no_gc;
4494 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4495 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4500 AllocationResult Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4502 int len = src->length();
4505 AllocationResult allocation = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4506 if (!allocation.To(&obj)) return allocation;
4508 obj->set_map_no_write_barrier(map);
4509 CopyBlock(obj->address() + FixedDoubleArray::kLengthOffset,
4510 src->address() + FixedDoubleArray::kLengthOffset,
4511 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4516 AllocationResult Heap::AllocateRawFixedArray(int length,
4517 PretenureFlag pretenure) {
4518 if (length < 0 || length > FixedArray::kMaxLength) {
4519 v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
4521 int size = FixedArray::SizeFor(length);
4522 AllocationSpace space = SelectSpace(size, pretenure);
4524 return AllocateRaw(size, space, OLD_SPACE);
4528 AllocationResult Heap::AllocateFixedArrayWithFiller(int length,
4529 PretenureFlag pretenure,
4531 DCHECK(length >= 0);
4532 DCHECK(empty_fixed_array()->IsFixedArray());
4533 if (length == 0) return empty_fixed_array();
4535 DCHECK(!InNewSpace(filler));
4536 HeapObject* result = nullptr;
4538 AllocationResult allocation = AllocateRawFixedArray(length, pretenure);
4539 if (!allocation.To(&result)) return allocation;
4542 result->set_map_no_write_barrier(fixed_array_map());
4543 FixedArray* array = FixedArray::cast(result);
4544 array->set_length(length);
4545 MemsetPointer(array->data_start(), filler, length);
4550 AllocationResult Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4551 return AllocateFixedArrayWithFiller(length, pretenure, undefined_value());
4555 AllocationResult Heap::AllocateUninitializedFixedArray(int length) {
4556 if (length == 0) return empty_fixed_array();
4560 AllocationResult allocation = AllocateRawFixedArray(length, NOT_TENURED);
4561 if (!allocation.To(&obj)) return allocation;
4564 obj->set_map_no_write_barrier(fixed_array_map());
4565 FixedArray::cast(obj)->set_length(length);
4570 AllocationResult Heap::AllocateUninitializedFixedDoubleArray(
4571 int length, PretenureFlag pretenure) {
4572 if (length == 0) return empty_fixed_array();
4574 HeapObject* elements;
4575 AllocationResult allocation = AllocateRawFixedDoubleArray(length, pretenure);
4576 if (!allocation.To(&elements)) return allocation;
4578 elements->set_map_no_write_barrier(fixed_double_array_map());
4579 FixedDoubleArray::cast(elements)->set_length(length);
4584 AllocationResult Heap::AllocateRawFixedDoubleArray(int length,
4585 PretenureFlag pretenure) {
4586 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4587 v8::internal::Heap::FatalProcessOutOfMemory("invalid array length",
4590 int size = FixedDoubleArray::SizeFor(length);
4591 AllocationSpace space = SelectSpace(size, pretenure);
4595 AllocationResult allocation =
4596 AllocateRaw(size, space, OLD_SPACE, kDoubleAligned);
4597 if (!allocation.To(&object)) return allocation;
4604 AllocationResult Heap::AllocateSymbol() {
4605 // Statically ensure that it is safe to allocate symbols in paged spaces.
4606 STATIC_ASSERT(Symbol::kSize <= Page::kMaxRegularHeapObjectSize);
4608 HeapObject* result = NULL;
4609 AllocationResult allocation =
4610 AllocateRaw(Symbol::kSize, OLD_SPACE, OLD_SPACE);
4611 if (!allocation.To(&result)) return allocation;
4613 result->set_map_no_write_barrier(symbol_map());
4615 // Generate a random hash value.
4619 hash = isolate()->random_number_generator()->NextInt() & Name::kHashBitMask;
4621 } while (hash == 0 && attempts < 30);
4622 if (hash == 0) hash = 1; // never return 0
4624 Symbol::cast(result)
4625 ->set_hash_field(Name::kIsNotArrayIndexMask | (hash << Name::kHashShift));
4626 Symbol::cast(result)->set_name(undefined_value());
4627 Symbol::cast(result)->set_flags(Smi::FromInt(0));
4629 DCHECK(!Symbol::cast(result)->is_private());
4634 AllocationResult Heap::AllocateStruct(InstanceType type) {
4637 #define MAKE_CASE(NAME, Name, name) \
4639 map = name##_map(); \
4641 STRUCT_LIST(MAKE_CASE)
4647 int size = map->instance_size();
4648 AllocationSpace space = SelectSpace(size, TENURED);
4651 AllocationResult allocation = Allocate(map, space);
4652 if (!allocation.To(&result)) return allocation;
4654 result->InitializeBody(size);
4659 bool Heap::IsHeapIterable() {
4660 // TODO(hpayer): This function is not correct. Allocation folding in old
4661 // space breaks the iterability.
4662 return new_space_top_after_last_gc_ == new_space()->top();
4666 void Heap::MakeHeapIterable() {
4667 DCHECK(AllowHeapAllocation::IsAllowed());
4668 if (!IsHeapIterable()) {
4669 CollectAllGarbage(kMakeHeapIterableMask, "Heap::MakeHeapIterable");
4671 if (mark_compact_collector()->sweeping_in_progress()) {
4672 mark_compact_collector()->EnsureSweepingCompleted();
4674 DCHECK(IsHeapIterable());
4678 static double ComputeMutatorUtilization(double mutator_speed, double gc_speed) {
4679 const double kMinMutatorUtilization = 0.0;
4680 const double kConservativeGcSpeedInBytesPerMillisecond = 200000;
4681 if (mutator_speed == 0) return kMinMutatorUtilization;
4682 if (gc_speed == 0) gc_speed = kConservativeGcSpeedInBytesPerMillisecond;
4684 // mutator_utilization = mutator_time / (mutator_time + gc_time)
4685 // mutator_time = 1 / mutator_speed
4686 // gc_time = 1 / gc_speed
4687 // mutator_utilization = (1 / mutator_speed) /
4688 // (1 / mutator_speed + 1 / gc_speed)
4689 // mutator_utilization = gc_speed / (mutator_speed + gc_speed)
4690 return gc_speed / (mutator_speed + gc_speed);
4694 double Heap::YoungGenerationMutatorUtilization() {
4695 double mutator_speed = static_cast<double>(
4696 tracer()->NewSpaceAllocationThroughputInBytesPerMillisecond());
4697 double gc_speed = static_cast<double>(
4698 tracer()->ScavengeSpeedInBytesPerMillisecond(kForSurvivedObjects));
4699 double result = ComputeMutatorUtilization(mutator_speed, gc_speed);
4700 if (FLAG_trace_mutator_utilization) {
4701 PrintIsolate(isolate(),
4702 "Young generation mutator utilization = %.3f ("
4703 "mutator_speed=%.f, gc_speed=%.f)\n",
4704 result, mutator_speed, gc_speed);
4710 double Heap::OldGenerationMutatorUtilization() {
4711 double mutator_speed = static_cast<double>(
4712 tracer()->OldGenerationAllocationThroughputInBytesPerMillisecond());
4713 double gc_speed = static_cast<double>(
4714 tracer()->CombinedMarkCompactSpeedInBytesPerMillisecond());
4715 double result = ComputeMutatorUtilization(mutator_speed, gc_speed);
4716 if (FLAG_trace_mutator_utilization) {
4717 PrintIsolate(isolate(),
4718 "Old generation mutator utilization = %.3f ("
4719 "mutator_speed=%.f, gc_speed=%.f)\n",
4720 result, mutator_speed, gc_speed);
4726 bool Heap::HasLowYoungGenerationAllocationRate() {
4727 const double high_mutator_utilization = 0.993;
4728 return YoungGenerationMutatorUtilization() > high_mutator_utilization;
4732 bool Heap::HasLowOldGenerationAllocationRate() {
4733 const double high_mutator_utilization = 0.993;
4734 return OldGenerationMutatorUtilization() > high_mutator_utilization;
4738 bool Heap::HasLowAllocationRate() {
4739 return HasLowYoungGenerationAllocationRate() &&
4740 HasLowOldGenerationAllocationRate();
4744 bool Heap::HasHighFragmentation() {
4745 intptr_t used = PromotedSpaceSizeOfObjects();
4746 intptr_t committed = CommittedOldGenerationMemory();
4747 return HasHighFragmentation(used, committed);
4751 bool Heap::HasHighFragmentation(intptr_t used, intptr_t committed) {
4752 const intptr_t kSlack = 16 * MB;
4753 // Fragmentation is high if committed > 2 * used + kSlack.
4754 // Rewrite the exression to avoid overflow.
4755 return committed - used > used + kSlack;
4759 void Heap::ReduceNewSpaceSize() {
4760 // TODO(ulan): Unify this constant with the similar constant in
4761 // GCIdleTimeHandler once the change is merged to 4.5.
4762 static const size_t kLowAllocationThroughput = 1000;
4763 size_t allocation_throughput =
4764 tracer()->CurrentAllocationThroughputInBytesPerMillisecond();
4765 if (FLAG_predictable || allocation_throughput == 0) return;
4766 if (allocation_throughput < kLowAllocationThroughput) {
4767 new_space_.Shrink();
4768 UncommitFromSpace();
4773 void Heap::FinalizeIncrementalMarkingIfComplete(const char* comment) {
4774 if (FLAG_overapproximate_weak_closure &&
4775 (incremental_marking()->IsReadyToOverApproximateWeakClosure() ||
4776 (!incremental_marking()->weak_closure_was_overapproximated() &&
4777 mark_compact_collector_.marking_deque()->IsEmpty()))) {
4778 OverApproximateWeakClosure(comment);
4779 } else if (incremental_marking()->IsComplete() ||
4780 (mark_compact_collector_.marking_deque()->IsEmpty())) {
4781 CollectAllGarbage(kNoGCFlags, comment);
4786 bool Heap::TryFinalizeIdleIncrementalMarking(
4787 double idle_time_in_ms, size_t size_of_objects,
4788 size_t final_incremental_mark_compact_speed_in_bytes_per_ms) {
4789 if (FLAG_overapproximate_weak_closure &&
4790 (incremental_marking()->IsReadyToOverApproximateWeakClosure() ||
4791 (!incremental_marking()->weak_closure_was_overapproximated() &&
4792 mark_compact_collector_.marking_deque()->IsEmpty() &&
4793 gc_idle_time_handler_.ShouldDoOverApproximateWeakClosure(
4794 static_cast<size_t>(idle_time_in_ms))))) {
4795 OverApproximateWeakClosure(
4796 "Idle notification: overapproximate weak closure");
4798 } else if (incremental_marking()->IsComplete() ||
4799 (mark_compact_collector_.marking_deque()->IsEmpty() &&
4800 gc_idle_time_handler_.ShouldDoFinalIncrementalMarkCompact(
4801 static_cast<size_t>(idle_time_in_ms), size_of_objects,
4802 final_incremental_mark_compact_speed_in_bytes_per_ms))) {
4803 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4810 GCIdleTimeHandler::HeapState Heap::ComputeHeapState() {
4811 GCIdleTimeHandler::HeapState heap_state;
4812 heap_state.contexts_disposed = contexts_disposed_;
4813 heap_state.contexts_disposal_rate =
4814 tracer()->ContextDisposalRateInMilliseconds();
4815 heap_state.size_of_objects = static_cast<size_t>(SizeOfObjects());
4816 heap_state.incremental_marking_stopped = incremental_marking()->IsStopped();
4817 heap_state.sweeping_in_progress =
4818 mark_compact_collector()->sweeping_in_progress();
4819 heap_state.sweeping_completed =
4820 mark_compact_collector()->IsSweepingCompleted();
4821 heap_state.mark_compact_speed_in_bytes_per_ms =
4822 static_cast<size_t>(tracer()->MarkCompactSpeedInBytesPerMillisecond());
4823 heap_state.incremental_marking_speed_in_bytes_per_ms = static_cast<size_t>(
4824 tracer()->IncrementalMarkingSpeedInBytesPerMillisecond());
4825 heap_state.final_incremental_mark_compact_speed_in_bytes_per_ms =
4826 static_cast<size_t>(
4827 tracer()->FinalIncrementalMarkCompactSpeedInBytesPerMillisecond());
4828 heap_state.scavenge_speed_in_bytes_per_ms =
4829 static_cast<size_t>(tracer()->ScavengeSpeedInBytesPerMillisecond());
4830 heap_state.used_new_space_size = new_space_.Size();
4831 heap_state.new_space_capacity = new_space_.Capacity();
4832 heap_state.new_space_allocation_throughput_in_bytes_per_ms =
4833 tracer()->NewSpaceAllocationThroughputInBytesPerMillisecond();
4838 double Heap::AdvanceIncrementalMarking(
4839 intptr_t step_size_in_bytes, double deadline_in_ms,
4840 IncrementalMarking::StepActions step_actions) {
4841 DCHECK(!incremental_marking()->IsStopped());
4843 if (step_size_in_bytes == 0) {
4844 step_size_in_bytes = GCIdleTimeHandler::EstimateMarkingStepSize(
4845 static_cast<size_t>(GCIdleTimeHandler::kIncrementalMarkingStepTimeInMs),
4846 static_cast<size_t>(
4847 tracer()->FinalIncrementalMarkCompactSpeedInBytesPerMillisecond()));
4850 double remaining_time_in_ms = 0.0;
4852 incremental_marking()->Step(
4853 step_size_in_bytes, step_actions.completion_action,
4854 step_actions.force_marking, step_actions.force_completion);
4855 remaining_time_in_ms = deadline_in_ms - MonotonicallyIncreasingTimeInMs();
4856 } while (remaining_time_in_ms >=
4857 2.0 * GCIdleTimeHandler::kIncrementalMarkingStepTimeInMs &&
4858 !incremental_marking()->IsComplete() &&
4859 !mark_compact_collector_.marking_deque()->IsEmpty());
4860 return remaining_time_in_ms;
4864 bool Heap::PerformIdleTimeAction(GCIdleTimeAction action,
4865 GCIdleTimeHandler::HeapState heap_state,
4866 double deadline_in_ms) {
4867 bool result = false;
4868 switch (action.type) {
4872 case DO_INCREMENTAL_MARKING: {
4873 const double remaining_idle_time_in_ms =
4874 AdvanceIncrementalMarking(action.parameter, deadline_in_ms,
4875 IncrementalMarking::IdleStepActions());
4876 if (remaining_idle_time_in_ms > 0.0) {
4877 action.additional_work = TryFinalizeIdleIncrementalMarking(
4878 remaining_idle_time_in_ms, heap_state.size_of_objects,
4879 heap_state.final_incremental_mark_compact_speed_in_bytes_per_ms);
4884 DCHECK(contexts_disposed_ > 0);
4885 HistogramTimerScope scope(isolate_->counters()->gc_context());
4886 CollectAllGarbage(kNoGCFlags, "idle notification: contexts disposed");
4890 CollectGarbage(NEW_SPACE, "idle notification: scavenge");
4892 case DO_FINALIZE_SWEEPING:
4893 mark_compact_collector()->EnsureSweepingCompleted();
4903 void Heap::IdleNotificationEpilogue(GCIdleTimeAction action,
4904 GCIdleTimeHandler::HeapState heap_state,
4905 double start_ms, double deadline_in_ms) {
4906 double idle_time_in_ms = deadline_in_ms - start_ms;
4907 double current_time = MonotonicallyIncreasingTimeInMs();
4908 last_idle_notification_time_ = current_time;
4909 double deadline_difference = deadline_in_ms - current_time;
4911 contexts_disposed_ = 0;
4913 isolate()->counters()->gc_idle_time_allotted_in_ms()->AddSample(
4914 static_cast<int>(idle_time_in_ms));
4916 if (deadline_in_ms - start_ms >
4917 GCIdleTimeHandler::kMaxFrameRenderingIdleTime) {
4918 int committed_memory = static_cast<int>(CommittedMemory() / KB);
4919 int used_memory = static_cast<int>(heap_state.size_of_objects / KB);
4920 isolate()->counters()->aggregated_memory_heap_committed()->AddSample(
4921 start_ms, committed_memory);
4922 isolate()->counters()->aggregated_memory_heap_used()->AddSample(
4923 start_ms, used_memory);
4926 if (deadline_difference >= 0) {
4927 if (action.type != DONE && action.type != DO_NOTHING) {
4928 isolate()->counters()->gc_idle_time_limit_undershot()->AddSample(
4929 static_cast<int>(deadline_difference));
4932 isolate()->counters()->gc_idle_time_limit_overshot()->AddSample(
4933 static_cast<int>(-deadline_difference));
4936 if ((FLAG_trace_idle_notification && action.type > DO_NOTHING) ||
4937 FLAG_trace_idle_notification_verbose) {
4938 PrintIsolate(isolate_, "%8.0f ms: ", isolate()->time_millis_since_init());
4940 "Idle notification: requested idle time %.2f ms, used idle time %.2f "
4941 "ms, deadline usage %.2f ms [",
4942 idle_time_in_ms, idle_time_in_ms - deadline_difference,
4943 deadline_difference);
4946 if (FLAG_trace_idle_notification_verbose) {
4956 void Heap::CheckAndNotifyBackgroundIdleNotification(double idle_time_in_ms,
4958 if (idle_time_in_ms >= GCIdleTimeHandler::kMinBackgroundIdleTime) {
4959 MemoryReducer::Event event;
4960 event.type = MemoryReducer::kBackgroundIdleNotification;
4961 event.time_ms = now_ms;
4962 event.can_start_incremental_gc = incremental_marking()->IsStopped() &&
4963 incremental_marking()->CanBeActivated();
4964 memory_reducer_.NotifyBackgroundIdleNotification(event);
4965 optimize_for_memory_usage_ = true;
4967 optimize_for_memory_usage_ = false;
4972 double Heap::MonotonicallyIncreasingTimeInMs() {
4973 return V8::GetCurrentPlatform()->MonotonicallyIncreasingTime() *
4974 static_cast<double>(base::Time::kMillisecondsPerSecond);
4978 bool Heap::IdleNotification(int idle_time_in_ms) {
4979 return IdleNotification(
4980 V8::GetCurrentPlatform()->MonotonicallyIncreasingTime() +
4981 (static_cast<double>(idle_time_in_ms) /
4982 static_cast<double>(base::Time::kMillisecondsPerSecond)));
4986 bool Heap::IdleNotification(double deadline_in_seconds) {
4987 CHECK(HasBeenSetUp());
4988 double deadline_in_ms =
4989 deadline_in_seconds *
4990 static_cast<double>(base::Time::kMillisecondsPerSecond);
4991 HistogramTimerScope idle_notification_scope(
4992 isolate_->counters()->gc_idle_notification());
4993 double start_ms = MonotonicallyIncreasingTimeInMs();
4994 double idle_time_in_ms = deadline_in_ms - start_ms;
4996 CheckAndNotifyBackgroundIdleNotification(idle_time_in_ms, start_ms);
4998 tracer()->SampleAllocation(start_ms, NewSpaceAllocationCounter(),
4999 OldGenerationAllocationCounter());
5001 GCIdleTimeHandler::HeapState heap_state = ComputeHeapState();
5003 GCIdleTimeAction action =
5004 gc_idle_time_handler_.Compute(idle_time_in_ms, heap_state);
5006 bool result = PerformIdleTimeAction(action, heap_state, deadline_in_ms);
5008 IdleNotificationEpilogue(action, heap_state, start_ms, deadline_in_ms);
5013 bool Heap::RecentIdleNotificationHappened() {
5014 return (last_idle_notification_time_ +
5015 GCIdleTimeHandler::kMaxScheduledIdleTime) >
5016 MonotonicallyIncreasingTimeInMs();
5022 void Heap::Print() {
5023 if (!HasBeenSetUp()) return;
5024 isolate()->PrintStack(stdout);
5025 AllSpaces spaces(this);
5026 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
5032 void Heap::ReportCodeStatistics(const char* title) {
5033 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5034 PagedSpace::ResetCodeStatistics(isolate());
5035 // We do not look for code in new space, map space, or old space. If code
5036 // somehow ends up in those spaces, we would miss it here.
5037 code_space_->CollectCodeStatistics();
5038 lo_space_->CollectCodeStatistics();
5039 PagedSpace::ReportCodeStatistics(isolate());
5043 // This function expects that NewSpace's allocated objects histogram is
5044 // populated (via a call to CollectStatistics or else as a side effect of a
5045 // just-completed scavenge collection).
5046 void Heap::ReportHeapStatistics(const char* title) {
5048 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n", title,
5050 PrintF("old_generation_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5051 old_generation_allocation_limit_);
5054 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles(isolate_));
5055 isolate_->global_handles()->PrintStats();
5058 PrintF("Heap statistics : ");
5059 isolate_->memory_allocator()->ReportStatistics();
5060 PrintF("To space : ");
5061 new_space_.ReportStatistics();
5062 PrintF("Old space : ");
5063 old_space_->ReportStatistics();
5064 PrintF("Code space : ");
5065 code_space_->ReportStatistics();
5066 PrintF("Map space : ");
5067 map_space_->ReportStatistics();
5068 PrintF("Large object space : ");
5069 lo_space_->ReportStatistics();
5070 PrintF(">>>>>> ========================================= >>>>>>\n");
5075 bool Heap::Contains(HeapObject* value) { return Contains(value->address()); }
5078 bool Heap::Contains(Address addr) {
5079 if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false;
5080 return HasBeenSetUp() &&
5081 (new_space_.ToSpaceContains(addr) || old_space_->Contains(addr) ||
5082 code_space_->Contains(addr) || map_space_->Contains(addr) ||
5083 lo_space_->SlowContains(addr));
5087 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5088 return InSpace(value->address(), space);
5092 bool Heap::InSpace(Address addr, AllocationSpace space) {
5093 if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false;
5094 if (!HasBeenSetUp()) return false;
5098 return new_space_.ToSpaceContains(addr);
5100 return old_space_->Contains(addr);
5102 return code_space_->Contains(addr);
5104 return map_space_->Contains(addr);
5106 return lo_space_->SlowContains(addr);
5113 bool Heap::IsValidAllocationSpace(AllocationSpace space) {
5127 bool Heap::RootIsImmortalImmovable(int root_index) {
5128 switch (root_index) {
5129 #define CASE(name) \
5130 case Heap::k##name##RootIndex: \
5132 IMMORTAL_IMMOVABLE_ROOT_LIST(CASE);
5141 void Heap::Verify() {
5142 CHECK(HasBeenSetUp());
5143 HandleScope scope(isolate());
5145 store_buffer()->Verify();
5147 if (mark_compact_collector()->sweeping_in_progress()) {
5148 // We have to wait here for the sweeper threads to have an iterable heap.
5149 mark_compact_collector()->EnsureSweepingCompleted();
5152 VerifyPointersVisitor visitor;
5153 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5155 VerifySmisVisitor smis_visitor;
5156 IterateSmiRoots(&smis_visitor);
5158 new_space_.Verify();
5160 old_space_->Verify(&visitor);
5161 map_space_->Verify(&visitor);
5163 VerifyPointersVisitor no_dirty_regions_visitor;
5164 code_space_->Verify(&no_dirty_regions_visitor);
5166 lo_space_->Verify();
5168 mark_compact_collector_.VerifyWeakEmbeddedObjectsInCode();
5169 if (FLAG_omit_map_checks_for_leaf_maps) {
5170 mark_compact_collector_.VerifyOmittedMapChecks();
5176 void Heap::ZapFromSpace() {
5177 if (!new_space_.IsFromSpaceCommitted()) return;
5178 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5179 new_space_.FromSpaceEnd());
5180 while (it.has_next()) {
5181 NewSpacePage* page = it.next();
5182 for (Address cursor = page->area_start(), limit = page->area_end();
5183 cursor < limit; cursor += kPointerSize) {
5184 Memory::Address_at(cursor) = kFromSpaceZapValue;
5190 void Heap::IterateAndMarkPointersToFromSpace(HeapObject* object, Address start,
5191 Address end, bool record_slots,
5192 ObjectSlotCallback callback) {
5193 Address slot_address = start;
5195 while (slot_address < end) {
5196 Object** slot = reinterpret_cast<Object**>(slot_address);
5197 Object* target = *slot;
5198 // If the store buffer becomes overfull we mark pages as being exempt from
5199 // the store buffer. These pages are scanned to find pointers that point
5200 // to the new space. In that case we may hit newly promoted objects and
5201 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5202 if (target->IsHeapObject()) {
5203 if (Heap::InFromSpace(target)) {
5204 callback(reinterpret_cast<HeapObject**>(slot),
5205 HeapObject::cast(target));
5206 Object* new_target = *slot;
5207 if (InNewSpace(new_target)) {
5208 SLOW_DCHECK(Heap::InToSpace(new_target));
5209 SLOW_DCHECK(new_target->IsHeapObject());
5210 store_buffer_.EnterDirectlyIntoStoreBuffer(
5211 reinterpret_cast<Address>(slot));
5213 SLOW_DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(new_target));
5214 } else if (record_slots &&
5215 MarkCompactCollector::IsOnEvacuationCandidate(target)) {
5216 mark_compact_collector()->RecordSlot(object, slot, target);
5219 slot_address += kPointerSize;
5224 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5225 IterateStrongRoots(v, mode);
5226 IterateWeakRoots(v, mode);
5230 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5231 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kStringTableRootIndex]));
5232 v->Synchronize(VisitorSynchronization::kStringTable);
5233 if (mode != VISIT_ALL_IN_SCAVENGE && mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5234 // Scavenge collections have special processing for this.
5235 external_string_table_.Iterate(v);
5237 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5241 void Heap::IterateSmiRoots(ObjectVisitor* v) {
5242 // Acquire execution access since we are going to read stack limit values.
5243 ExecutionAccess access(isolate());
5244 v->VisitPointers(&roots_[kSmiRootsStart], &roots_[kRootListLength]);
5245 v->Synchronize(VisitorSynchronization::kSmiRootList);
5249 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5250 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5251 v->Synchronize(VisitorSynchronization::kStrongRootList);
5253 v->VisitPointer(bit_cast<Object**>(&hidden_string_));
5254 v->Synchronize(VisitorSynchronization::kInternalizedString);
5256 isolate_->bootstrapper()->Iterate(v);
5257 v->Synchronize(VisitorSynchronization::kBootstrapper);
5258 isolate_->Iterate(v);
5259 v->Synchronize(VisitorSynchronization::kTop);
5260 Relocatable::Iterate(isolate_, v);
5261 v->Synchronize(VisitorSynchronization::kRelocatable);
5263 if (isolate_->deoptimizer_data() != NULL) {
5264 isolate_->deoptimizer_data()->Iterate(v);
5266 v->Synchronize(VisitorSynchronization::kDebug);
5267 isolate_->compilation_cache()->Iterate(v);
5268 v->Synchronize(VisitorSynchronization::kCompilationCache);
5270 // Iterate over local handles in handle scopes.
5271 isolate_->handle_scope_implementer()->Iterate(v);
5272 isolate_->IterateDeferredHandles(v);
5273 v->Synchronize(VisitorSynchronization::kHandleScope);
5275 // Iterate over the builtin code objects and code stubs in the
5276 // heap. Note that it is not necessary to iterate over code objects
5277 // on scavenge collections.
5278 if (mode != VISIT_ALL_IN_SCAVENGE) {
5279 isolate_->builtins()->IterateBuiltins(v);
5281 v->Synchronize(VisitorSynchronization::kBuiltins);
5283 // Iterate over global handles.
5285 case VISIT_ONLY_STRONG:
5286 isolate_->global_handles()->IterateStrongRoots(v);
5288 case VISIT_ALL_IN_SCAVENGE:
5289 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5291 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5293 isolate_->global_handles()->IterateAllRoots(v);
5296 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5298 // Iterate over eternal handles.
5299 if (mode == VISIT_ALL_IN_SCAVENGE) {
5300 isolate_->eternal_handles()->IterateNewSpaceRoots(v);
5302 isolate_->eternal_handles()->IterateAllRoots(v);
5304 v->Synchronize(VisitorSynchronization::kEternalHandles);
5306 // Iterate over pointers being held by inactive threads.
5307 isolate_->thread_manager()->Iterate(v);
5308 v->Synchronize(VisitorSynchronization::kThreadManager);
5310 // Iterate over other strong roots (currently only identity maps).
5311 for (StrongRootsList* list = strong_roots_list_; list; list = list->next) {
5312 v->VisitPointers(list->start, list->end);
5314 v->Synchronize(VisitorSynchronization::kStrongRoots);
5316 // Iterate over the pointers the Serialization/Deserialization code is
5318 // During garbage collection this keeps the partial snapshot cache alive.
5319 // During deserialization of the startup snapshot this creates the partial
5320 // snapshot cache and deserializes the objects it refers to. During
5321 // serialization this does nothing, since the partial snapshot cache is
5322 // empty. However the next thing we do is create the partial snapshot,
5323 // filling up the partial snapshot cache with objects it needs as we go.
5324 SerializerDeserializer::Iterate(isolate_, v);
5325 // We don't do a v->Synchronize call here, because in debug mode that will
5326 // output a flag to the snapshot. However at this point the serializer and
5327 // deserializer are deliberately a little unsynchronized (see above) so the
5328 // checking of the sync flag in the snapshot would fail.
5332 // TODO(1236194): Since the heap size is configurable on the command line
5333 // and through the API, we should gracefully handle the case that the heap
5334 // size is not big enough to fit all the initial objects.
5335 bool Heap::ConfigureHeap(int max_semi_space_size, int max_old_space_size,
5336 int max_executable_size, size_t code_range_size) {
5337 if (HasBeenSetUp()) return false;
5339 // Overwrite default configuration.
5340 if (max_semi_space_size > 0) {
5341 max_semi_space_size_ = max_semi_space_size * MB;
5343 if (max_old_space_size > 0) {
5344 max_old_generation_size_ = static_cast<intptr_t>(max_old_space_size) * MB;
5346 if (max_executable_size > 0) {
5347 max_executable_size_ = static_cast<intptr_t>(max_executable_size) * MB;
5350 // If max space size flags are specified overwrite the configuration.
5351 if (FLAG_max_semi_space_size > 0) {
5352 max_semi_space_size_ = FLAG_max_semi_space_size * MB;
5354 if (FLAG_max_old_space_size > 0) {
5355 max_old_generation_size_ =
5356 static_cast<intptr_t>(FLAG_max_old_space_size) * MB;
5358 if (FLAG_max_executable_size > 0) {
5359 max_executable_size_ = static_cast<intptr_t>(FLAG_max_executable_size) * MB;
5362 if (Page::kPageSize > MB) {
5363 max_semi_space_size_ = ROUND_UP(max_semi_space_size_, Page::kPageSize);
5364 max_old_generation_size_ =
5365 ROUND_UP(max_old_generation_size_, Page::kPageSize);
5366 max_executable_size_ = ROUND_UP(max_executable_size_, Page::kPageSize);
5369 if (FLAG_stress_compaction) {
5370 // This will cause more frequent GCs when stressing.
5371 max_semi_space_size_ = Page::kPageSize;
5374 if (isolate()->snapshot_available()) {
5375 // If we are using a snapshot we always reserve the default amount
5376 // of memory for each semispace because code in the snapshot has
5377 // write-barrier code that relies on the size and alignment of new
5378 // space. We therefore cannot use a larger max semispace size
5379 // than the default reserved semispace size.
5380 if (max_semi_space_size_ > reserved_semispace_size_) {
5381 max_semi_space_size_ = reserved_semispace_size_;
5382 if (FLAG_trace_gc) {
5383 PrintIsolate(isolate_,
5384 "Max semi-space size cannot be more than %d kbytes\n",
5385 reserved_semispace_size_ >> 10);
5389 // If we are not using snapshots we reserve space for the actual
5390 // max semispace size.
5391 reserved_semispace_size_ = max_semi_space_size_;
5394 // The new space size must be a power of two to support single-bit testing
5396 max_semi_space_size_ =
5397 base::bits::RoundUpToPowerOfTwo32(max_semi_space_size_);
5398 reserved_semispace_size_ =
5399 base::bits::RoundUpToPowerOfTwo32(reserved_semispace_size_);
5401 if (FLAG_min_semi_space_size > 0) {
5402 int initial_semispace_size = FLAG_min_semi_space_size * MB;
5403 if (initial_semispace_size > max_semi_space_size_) {
5404 initial_semispace_size_ = max_semi_space_size_;
5405 if (FLAG_trace_gc) {
5406 PrintIsolate(isolate_,
5407 "Min semi-space size cannot be more than the maximum "
5408 "semi-space size of %d MB\n",
5409 max_semi_space_size_ / MB);
5412 initial_semispace_size_ =
5413 ROUND_UP(initial_semispace_size, Page::kPageSize);
5417 initial_semispace_size_ = Min(initial_semispace_size_, max_semi_space_size_);
5419 if (FLAG_target_semi_space_size > 0) {
5420 int target_semispace_size = FLAG_target_semi_space_size * MB;
5421 if (target_semispace_size < initial_semispace_size_) {
5422 target_semispace_size_ = initial_semispace_size_;
5423 if (FLAG_trace_gc) {
5424 PrintIsolate(isolate_,
5425 "Target semi-space size cannot be less than the minimum "
5426 "semi-space size of %d MB\n",
5427 initial_semispace_size_ / MB);
5429 } else if (target_semispace_size > max_semi_space_size_) {
5430 target_semispace_size_ = max_semi_space_size_;
5431 if (FLAG_trace_gc) {
5432 PrintIsolate(isolate_,
5433 "Target semi-space size cannot be less than the maximum "
5434 "semi-space size of %d MB\n",
5435 max_semi_space_size_ / MB);
5438 target_semispace_size_ = ROUND_UP(target_semispace_size, Page::kPageSize);
5442 target_semispace_size_ = Max(initial_semispace_size_, target_semispace_size_);
5444 if (FLAG_semi_space_growth_factor < 2) {
5445 FLAG_semi_space_growth_factor = 2;
5448 // The old generation is paged and needs at least one page for each space.
5449 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5450 max_old_generation_size_ =
5451 Max(static_cast<intptr_t>(paged_space_count * Page::kPageSize),
5452 max_old_generation_size_);
5454 // The max executable size must be less than or equal to the max old
5456 if (max_executable_size_ > max_old_generation_size_) {
5457 max_executable_size_ = max_old_generation_size_;
5460 if (FLAG_initial_old_space_size > 0) {
5461 initial_old_generation_size_ = FLAG_initial_old_space_size * MB;
5463 initial_old_generation_size_ =
5464 max_old_generation_size_ / kInitalOldGenerationLimitFactor;
5466 old_generation_allocation_limit_ = initial_old_generation_size_;
5468 // We rely on being able to allocate new arrays in paged spaces.
5469 DCHECK(Page::kMaxRegularHeapObjectSize >=
5471 FixedArray::SizeFor(JSObject::kInitialMaxFastElementArray) +
5472 AllocationMemento::kSize));
5474 code_range_size_ = code_range_size * MB;
5481 void Heap::AddToRingBuffer(const char* string) {
5483 Min(strlen(string), kTraceRingBufferSize - ring_buffer_end_);
5484 memcpy(trace_ring_buffer_ + ring_buffer_end_, string, first_part);
5485 ring_buffer_end_ += first_part;
5486 if (first_part < strlen(string)) {
5487 ring_buffer_full_ = true;
5488 size_t second_part = strlen(string) - first_part;
5489 memcpy(trace_ring_buffer_, string + first_part, second_part);
5490 ring_buffer_end_ = second_part;
5495 void Heap::GetFromRingBuffer(char* buffer) {
5497 if (ring_buffer_full_) {
5498 copied = kTraceRingBufferSize - ring_buffer_end_;
5499 memcpy(buffer, trace_ring_buffer_ + ring_buffer_end_, copied);
5501 memcpy(buffer + copied, trace_ring_buffer_, ring_buffer_end_);
5505 bool Heap::ConfigureHeapDefault() { return ConfigureHeap(0, 0, 0, 0); }
5508 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5509 *stats->start_marker = HeapStats::kStartMarker;
5510 *stats->end_marker = HeapStats::kEndMarker;
5511 *stats->new_space_size = new_space_.SizeAsInt();
5512 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5513 *stats->old_space_size = old_space_->SizeOfObjects();
5514 *stats->old_space_capacity = old_space_->Capacity();
5515 *stats->code_space_size = code_space_->SizeOfObjects();
5516 *stats->code_space_capacity = code_space_->Capacity();
5517 *stats->map_space_size = map_space_->SizeOfObjects();
5518 *stats->map_space_capacity = map_space_->Capacity();
5519 *stats->lo_space_size = lo_space_->Size();
5520 isolate_->global_handles()->RecordStats(stats);
5521 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5522 *stats->memory_allocator_capacity =
5523 isolate()->memory_allocator()->Size() +
5524 isolate()->memory_allocator()->Available();
5525 *stats->os_error = base::OS::GetLastError();
5526 isolate()->memory_allocator()->Available();
5527 if (take_snapshot) {
5528 HeapIterator iterator(this);
5529 for (HeapObject* obj = iterator.next(); obj != NULL;
5530 obj = iterator.next()) {
5531 InstanceType type = obj->map()->instance_type();
5532 DCHECK(0 <= type && type <= LAST_TYPE);
5533 stats->objects_per_type[type]++;
5534 stats->size_per_type[type] += obj->Size();
5537 if (stats->last_few_messages != NULL)
5538 GetFromRingBuffer(stats->last_few_messages);
5539 if (stats->js_stacktrace != NULL) {
5540 FixedStringAllocator fixed(stats->js_stacktrace, kStacktraceBufferSize - 1);
5541 StringStream accumulator(&fixed);
5542 isolate()->PrintStack(&accumulator, Isolate::kPrintStackVerbose);
5547 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5548 return old_space_->SizeOfObjects() + code_space_->SizeOfObjects() +
5549 map_space_->SizeOfObjects() + lo_space_->SizeOfObjects();
5553 int64_t Heap::PromotedExternalMemorySize() {
5554 if (amount_of_external_allocated_memory_ <=
5555 amount_of_external_allocated_memory_at_last_global_gc_)
5557 return amount_of_external_allocated_memory_ -
5558 amount_of_external_allocated_memory_at_last_global_gc_;
5562 const double Heap::kMinHeapGrowingFactor = 1.1;
5563 const double Heap::kMaxHeapGrowingFactor = 4.0;
5564 const double Heap::kMaxHeapGrowingFactorMemoryConstrained = 2.0;
5565 const double Heap::kMaxHeapGrowingFactorIdle = 1.5;
5566 const double Heap::kTargetMutatorUtilization = 0.97;
5569 // Given GC speed in bytes per ms, the allocation throughput in bytes per ms
5570 // (mutator speed), this function returns the heap growing factor that will
5571 // achieve the kTargetMutatorUtilisation if the GC speed and the mutator speed
5572 // remain the same until the next GC.
5574 // For a fixed time-frame T = TM + TG, the mutator utilization is the ratio
5575 // TM / (TM + TG), where TM is the time spent in the mutator and TG is the
5576 // time spent in the garbage collector.
5578 // Let MU be kTargetMutatorUtilisation, the desired mutator utilization for the
5579 // time-frame from the end of the current GC to the end of the next GC. Based
5580 // on the MU we can compute the heap growing factor F as
5582 // F = R * (1 - MU) / (R * (1 - MU) - MU), where R = gc_speed / mutator_speed.
5584 // This formula can be derived as follows.
5586 // F = Limit / Live by definition, where the Limit is the allocation limit,
5587 // and the Live is size of live objects.
5588 // Let’s assume that we already know the Limit. Then:
5589 // TG = Limit / gc_speed
5590 // TM = (TM + TG) * MU, by definition of MU.
5591 // TM = TG * MU / (1 - MU)
5592 // TM = Limit * MU / (gc_speed * (1 - MU))
5593 // On the other hand, if the allocation throughput remains constant:
5594 // Limit = Live + TM * allocation_throughput = Live + TM * mutator_speed
5595 // Solving it for TM, we get
5596 // TM = (Limit - Live) / mutator_speed
5597 // Combining the two equation for TM:
5598 // (Limit - Live) / mutator_speed = Limit * MU / (gc_speed * (1 - MU))
5599 // (Limit - Live) = Limit * MU * mutator_speed / (gc_speed * (1 - MU))
5600 // substitute R = gc_speed / mutator_speed
5601 // (Limit - Live) = Limit * MU / (R * (1 - MU))
5602 // substitute F = Limit / Live
5603 // F - 1 = F * MU / (R * (1 - MU))
5604 // F - F * MU / (R * (1 - MU)) = 1
5605 // F * (1 - MU / (R * (1 - MU))) = 1
5606 // F * (R * (1 - MU) - MU) / (R * (1 - MU)) = 1
5607 // F = R * (1 - MU) / (R * (1 - MU) - MU)
5608 double Heap::HeapGrowingFactor(double gc_speed, double mutator_speed) {
5609 if (gc_speed == 0 || mutator_speed == 0) return kMaxHeapGrowingFactor;
5611 const double speed_ratio = gc_speed / mutator_speed;
5612 const double mu = kTargetMutatorUtilization;
5614 const double a = speed_ratio * (1 - mu);
5615 const double b = speed_ratio * (1 - mu) - mu;
5617 // The factor is a / b, but we need to check for small b first.
5619 (a < b * kMaxHeapGrowingFactor) ? a / b : kMaxHeapGrowingFactor;
5620 factor = Min(factor, kMaxHeapGrowingFactor);
5621 factor = Max(factor, kMinHeapGrowingFactor);
5626 intptr_t Heap::CalculateOldGenerationAllocationLimit(double factor,
5627 intptr_t old_gen_size) {
5628 CHECK(factor > 1.0);
5629 CHECK(old_gen_size > 0);
5630 intptr_t limit = static_cast<intptr_t>(old_gen_size * factor);
5631 limit = Max(limit, old_gen_size + kMinimumOldGenerationAllocationLimit);
5632 limit += new_space_.Capacity();
5633 intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
5634 return Min(limit, halfway_to_the_max);
5638 void Heap::SetOldGenerationAllocationLimit(intptr_t old_gen_size,
5640 double mutator_speed) {
5641 const double kConservativeHeapGrowingFactor = 1.3;
5643 double factor = HeapGrowingFactor(gc_speed, mutator_speed);
5645 if (FLAG_trace_gc_verbose) {
5646 PrintIsolate(isolate_,
5647 "Heap growing factor %.1f based on mu=%.3f, speed_ratio=%.f "
5648 "(gc=%.f, mutator=%.f)\n",
5649 factor, kTargetMutatorUtilization, gc_speed / mutator_speed,
5650 gc_speed, mutator_speed);
5653 // We set the old generation growing factor to 2 to grow the heap slower on
5654 // memory-constrained devices.
5655 if (max_old_generation_size_ <= kMaxOldSpaceSizeMediumMemoryDevice ||
5656 FLAG_optimize_for_size) {
5657 factor = Min(factor, kMaxHeapGrowingFactorMemoryConstrained);
5660 if (memory_reducer_.ShouldGrowHeapSlowly() || optimize_for_memory_usage_) {
5661 factor = Min(factor, kConservativeHeapGrowingFactor);
5664 if (FLAG_stress_compaction ||
5665 mark_compact_collector()->reduce_memory_footprint_) {
5666 factor = kMinHeapGrowingFactor;
5669 old_generation_allocation_limit_ =
5670 CalculateOldGenerationAllocationLimit(factor, old_gen_size);
5672 if (FLAG_trace_gc_verbose) {
5673 PrintIsolate(isolate_, "Grow: old size: %" V8_PTR_PREFIX
5674 "d KB, new limit: %" V8_PTR_PREFIX "d KB (%.1f)\n",
5675 old_gen_size / KB, old_generation_allocation_limit_ / KB,
5681 void Heap::DampenOldGenerationAllocationLimit(intptr_t old_gen_size,
5683 double mutator_speed) {
5684 double factor = HeapGrowingFactor(gc_speed, mutator_speed);
5685 intptr_t limit = CalculateOldGenerationAllocationLimit(factor, old_gen_size);
5686 if (limit < old_generation_allocation_limit_) {
5687 if (FLAG_trace_gc_verbose) {
5688 PrintIsolate(isolate_, "Dampen: old size: %" V8_PTR_PREFIX
5689 "d KB, old limit: %" V8_PTR_PREFIX
5691 "new limit: %" V8_PTR_PREFIX "d KB (%.1f)\n",
5692 old_gen_size / KB, old_generation_allocation_limit_ / KB,
5693 limit / KB, factor);
5695 old_generation_allocation_limit_ = limit;
5700 void Heap::EnableInlineAllocation() {
5701 if (!inline_allocation_disabled_) return;
5702 inline_allocation_disabled_ = false;
5704 // Update inline allocation limit for new space.
5705 new_space()->UpdateInlineAllocationLimit(0);
5709 void Heap::DisableInlineAllocation() {
5710 if (inline_allocation_disabled_) return;
5711 inline_allocation_disabled_ = true;
5713 // Update inline allocation limit for new space.
5714 new_space()->UpdateInlineAllocationLimit(0);
5716 // Update inline allocation limit for old spaces.
5717 PagedSpaces spaces(this);
5718 for (PagedSpace* space = spaces.next(); space != NULL;
5719 space = spaces.next()) {
5720 space->EmptyAllocationInfo();
5725 V8_DECLARE_ONCE(initialize_gc_once);
5727 static void InitializeGCOnce() {
5728 InitializeScavengingVisitorsTables();
5729 NewSpaceScavenger::Initialize();
5730 MarkCompactCollector::Initialize();
5734 bool Heap::SetUp() {
5736 allocation_timeout_ = FLAG_gc_interval;
5739 // Initialize heap spaces and initial maps and objects. Whenever something
5740 // goes wrong, just return false. The caller should check the results and
5741 // call Heap::TearDown() to release allocated memory.
5743 // If the heap is not yet configured (e.g. through the API), configure it.
5744 // Configuration is based on the flags new-space-size (really the semispace
5745 // size) and old-space-size if set or the initial values of semispace_size_
5746 // and old_generation_size_ otherwise.
5748 if (!ConfigureHeapDefault()) return false;
5751 concurrent_sweeping_enabled_ = FLAG_concurrent_sweeping;
5753 base::CallOnce(&initialize_gc_once, &InitializeGCOnce);
5755 // Set up memory allocator.
5756 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
5759 // Set up new space.
5760 if (!new_space_.SetUp(reserved_semispace_size_, max_semi_space_size_)) {
5763 new_space_top_after_last_gc_ = new_space()->top();
5765 // Initialize old space.
5766 old_space_ = new OldSpace(this, OLD_SPACE, NOT_EXECUTABLE);
5767 if (old_space_ == NULL) return false;
5768 if (!old_space_->SetUp()) return false;
5770 if (!isolate_->code_range()->SetUp(code_range_size_)) return false;
5772 // Initialize the code space, set its maximum capacity to the old
5773 // generation size. It needs executable memory.
5774 code_space_ = new OldSpace(this, CODE_SPACE, EXECUTABLE);
5775 if (code_space_ == NULL) return false;
5776 if (!code_space_->SetUp()) return false;
5778 // Initialize map space.
5779 map_space_ = new MapSpace(this, MAP_SPACE);
5780 if (map_space_ == NULL) return false;
5781 if (!map_space_->SetUp()) return false;
5783 // The large object code space may contain code or data. We set the memory
5784 // to be non-executable here for safety, but this means we need to enable it
5785 // explicitly when allocating large code objects.
5786 lo_space_ = new LargeObjectSpace(this, LO_SPACE);
5787 if (lo_space_ == NULL) return false;
5788 if (!lo_space_->SetUp()) return false;
5790 // Set up the seed that is used to randomize the string hash function.
5791 DCHECK(hash_seed() == 0);
5792 if (FLAG_randomize_hashes) {
5793 if (FLAG_hash_seed == 0) {
5794 int rnd = isolate()->random_number_generator()->NextInt();
5795 set_hash_seed(Smi::FromInt(rnd & Name::kHashBitMask));
5797 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5801 for (int i = 0; i < static_cast<int>(v8::Isolate::kUseCounterFeatureCount);
5803 deferred_counters_[i] = 0;
5807 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5808 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
5810 store_buffer()->SetUp();
5812 mark_compact_collector()->SetUp();
5818 bool Heap::CreateHeapObjects() {
5819 // Create initial maps.
5820 if (!CreateInitialMaps()) return false;
5823 // Create initial objects
5824 CreateInitialObjects();
5825 CHECK_EQ(0u, gc_count_);
5827 set_native_contexts_list(undefined_value());
5828 set_allocation_sites_list(undefined_value());
5833 void Heap::SetStackLimits() {
5834 DCHECK(isolate_ != NULL);
5835 DCHECK(isolate_ == isolate());
5836 // On 64 bit machines, pointers are generally out of range of Smis. We write
5837 // something that looks like an out of range Smi to the GC.
5839 // Set up the special root array entries containing the stack limits.
5840 // These are actually addresses, but the tag makes the GC ignore it.
5841 roots_[kStackLimitRootIndex] = reinterpret_cast<Object*>(
5842 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
5843 roots_[kRealStackLimitRootIndex] = reinterpret_cast<Object*>(
5844 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
5848 void Heap::NotifyDeserializationComplete() {
5849 deserialization_complete_ = true;
5851 // All pages right after bootstrapping must be marked as never-evacuate.
5852 PagedSpaces spaces(this);
5853 for (PagedSpace* s = spaces.next(); s != NULL; s = spaces.next()) {
5855 while (it.has_next()) CHECK(it.next()->NeverEvacuate());
5861 void Heap::TearDown() {
5863 if (FLAG_verify_heap) {
5868 UpdateMaximumCommitted();
5870 if (FLAG_print_cumulative_gc_stat) {
5872 PrintF("gc_count=%d ", gc_count_);
5873 PrintF("mark_sweep_count=%d ", ms_count_);
5874 PrintF("max_gc_pause=%.1f ", get_max_gc_pause());
5875 PrintF("total_gc_time=%.1f ", total_gc_time_ms_);
5876 PrintF("min_in_mutator=%.1f ", get_min_in_mutator());
5877 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ", get_max_alive_after_gc());
5878 PrintF("total_marking_time=%.1f ", tracer_.cumulative_marking_duration());
5879 PrintF("total_sweeping_time=%.1f ", tracer_.cumulative_sweeping_duration());
5883 if (FLAG_print_max_heap_committed) {
5885 PrintF("maximum_committed_by_heap=%" V8_PTR_PREFIX "d ",
5886 MaximumCommittedMemory());
5887 PrintF("maximum_committed_by_new_space=%" V8_PTR_PREFIX "d ",
5888 new_space_.MaximumCommittedMemory());
5889 PrintF("maximum_committed_by_old_space=%" V8_PTR_PREFIX "d ",
5890 old_space_->MaximumCommittedMemory());
5891 PrintF("maximum_committed_by_code_space=%" V8_PTR_PREFIX "d ",
5892 code_space_->MaximumCommittedMemory());
5893 PrintF("maximum_committed_by_map_space=%" V8_PTR_PREFIX "d ",
5894 map_space_->MaximumCommittedMemory());
5895 PrintF("maximum_committed_by_lo_space=%" V8_PTR_PREFIX "d ",
5896 lo_space_->MaximumCommittedMemory());
5900 if (FLAG_verify_predictable) {
5901 PrintAlloctionsHash();
5904 memory_reducer_.TearDown();
5906 TearDownArrayBuffers();
5908 isolate_->global_handles()->TearDown();
5910 external_string_table_.TearDown();
5912 mark_compact_collector()->TearDown();
5914 new_space_.TearDown();
5916 if (old_space_ != NULL) {
5917 old_space_->TearDown();
5922 if (code_space_ != NULL) {
5923 code_space_->TearDown();
5928 if (map_space_ != NULL) {
5929 map_space_->TearDown();
5934 if (lo_space_ != NULL) {
5935 lo_space_->TearDown();
5940 store_buffer()->TearDown();
5942 isolate_->memory_allocator()->TearDown();
5944 StrongRootsList* next = NULL;
5945 for (StrongRootsList* list = strong_roots_list_; list; list = next) {
5949 strong_roots_list_ = NULL;
5953 void Heap::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
5954 GCType gc_type, bool pass_isolate) {
5955 DCHECK(callback != NULL);
5956 GCPrologueCallbackPair pair(callback, gc_type, pass_isolate);
5957 DCHECK(!gc_prologue_callbacks_.Contains(pair));
5958 return gc_prologue_callbacks_.Add(pair);
5962 void Heap::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) {
5963 DCHECK(callback != NULL);
5964 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
5965 if (gc_prologue_callbacks_[i].callback == callback) {
5966 gc_prologue_callbacks_.Remove(i);
5974 void Heap::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
5975 GCType gc_type, bool pass_isolate) {
5976 DCHECK(callback != NULL);
5977 GCEpilogueCallbackPair pair(callback, gc_type, pass_isolate);
5978 DCHECK(!gc_epilogue_callbacks_.Contains(pair));
5979 return gc_epilogue_callbacks_.Add(pair);
5983 void Heap::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) {
5984 DCHECK(callback != NULL);
5985 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
5986 if (gc_epilogue_callbacks_[i].callback == callback) {
5987 gc_epilogue_callbacks_.Remove(i);
5995 // TODO(ishell): Find a better place for this.
5996 void Heap::AddWeakObjectToCodeDependency(Handle<HeapObject> obj,
5997 Handle<DependentCode> dep) {
5998 DCHECK(!InNewSpace(*obj));
5999 DCHECK(!InNewSpace(*dep));
6000 Handle<WeakHashTable> table(weak_object_to_code_table(), isolate());
6001 table = WeakHashTable::Put(table, obj, dep);
6002 if (*table != weak_object_to_code_table())
6003 set_weak_object_to_code_table(*table);
6004 DCHECK_EQ(*dep, LookupWeakObjectToCodeDependency(obj));
6008 DependentCode* Heap::LookupWeakObjectToCodeDependency(Handle<HeapObject> obj) {
6009 Object* dep = weak_object_to_code_table()->Lookup(obj);
6010 if (dep->IsDependentCode()) return DependentCode::cast(dep);
6011 return DependentCode::cast(empty_fixed_array());
6015 void Heap::AddRetainedMap(Handle<Map> map) {
6016 if (FLAG_retain_maps_for_n_gc == 0) return;
6017 Handle<WeakCell> cell = Map::WeakCellForMap(map);
6018 Handle<ArrayList> array(retained_maps(), isolate());
6019 array = ArrayList::Add(
6020 array, cell, handle(Smi::FromInt(FLAG_retain_maps_for_n_gc), isolate()),
6021 ArrayList::kReloadLengthAfterAllocation);
6022 if (*array != retained_maps()) {
6023 set_retained_maps(*array);
6028 void Heap::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
6029 v8::internal::V8::FatalProcessOutOfMemory(location, take_snapshot);
6034 class PrintHandleVisitor : public ObjectVisitor {
6036 void VisitPointers(Object** start, Object** end) {
6037 for (Object** p = start; p < end; p++)
6038 PrintF(" handle %p to %p\n", reinterpret_cast<void*>(p),
6039 reinterpret_cast<void*>(*p));
6044 void Heap::PrintHandles() {
6045 PrintF("Handles:\n");
6046 PrintHandleVisitor v;
6047 isolate_->handle_scope_implementer()->Iterate(&v);
6052 class CheckHandleCountVisitor : public ObjectVisitor {
6054 CheckHandleCountVisitor() : handle_count_(0) {}
6055 ~CheckHandleCountVisitor() {
6056 CHECK(handle_count_ < HandleScope::kCheckHandleThreshold);
6058 void VisitPointers(Object** start, Object** end) {
6059 handle_count_ += end - start;
6063 ptrdiff_t handle_count_;
6067 void Heap::CheckHandleCount() {
6068 CheckHandleCountVisitor v;
6069 isolate_->handle_scope_implementer()->Iterate(&v);
6073 Space* AllSpaces::next() {
6074 switch (counter_++) {
6076 return heap_->new_space();
6078 return heap_->old_space();
6080 return heap_->code_space();
6082 return heap_->map_space();
6084 return heap_->lo_space();
6091 PagedSpace* PagedSpaces::next() {
6092 switch (counter_++) {
6094 return heap_->old_space();
6096 return heap_->code_space();
6098 return heap_->map_space();
6105 OldSpace* OldSpaces::next() {
6106 switch (counter_++) {
6108 return heap_->old_space();
6110 return heap_->code_space();
6117 SpaceIterator::SpaceIterator(Heap* heap)
6118 : heap_(heap), current_space_(FIRST_SPACE), iterator_(NULL) {}
6121 SpaceIterator::~SpaceIterator() {
6122 // Delete active iterator if any.
6127 bool SpaceIterator::has_next() {
6128 // Iterate until no more spaces.
6129 return current_space_ != LAST_SPACE;
6133 ObjectIterator* SpaceIterator::next() {
6134 if (iterator_ != NULL) {
6137 // Move to the next space
6139 if (current_space_ > LAST_SPACE) {
6144 // Return iterator for the new current space.
6145 return CreateIterator();
6149 // Create an iterator for the space to iterate.
6150 ObjectIterator* SpaceIterator::CreateIterator() {
6151 DCHECK(iterator_ == NULL);
6153 switch (current_space_) {
6155 iterator_ = new SemiSpaceIterator(heap_->new_space());
6158 iterator_ = new HeapObjectIterator(heap_->old_space());
6161 iterator_ = new HeapObjectIterator(heap_->code_space());
6164 iterator_ = new HeapObjectIterator(heap_->map_space());
6167 iterator_ = new LargeObjectIterator(heap_->lo_space());
6171 // Return the newly allocated iterator;
6172 DCHECK(iterator_ != NULL);
6177 class HeapObjectsFilter {
6179 virtual ~HeapObjectsFilter() {}
6180 virtual bool SkipObject(HeapObject* object) = 0;
6184 class UnreachableObjectsFilter : public HeapObjectsFilter {
6186 explicit UnreachableObjectsFilter(Heap* heap) : heap_(heap) {
6187 MarkReachableObjects();
6190 ~UnreachableObjectsFilter() {
6191 heap_->mark_compact_collector()->ClearMarkbits();
6194 bool SkipObject(HeapObject* object) {
6195 if (object->IsFiller()) return true;
6196 MarkBit mark_bit = Marking::MarkBitFrom(object);
6197 return Marking::IsWhite(mark_bit);
6201 class MarkingVisitor : public ObjectVisitor {
6203 MarkingVisitor() : marking_stack_(10) {}
6205 void VisitPointers(Object** start, Object** end) {
6206 for (Object** p = start; p < end; p++) {
6207 if (!(*p)->IsHeapObject()) continue;
6208 HeapObject* obj = HeapObject::cast(*p);
6209 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6210 if (Marking::IsWhite(mark_bit)) {
6211 Marking::WhiteToBlack(mark_bit);
6212 marking_stack_.Add(obj);
6217 void TransitiveClosure() {
6218 while (!marking_stack_.is_empty()) {
6219 HeapObject* obj = marking_stack_.RemoveLast();
6225 List<HeapObject*> marking_stack_;
6228 void MarkReachableObjects() {
6229 MarkingVisitor visitor;
6230 heap_->IterateRoots(&visitor, VISIT_ALL);
6231 visitor.TransitiveClosure();
6235 DisallowHeapAllocation no_allocation_;
6239 HeapIterator::HeapIterator(Heap* heap)
6240 : make_heap_iterable_helper_(heap),
6241 no_heap_allocation_(),
6243 filtering_(HeapIterator::kNoFiltering),
6249 HeapIterator::HeapIterator(Heap* heap,
6250 HeapIterator::HeapObjectsFiltering filtering)
6251 : make_heap_iterable_helper_(heap),
6252 no_heap_allocation_(),
6254 filtering_(filtering),
6260 HeapIterator::~HeapIterator() { Shutdown(); }
6263 void HeapIterator::Init() {
6264 // Start the iteration.
6265 space_iterator_ = new SpaceIterator(heap_);
6266 switch (filtering_) {
6267 case kFilterUnreachable:
6268 filter_ = new UnreachableObjectsFilter(heap_);
6273 object_iterator_ = space_iterator_->next();
6277 void HeapIterator::Shutdown() {
6279 // Assert that in filtering mode we have iterated through all
6280 // objects. Otherwise, heap will be left in an inconsistent state.
6281 if (filtering_ != kNoFiltering) {
6282 DCHECK(object_iterator_ == NULL);
6285 // Make sure the last iterator is deallocated.
6286 delete space_iterator_;
6287 space_iterator_ = NULL;
6288 object_iterator_ = NULL;
6294 HeapObject* HeapIterator::next() {
6295 if (filter_ == NULL) return NextObject();
6297 HeapObject* obj = NextObject();
6298 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6303 HeapObject* HeapIterator::NextObject() {
6304 // No iterator means we are done.
6305 if (object_iterator_ == NULL) return NULL;
6307 if (HeapObject* obj = object_iterator_->next_object()) {
6308 // If the current iterator has more objects we are fine.
6311 // Go though the spaces looking for one that has objects.
6312 while (space_iterator_->has_next()) {
6313 object_iterator_ = space_iterator_->next();
6314 if (HeapObject* obj = object_iterator_->next_object()) {
6319 // Done with the last space.
6320 object_iterator_ = NULL;
6325 void HeapIterator::reset() {
6326 // Restart the iterator.
6334 Object* const PathTracer::kAnyGlobalObject = NULL;
6336 class PathTracer::MarkVisitor : public ObjectVisitor {
6338 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6339 void VisitPointers(Object** start, Object** end) {
6340 // Scan all HeapObject pointers in [start, end)
6341 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6342 if ((*p)->IsHeapObject()) tracer_->MarkRecursively(p, this);
6347 PathTracer* tracer_;
6351 class PathTracer::UnmarkVisitor : public ObjectVisitor {
6353 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6354 void VisitPointers(Object** start, Object** end) {
6355 // Scan all HeapObject pointers in [start, end)
6356 for (Object** p = start; p < end; p++) {
6357 if ((*p)->IsHeapObject()) tracer_->UnmarkRecursively(p, this);
6362 PathTracer* tracer_;
6366 void PathTracer::VisitPointers(Object** start, Object** end) {
6367 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6368 // Visit all HeapObject pointers in [start, end)
6369 for (Object** p = start; !done && (p < end); p++) {
6370 if ((*p)->IsHeapObject()) {
6372 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6378 void PathTracer::Reset() {
6379 found_target_ = false;
6380 object_stack_.Clear();
6384 void PathTracer::TracePathFrom(Object** root) {
6385 DCHECK((search_target_ == kAnyGlobalObject) ||
6386 search_target_->IsHeapObject());
6387 found_target_in_trace_ = false;
6390 MarkVisitor mark_visitor(this);
6391 MarkRecursively(root, &mark_visitor);
6393 UnmarkVisitor unmark_visitor(this);
6394 UnmarkRecursively(root, &unmark_visitor);
6400 static bool SafeIsNativeContext(HeapObject* obj) {
6401 return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map();
6405 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6406 if (!(*p)->IsHeapObject()) return;
6408 HeapObject* obj = HeapObject::cast(*p);
6410 MapWord map_word = obj->map_word();
6411 if (!map_word.ToMap()->IsHeapObject()) return; // visited before
6413 if (found_target_in_trace_) return; // stop if target found
6414 object_stack_.Add(obj);
6415 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6416 (obj == search_target_)) {
6417 found_target_in_trace_ = true;
6418 found_target_ = true;
6422 bool is_native_context = SafeIsNativeContext(obj);
6425 Map* map = Map::cast(map_word.ToMap());
6427 MapWord marked_map_word =
6428 MapWord::FromRawValue(obj->map_word().ToRawValue() + kMarkTag);
6429 obj->set_map_word(marked_map_word);
6431 // Scan the object body.
6432 if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6433 // This is specialized to scan Context's properly.
6435 reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize);
6437 reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize +
6438 Context::FIRST_WEAK_SLOT * kPointerSize);
6439 mark_visitor->VisitPointers(start, end);
6441 obj->IterateBody(map->instance_type(), obj->SizeFromMap(map), mark_visitor);
6444 // Scan the map after the body because the body is a lot more interesting
6445 // when doing leak detection.
6446 MarkRecursively(reinterpret_cast<Object**>(&map), mark_visitor);
6448 if (!found_target_in_trace_) { // don't pop if found the target
6449 object_stack_.RemoveLast();
6454 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6455 if (!(*p)->IsHeapObject()) return;
6457 HeapObject* obj = HeapObject::cast(*p);
6459 MapWord map_word = obj->map_word();
6460 if (map_word.ToMap()->IsHeapObject()) return; // unmarked already
6462 MapWord unmarked_map_word =
6463 MapWord::FromRawValue(map_word.ToRawValue() - kMarkTag);
6464 obj->set_map_word(unmarked_map_word);
6466 Map* map = Map::cast(unmarked_map_word.ToMap());
6468 UnmarkRecursively(reinterpret_cast<Object**>(&map), unmark_visitor);
6470 obj->IterateBody(map->instance_type(), obj->SizeFromMap(map), unmark_visitor);
6474 void PathTracer::ProcessResults() {
6475 if (found_target_) {
6476 OFStream os(stdout);
6477 os << "=====================================\n"
6478 << "==== Path to object ====\n"
6479 << "=====================================\n\n";
6481 DCHECK(!object_stack_.is_empty());
6482 for (int i = 0; i < object_stack_.length(); i++) {
6483 if (i > 0) os << "\n |\n |\n V\n\n";
6484 object_stack_[i]->Print(os);
6486 os << "=====================================\n";
6491 // Triggers a depth-first traversal of reachable objects from one
6492 // given root object and finds a path to a specific heap object and
6494 void Heap::TracePathToObjectFrom(Object* target, Object* root) {
6495 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6496 tracer.VisitPointer(&root);
6500 // Triggers a depth-first traversal of reachable objects from roots
6501 // and finds a path to a specific heap object and prints it.
6502 void Heap::TracePathToObject(Object* target) {
6503 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6504 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6508 // Triggers a depth-first traversal of reachable objects from roots
6509 // and finds a path to any global object and prints it. Useful for
6510 // determining the source for leaks of global objects.
6511 void Heap::TracePathToGlobal() {
6512 PathTracer tracer(PathTracer::kAnyGlobalObject, PathTracer::FIND_ALL,
6514 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6519 void Heap::UpdateCumulativeGCStatistics(double duration,
6520 double spent_in_mutator,
6521 double marking_time) {
6522 if (FLAG_print_cumulative_gc_stat) {
6523 total_gc_time_ms_ += duration;
6524 max_gc_pause_ = Max(max_gc_pause_, duration);
6525 max_alive_after_gc_ = Max(max_alive_after_gc_, SizeOfObjects());
6526 min_in_mutator_ = Min(min_in_mutator_, spent_in_mutator);
6527 } else if (FLAG_trace_gc_verbose) {
6528 total_gc_time_ms_ += duration;
6531 marking_time_ += marking_time;
6535 int KeyedLookupCache::Hash(Handle<Map> map, Handle<Name> name) {
6536 DisallowHeapAllocation no_gc;
6537 // Uses only lower 32 bits if pointers are larger.
6538 uintptr_t addr_hash =
6539 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(*map)) >> kMapHashShift;
6540 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6544 int KeyedLookupCache::Lookup(Handle<Map> map, Handle<Name> name) {
6545 DisallowHeapAllocation no_gc;
6546 int index = (Hash(map, name) & kHashMask);
6547 for (int i = 0; i < kEntriesPerBucket; i++) {
6548 Key& key = keys_[index + i];
6549 if ((key.map == *map) && key.name->Equals(*name)) {
6550 return field_offsets_[index + i];
6557 void KeyedLookupCache::Update(Handle<Map> map, Handle<Name> name,
6559 DisallowHeapAllocation no_gc;
6560 if (!name->IsUniqueName()) {
6561 if (!StringTable::InternalizeStringIfExists(
6562 name->GetIsolate(), Handle<String>::cast(name)).ToHandle(&name)) {
6566 // This cache is cleared only between mark compact passes, so we expect the
6567 // cache to only contain old space names.
6568 DCHECK(!map->GetIsolate()->heap()->InNewSpace(*name));
6570 int index = (Hash(map, name) & kHashMask);
6571 // After a GC there will be free slots, so we use them in order (this may
6572 // help to get the most frequently used one in position 0).
6573 for (int i = 0; i < kEntriesPerBucket; i++) {
6574 Key& key = keys_[index];
6575 Object* free_entry_indicator = NULL;
6576 if (key.map == free_entry_indicator) {
6579 field_offsets_[index + i] = field_offset;
6583 // No free entry found in this bucket, so we move them all down one and
6584 // put the new entry at position zero.
6585 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6586 Key& key = keys_[index + i];
6587 Key& key2 = keys_[index + i - 1];
6589 field_offsets_[index + i] = field_offsets_[index + i - 1];
6592 // Write the new first entry.
6593 Key& key = keys_[index];
6596 field_offsets_[index] = field_offset;
6600 void KeyedLookupCache::Clear() {
6601 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6605 void DescriptorLookupCache::Clear() {
6606 for (int index = 0; index < kLength; index++) keys_[index].source = NULL;
6610 void ExternalStringTable::CleanUp() {
6612 for (int i = 0; i < new_space_strings_.length(); ++i) {
6613 if (new_space_strings_[i] == heap_->the_hole_value()) {
6616 DCHECK(new_space_strings_[i]->IsExternalString());
6617 if (heap_->InNewSpace(new_space_strings_[i])) {
6618 new_space_strings_[last++] = new_space_strings_[i];
6620 old_space_strings_.Add(new_space_strings_[i]);
6623 new_space_strings_.Rewind(last);
6624 new_space_strings_.Trim();
6627 for (int i = 0; i < old_space_strings_.length(); ++i) {
6628 if (old_space_strings_[i] == heap_->the_hole_value()) {
6631 DCHECK(old_space_strings_[i]->IsExternalString());
6632 DCHECK(!heap_->InNewSpace(old_space_strings_[i]));
6633 old_space_strings_[last++] = old_space_strings_[i];
6635 old_space_strings_.Rewind(last);
6636 old_space_strings_.Trim();
6638 if (FLAG_verify_heap) {
6645 void ExternalStringTable::TearDown() {
6646 for (int i = 0; i < new_space_strings_.length(); ++i) {
6647 heap_->FinalizeExternalString(ExternalString::cast(new_space_strings_[i]));
6649 new_space_strings_.Free();
6650 for (int i = 0; i < old_space_strings_.length(); ++i) {
6651 heap_->FinalizeExternalString(ExternalString::cast(old_space_strings_[i]));
6653 old_space_strings_.Free();
6657 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6658 chunk->set_next_chunk(chunks_queued_for_free_);
6659 chunks_queued_for_free_ = chunk;
6663 void Heap::FreeQueuedChunks() {
6664 if (chunks_queued_for_free_ == NULL) return;
6667 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6668 next = chunk->next_chunk();
6669 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6671 if (chunk->owner()->identity() == LO_SPACE) {
6672 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6673 // If FromAnyPointerAddress encounters a slot that belongs to a large
6674 // chunk queued for deletion it will fail to find the chunk because
6675 // it try to perform a search in the list of pages owned by of the large
6676 // object space and queued chunks were detached from that list.
6677 // To work around this we split large chunk into normal kPageSize aligned
6678 // pieces and initialize size, owner and flags field of every piece.
6679 // If FromAnyPointerAddress encounters a slot that belongs to one of
6680 // these smaller pieces it will treat it as a slot on a normal Page.
6681 Address chunk_end = chunk->address() + chunk->size();
6682 MemoryChunk* inner =
6683 MemoryChunk::FromAddress(chunk->address() + Page::kPageSize);
6684 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
6685 while (inner <= inner_last) {
6686 // Size of a large chunk is always a multiple of
6687 // OS::AllocateAlignment() so there is always
6688 // enough space for a fake MemoryChunk header.
6689 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
6690 // Guard against overflow.
6691 if (area_end < inner->address()) area_end = chunk_end;
6692 inner->SetArea(inner->address(), area_end);
6693 inner->set_size(Page::kPageSize);
6694 inner->set_owner(lo_space());
6695 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6696 inner = MemoryChunk::FromAddress(inner->address() + Page::kPageSize);
6700 isolate_->heap()->store_buffer()->Compact();
6701 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6702 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6703 next = chunk->next_chunk();
6704 isolate_->memory_allocator()->Free(chunk);
6706 chunks_queued_for_free_ = NULL;
6710 void Heap::RememberUnmappedPage(Address page, bool compacted) {
6711 uintptr_t p = reinterpret_cast<uintptr_t>(page);
6712 // Tag the page pointer to make it findable in the dump file.
6714 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
6716 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
6718 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
6719 reinterpret_cast<Address>(p);
6720 remembered_unmapped_pages_index_++;
6721 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
6725 void Heap::ClearObjectStats(bool clear_last_time_stats) {
6726 memset(object_counts_, 0, sizeof(object_counts_));
6727 memset(object_sizes_, 0, sizeof(object_sizes_));
6728 if (clear_last_time_stats) {
6729 memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_));
6730 memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_));
6735 static base::LazyMutex object_stats_mutex = LAZY_MUTEX_INITIALIZER;
6738 void Heap::TraceObjectStat(const char* name, int count, int size, double time) {
6739 PrintIsolate(isolate_,
6740 "heap:%p, time:%f, gc:%d, type:%s, count:%d, size:%d\n",
6741 static_cast<void*>(this), time, ms_count_, name, count, size);
6745 void Heap::TraceObjectStats() {
6746 base::LockGuard<base::Mutex> lock_guard(object_stats_mutex.Pointer());
6751 double time = isolate_->time_millis_since_init();
6752 #define TRACE_OBJECT_COUNT(name) \
6753 count = static_cast<int>(object_counts_[name]); \
6754 size = static_cast<int>(object_sizes_[name]) / KB; \
6755 total_size += size; \
6756 TraceObjectStat(#name, count, size, time);
6757 INSTANCE_TYPE_LIST(TRACE_OBJECT_COUNT)
6758 #undef TRACE_OBJECT_COUNT
6759 #define TRACE_OBJECT_COUNT(name) \
6760 index = FIRST_CODE_KIND_SUB_TYPE + Code::name; \
6761 count = static_cast<int>(object_counts_[index]); \
6762 size = static_cast<int>(object_sizes_[index]) / KB; \
6763 TraceObjectStat("*CODE_" #name, count, size, time);
6764 CODE_KIND_LIST(TRACE_OBJECT_COUNT)
6765 #undef TRACE_OBJECT_COUNT
6766 #define TRACE_OBJECT_COUNT(name) \
6767 index = FIRST_FIXED_ARRAY_SUB_TYPE + name; \
6768 count = static_cast<int>(object_counts_[index]); \
6769 size = static_cast<int>(object_sizes_[index]) / KB; \
6770 TraceObjectStat("*FIXED_ARRAY_" #name, count, size, time);
6771 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(TRACE_OBJECT_COUNT)
6772 #undef TRACE_OBJECT_COUNT
6773 #define TRACE_OBJECT_COUNT(name) \
6775 FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge; \
6776 count = static_cast<int>(object_counts_[index]); \
6777 size = static_cast<int>(object_sizes_[index]) / KB; \
6778 TraceObjectStat("*CODE_AGE_" #name, count, size, time);
6779 CODE_AGE_LIST_COMPLETE(TRACE_OBJECT_COUNT)
6780 #undef TRACE_OBJECT_COUNT
6784 void Heap::CheckpointObjectStats() {
6785 base::LockGuard<base::Mutex> lock_guard(object_stats_mutex.Pointer());
6786 Counters* counters = isolate()->counters();
6787 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
6788 counters->count_of_##name()->Increment( \
6789 static_cast<int>(object_counts_[name])); \
6790 counters->count_of_##name()->Decrement( \
6791 static_cast<int>(object_counts_last_time_[name])); \
6792 counters->size_of_##name()->Increment( \
6793 static_cast<int>(object_sizes_[name])); \
6794 counters->size_of_##name()->Decrement( \
6795 static_cast<int>(object_sizes_last_time_[name]));
6796 INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6797 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6799 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
6800 index = FIRST_CODE_KIND_SUB_TYPE + Code::name; \
6801 counters->count_of_CODE_TYPE_##name()->Increment( \
6802 static_cast<int>(object_counts_[index])); \
6803 counters->count_of_CODE_TYPE_##name()->Decrement( \
6804 static_cast<int>(object_counts_last_time_[index])); \
6805 counters->size_of_CODE_TYPE_##name()->Increment( \
6806 static_cast<int>(object_sizes_[index])); \
6807 counters->size_of_CODE_TYPE_##name()->Decrement( \
6808 static_cast<int>(object_sizes_last_time_[index]));
6809 CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6810 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6811 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
6812 index = FIRST_FIXED_ARRAY_SUB_TYPE + name; \
6813 counters->count_of_FIXED_ARRAY_##name()->Increment( \
6814 static_cast<int>(object_counts_[index])); \
6815 counters->count_of_FIXED_ARRAY_##name()->Decrement( \
6816 static_cast<int>(object_counts_last_time_[index])); \
6817 counters->size_of_FIXED_ARRAY_##name()->Increment( \
6818 static_cast<int>(object_sizes_[index])); \
6819 counters->size_of_FIXED_ARRAY_##name()->Decrement( \
6820 static_cast<int>(object_sizes_last_time_[index]));
6821 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6822 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6823 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
6825 FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge; \
6826 counters->count_of_CODE_AGE_##name()->Increment( \
6827 static_cast<int>(object_counts_[index])); \
6828 counters->count_of_CODE_AGE_##name()->Decrement( \
6829 static_cast<int>(object_counts_last_time_[index])); \
6830 counters->size_of_CODE_AGE_##name()->Increment( \
6831 static_cast<int>(object_sizes_[index])); \
6832 counters->size_of_CODE_AGE_##name()->Decrement( \
6833 static_cast<int>(object_sizes_last_time_[index]));
6834 CODE_AGE_LIST_COMPLETE(ADJUST_LAST_TIME_OBJECT_COUNT)
6835 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6837 MemCopy(object_counts_last_time_, object_counts_, sizeof(object_counts_));
6838 MemCopy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_));
6843 void Heap::RegisterStrongRoots(Object** start, Object** end) {
6844 StrongRootsList* list = new StrongRootsList();
6845 list->next = strong_roots_list_;
6846 list->start = start;
6848 strong_roots_list_ = list;
6852 void Heap::UnregisterStrongRoots(Object** start) {
6853 StrongRootsList* prev = NULL;
6854 StrongRootsList* list = strong_roots_list_;
6855 while (list != nullptr) {
6856 StrongRootsList* next = list->next;
6857 if (list->start == start) {
6861 strong_roots_list_ = next;
6872 bool Heap::GetObjectTypeName(size_t index, const char** object_type,
6873 const char** object_sub_type) {
6874 if (index >= OBJECT_STATS_COUNT) return false;
6876 switch (static_cast<int>(index)) {
6877 #define COMPARE_AND_RETURN_NAME(name) \
6879 *object_type = #name; \
6880 *object_sub_type = ""; \
6882 INSTANCE_TYPE_LIST(COMPARE_AND_RETURN_NAME)
6883 #undef COMPARE_AND_RETURN_NAME
6884 #define COMPARE_AND_RETURN_NAME(name) \
6885 case FIRST_CODE_KIND_SUB_TYPE + Code::name: \
6886 *object_type = "CODE_TYPE"; \
6887 *object_sub_type = "CODE_KIND/" #name; \
6889 CODE_KIND_LIST(COMPARE_AND_RETURN_NAME)
6890 #undef COMPARE_AND_RETURN_NAME
6891 #define COMPARE_AND_RETURN_NAME(name) \
6892 case FIRST_FIXED_ARRAY_SUB_TYPE + name: \
6893 *object_type = "FIXED_ARRAY_TYPE"; \
6894 *object_sub_type = #name; \
6896 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COMPARE_AND_RETURN_NAME)
6897 #undef COMPARE_AND_RETURN_NAME
6898 #define COMPARE_AND_RETURN_NAME(name) \
6899 case FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge: \
6900 *object_type = "CODE_TYPE"; \
6901 *object_sub_type = "CODE_AGE/" #name; \
6903 CODE_AGE_LIST_COMPLETE(COMPARE_AND_RETURN_NAME)
6904 #undef COMPARE_AND_RETURN_NAME
6908 } // namespace internal