1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "accessors.h"
32 #include "bootstrapper.h"
34 #include "compilation-cache.h"
36 #include "deoptimizer.h"
37 #include "global-handles.h"
38 #include "heap-profiler.h"
39 #include "incremental-marking.h"
40 #include "liveobjectlist-inl.h"
41 #include "mark-compact.h"
43 #include "objects-visiting.h"
44 #include "objects-visiting-inl.h"
46 #include "runtime-profiler.h"
47 #include "scopeinfo.h"
49 #include "store-buffer.h"
50 #include "v8threads.h"
51 #include "vm-state-inl.h"
52 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
53 #include "regexp-macro-assembler.h"
54 #include "arm/regexp-macro-assembler-arm.h"
56 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
57 #include "regexp-macro-assembler.h"
58 #include "mips/regexp-macro-assembler-mips.h"
67 // semispace_size_ should be a power of 2 and old_generation_size_ should be
68 // a multiple of Page::kPageSize.
69 #if defined(V8_TARGET_ARCH_X64)
70 #define LUMP_OF_MEMORY (2 * MB)
71 code_range_size_(512*MB),
73 #define LUMP_OF_MEMORY MB
77 reserved_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
78 max_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
79 initial_semispace_size_(Page::kPageSize),
80 max_old_generation_size_(192*MB),
81 max_executable_size_(max_old_generation_size_),
83 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
84 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
85 initial_semispace_size_(Page::kPageSize),
86 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
87 max_executable_size_(256l * LUMP_OF_MEMORY),
90 // Variables set based on semispace_size_ and old_generation_size_ in
91 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
92 // Will be 4 * reserved_semispace_size_ to ensure that young
93 // generation can be aligned to its size.
94 survived_since_last_expansion_(0),
96 always_allocate_scope_depth_(0),
97 linear_allocation_scope_depth_(0),
98 contexts_disposed_(0),
100 scan_on_scavenge_pages_(0),
102 old_pointer_space_(NULL),
103 old_data_space_(NULL),
108 gc_state_(NOT_IN_GC),
109 gc_post_processing_depth_(0),
112 remembered_unmapped_pages_index_(0),
113 unflattened_strings_length_(0),
115 allocation_allowed_(true),
116 allocation_timeout_(0),
117 disallow_allocation_failure_(false),
120 new_space_high_promotion_mode_active_(false),
121 old_gen_promotion_limit_(kMinimumPromotionLimit),
122 old_gen_allocation_limit_(kMinimumAllocationLimit),
123 old_gen_limit_factor_(1),
124 size_of_old_gen_at_last_old_space_gc_(0),
125 external_allocation_limit_(0),
126 amount_of_external_allocated_memory_(0),
127 amount_of_external_allocated_memory_at_last_global_gc_(0),
128 old_gen_exhausted_(false),
129 store_buffer_rebuilder_(store_buffer()),
130 hidden_symbol_(NULL),
131 global_gc_prologue_callback_(NULL),
132 global_gc_epilogue_callback_(NULL),
133 gc_safe_size_of_old_object_(NULL),
134 total_regexp_code_generated_(0),
136 young_survivors_after_last_gc_(0),
137 high_survival_rate_period_length_(0),
139 previous_survival_rate_trend_(Heap::STABLE),
140 survival_rate_trend_(Heap::STABLE),
142 total_gc_time_ms_(0),
143 max_alive_after_gc_(0),
144 min_in_mutator_(kMaxInt),
145 alive_after_last_gc_(0),
146 last_gc_end_timestamp_(0.0),
149 incremental_marking_(this),
150 number_idle_notifications_(0),
151 last_idle_notification_gc_count_(0),
152 last_idle_notification_gc_count_init_(false),
153 mark_sweeps_since_idle_round_started_(0),
154 ms_count_at_last_idle_notification_(0),
155 gc_count_at_last_idle_gc_(0),
156 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
157 promotion_queue_(this),
159 chunks_queued_for_free_(NULL),
160 relocation_mutex_(NULL) {
161 // Allow build-time customization of the max semispace size. Building
162 // V8 with snapshots and a non-default max semispace size is much
163 // easier if you can define it as part of the build environment.
164 #if defined(V8_MAX_SEMISPACE_SIZE)
165 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
168 intptr_t max_virtual = OS::MaxVirtualMemory();
170 if (max_virtual > 0) {
171 if (code_range_size_ > 0) {
172 // Reserve no more than 1/8 of the memory for the code range.
173 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
177 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
178 native_contexts_list_ = NULL;
179 mark_compact_collector_.heap_ = this;
180 external_string_table_.heap_ = this;
181 // Put a dummy entry in the remembered pages so we can find the list the
182 // minidump even if there are no real unmapped pages.
183 RememberUnmappedPage(NULL, false);
185 ClearObjectStats(true);
189 intptr_t Heap::Capacity() {
190 if (!HasBeenSetUp()) return 0;
192 return new_space_.Capacity() +
193 old_pointer_space_->Capacity() +
194 old_data_space_->Capacity() +
195 code_space_->Capacity() +
196 map_space_->Capacity() +
197 cell_space_->Capacity();
201 intptr_t Heap::CommittedMemory() {
202 if (!HasBeenSetUp()) return 0;
204 return new_space_.CommittedMemory() +
205 old_pointer_space_->CommittedMemory() +
206 old_data_space_->CommittedMemory() +
207 code_space_->CommittedMemory() +
208 map_space_->CommittedMemory() +
209 cell_space_->CommittedMemory() +
213 intptr_t Heap::CommittedMemoryExecutable() {
214 if (!HasBeenSetUp()) return 0;
216 return isolate()->memory_allocator()->SizeExecutable();
220 intptr_t Heap::Available() {
221 if (!HasBeenSetUp()) return 0;
223 return new_space_.Available() +
224 old_pointer_space_->Available() +
225 old_data_space_->Available() +
226 code_space_->Available() +
227 map_space_->Available() +
228 cell_space_->Available();
232 bool Heap::HasBeenSetUp() {
233 return old_pointer_space_ != NULL &&
234 old_data_space_ != NULL &&
235 code_space_ != NULL &&
236 map_space_ != NULL &&
237 cell_space_ != NULL &&
242 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
243 if (IntrusiveMarking::IsMarked(object)) {
244 return IntrusiveMarking::SizeOfMarkedObject(object);
246 return object->SizeFromMap(object->map());
250 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
251 const char** reason) {
252 // Is global GC requested?
253 if (space != NEW_SPACE) {
254 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
255 *reason = "GC in old space requested";
256 return MARK_COMPACTOR;
259 if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
260 *reason = "GC in old space forced by flags";
261 return MARK_COMPACTOR;
264 // Is enough data promoted to justify a global GC?
265 if (OldGenerationPromotionLimitReached()) {
266 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
267 *reason = "promotion limit reached";
268 return MARK_COMPACTOR;
271 // Have allocation in OLD and LO failed?
272 if (old_gen_exhausted_) {
273 isolate_->counters()->
274 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
275 *reason = "old generations exhausted";
276 return MARK_COMPACTOR;
279 // Is there enough space left in OLD to guarantee that a scavenge can
282 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
283 // for object promotion. It counts only the bytes that the memory
284 // allocator has not yet allocated from the OS and assigned to any space,
285 // and does not count available bytes already in the old space or code
286 // space. Undercounting is safe---we may get an unrequested full GC when
287 // a scavenge would have succeeded.
288 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
289 isolate_->counters()->
290 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
291 *reason = "scavenge might not succeed";
292 return MARK_COMPACTOR;
301 // TODO(1238405): Combine the infrastructure for --heap-stats and
302 // --log-gc to avoid the complicated preprocessor and flag testing.
303 void Heap::ReportStatisticsBeforeGC() {
304 // Heap::ReportHeapStatistics will also log NewSpace statistics when
305 // compiled --log-gc is set. The following logic is used to avoid
308 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
309 if (FLAG_heap_stats) {
310 ReportHeapStatistics("Before GC");
311 } else if (FLAG_log_gc) {
312 new_space_.ReportStatistics();
314 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
317 new_space_.CollectStatistics();
318 new_space_.ReportStatistics();
319 new_space_.ClearHistograms();
325 void Heap::PrintShortHeapStatistics() {
326 if (!FLAG_trace_gc_verbose) return;
327 PrintPID("Memory allocator, used: %6" V8_PTR_PREFIX "d KB"
328 ", available: %6" V8_PTR_PREFIX "d KB\n",
329 isolate_->memory_allocator()->Size() / KB,
330 isolate_->memory_allocator()->Available() / KB);
331 PrintPID("New space, used: %6" V8_PTR_PREFIX "d KB"
332 ", available: %6" V8_PTR_PREFIX "d KB"
333 ", committed: %6" V8_PTR_PREFIX "d KB\n",
334 new_space_.Size() / KB,
335 new_space_.Available() / KB,
336 new_space_.CommittedMemory() / KB);
337 PrintPID("Old pointers, used: %6" V8_PTR_PREFIX "d KB"
338 ", available: %6" V8_PTR_PREFIX "d KB"
339 ", committed: %6" V8_PTR_PREFIX "d KB\n",
340 old_pointer_space_->SizeOfObjects() / KB,
341 old_pointer_space_->Available() / KB,
342 old_pointer_space_->CommittedMemory() / KB);
343 PrintPID("Old data space, used: %6" V8_PTR_PREFIX "d KB"
344 ", available: %6" V8_PTR_PREFIX "d KB"
345 ", committed: %6" V8_PTR_PREFIX "d KB\n",
346 old_data_space_->SizeOfObjects() / KB,
347 old_data_space_->Available() / KB,
348 old_data_space_->CommittedMemory() / KB);
349 PrintPID("Code space, used: %6" V8_PTR_PREFIX "d KB"
350 ", available: %6" V8_PTR_PREFIX "d KB"
351 ", committed: %6" V8_PTR_PREFIX "d KB\n",
352 code_space_->SizeOfObjects() / KB,
353 code_space_->Available() / KB,
354 code_space_->CommittedMemory() / KB);
355 PrintPID("Map space, used: %6" V8_PTR_PREFIX "d KB"
356 ", available: %6" V8_PTR_PREFIX "d KB"
357 ", committed: %6" V8_PTR_PREFIX "d KB\n",
358 map_space_->SizeOfObjects() / KB,
359 map_space_->Available() / KB,
360 map_space_->CommittedMemory() / KB);
361 PrintPID("Cell space, used: %6" V8_PTR_PREFIX "d KB"
362 ", available: %6" V8_PTR_PREFIX "d KB"
363 ", committed: %6" V8_PTR_PREFIX "d KB\n",
364 cell_space_->SizeOfObjects() / KB,
365 cell_space_->Available() / KB,
366 cell_space_->CommittedMemory() / KB);
367 PrintPID("Large object space, used: %6" V8_PTR_PREFIX "d KB"
368 ", available: %6" V8_PTR_PREFIX "d KB"
369 ", committed: %6" V8_PTR_PREFIX "d KB\n",
370 lo_space_->SizeOfObjects() / KB,
371 lo_space_->Available() / KB,
372 lo_space_->CommittedMemory() / KB);
373 PrintPID("Total time spent in GC : %d ms\n", total_gc_time_ms_);
377 // TODO(1238405): Combine the infrastructure for --heap-stats and
378 // --log-gc to avoid the complicated preprocessor and flag testing.
379 void Heap::ReportStatisticsAfterGC() {
380 // Similar to the before GC, we use some complicated logic to ensure that
381 // NewSpace statistics are logged exactly once when --log-gc is turned on.
383 if (FLAG_heap_stats) {
384 new_space_.CollectStatistics();
385 ReportHeapStatistics("After GC");
386 } else if (FLAG_log_gc) {
387 new_space_.ReportStatistics();
390 if (FLAG_log_gc) new_space_.ReportStatistics();
395 void Heap::GarbageCollectionPrologue() {
396 isolate_->transcendental_cache()->Clear();
397 ClearJSFunctionResultCaches();
399 unflattened_strings_length_ = 0;
401 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
402 allow_allocation(false);
404 if (FLAG_verify_heap) {
408 if (FLAG_gc_verbose) Print();
412 ReportStatisticsBeforeGC();
415 LiveObjectList::GCPrologue();
416 store_buffer()->GCPrologue();
419 intptr_t Heap::SizeOfObjects() {
422 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
423 total += space->SizeOfObjects();
428 void Heap::GarbageCollectionEpilogue() {
429 store_buffer()->GCEpilogue();
430 LiveObjectList::GCEpilogue();
432 allow_allocation(true);
435 if (FLAG_verify_heap) {
439 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
440 if (FLAG_print_handles) PrintHandles();
441 if (FLAG_gc_verbose) Print();
442 if (FLAG_code_stats) ReportCodeStatistics("After GC");
445 isolate_->counters()->alive_after_last_gc()->Set(
446 static_cast<int>(SizeOfObjects()));
448 isolate_->counters()->symbol_table_capacity()->Set(
449 symbol_table()->Capacity());
450 isolate_->counters()->number_of_symbols()->Set(
451 symbol_table()->NumberOfElements());
453 if (CommittedMemory() > 0) {
454 isolate_->counters()->external_fragmentation_total()->AddSample(
455 static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory()));
457 isolate_->counters()->heap_fraction_map_space()->AddSample(
459 (map_space()->CommittedMemory() * 100.0) / CommittedMemory()));
460 isolate_->counters()->heap_fraction_cell_space()->AddSample(
462 (cell_space()->CommittedMemory() * 100.0) / CommittedMemory()));
464 isolate_->counters()->heap_sample_total_committed()->AddSample(
465 static_cast<int>(CommittedMemory() / KB));
466 isolate_->counters()->heap_sample_total_used()->AddSample(
467 static_cast<int>(SizeOfObjects() / KB));
468 isolate_->counters()->heap_sample_map_space_committed()->AddSample(
469 static_cast<int>(map_space()->CommittedMemory() / KB));
470 isolate_->counters()->heap_sample_cell_space_committed()->AddSample(
471 static_cast<int>(cell_space()->CommittedMemory() / KB));
474 #define UPDATE_COUNTERS_FOR_SPACE(space) \
475 isolate_->counters()->space##_bytes_available()->Set( \
476 static_cast<int>(space()->Available())); \
477 isolate_->counters()->space##_bytes_committed()->Set( \
478 static_cast<int>(space()->CommittedMemory())); \
479 isolate_->counters()->space##_bytes_used()->Set( \
480 static_cast<int>(space()->SizeOfObjects()));
481 #define UPDATE_FRAGMENTATION_FOR_SPACE(space) \
482 if (space()->CommittedMemory() > 0) { \
483 isolate_->counters()->external_fragmentation_##space()->AddSample( \
484 static_cast<int>(100 - \
485 (space()->SizeOfObjects() * 100.0) / space()->CommittedMemory())); \
487 #define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space) \
488 UPDATE_COUNTERS_FOR_SPACE(space) \
489 UPDATE_FRAGMENTATION_FOR_SPACE(space)
491 UPDATE_COUNTERS_FOR_SPACE(new_space)
492 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_pointer_space)
493 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_data_space)
494 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space)
495 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space)
496 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(cell_space)
497 UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space)
498 #undef UPDATE_COUNTERS_FOR_SPACE
499 #undef UPDATE_FRAGMENTATION_FOR_SPACE
500 #undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE
503 ReportStatisticsAfterGC();
505 #ifdef ENABLE_DEBUGGER_SUPPORT
506 isolate_->debug()->AfterGarbageCollection();
507 #endif // ENABLE_DEBUGGER_SUPPORT
511 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
512 // Since we are ignoring the return value, the exact choice of space does
513 // not matter, so long as we do not specify NEW_SPACE, which would not
515 mark_compact_collector_.SetFlags(flags);
516 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
517 mark_compact_collector_.SetFlags(kNoGCFlags);
521 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
522 // Since we are ignoring the return value, the exact choice of space does
523 // not matter, so long as we do not specify NEW_SPACE, which would not
525 // Major GC would invoke weak handle callbacks on weakly reachable
526 // handles, but won't collect weakly reachable objects until next
527 // major GC. Therefore if we collect aggressively and weak handle callback
528 // has been invoked, we rerun major GC to release objects which become
530 // Note: as weak callbacks can execute arbitrary code, we cannot
531 // hope that eventually there will be no weak callbacks invocations.
532 // Therefore stop recollecting after several attempts.
533 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
534 kReduceMemoryFootprintMask);
535 isolate_->compilation_cache()->Clear();
536 const int kMaxNumberOfAttempts = 7;
537 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
538 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
542 mark_compact_collector()->SetFlags(kNoGCFlags);
546 incremental_marking()->UncommitMarkingDeque();
550 bool Heap::CollectGarbage(AllocationSpace space,
551 GarbageCollector collector,
552 const char* gc_reason,
553 const char* collector_reason) {
554 // The VM is in the GC state until exiting this function.
555 VMState state(isolate_, GC);
558 // Reset the allocation timeout to the GC interval, but make sure to
559 // allow at least a few allocations after a collection. The reason
560 // for this is that we have a lot of allocation sequences and we
561 // assume that a garbage collection will allow the subsequent
562 // allocation attempts to go through.
563 allocation_timeout_ = Max(6, FLAG_gc_interval);
566 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
567 if (FLAG_trace_incremental_marking) {
568 PrintF("[IncrementalMarking] Scavenge during marking.\n");
572 if (collector == MARK_COMPACTOR &&
573 !mark_compact_collector()->abort_incremental_marking_ &&
574 !incremental_marking()->IsStopped() &&
575 !incremental_marking()->should_hurry() &&
576 FLAG_incremental_marking_steps) {
577 // Make progress in incremental marking.
578 const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
579 incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
580 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
581 if (!incremental_marking()->IsComplete()) {
582 if (FLAG_trace_incremental_marking) {
583 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
585 collector = SCAVENGER;
586 collector_reason = "incremental marking delaying mark-sweep";
590 bool next_gc_likely_to_collect_more = false;
592 { GCTracer tracer(this, gc_reason, collector_reason);
593 GarbageCollectionPrologue();
594 // The GC count was incremented in the prologue. Tell the tracer about
596 tracer.set_gc_count(gc_count_);
598 // Tell the tracer which collector we've selected.
599 tracer.set_collector(collector);
601 HistogramTimer* rate = (collector == SCAVENGER)
602 ? isolate_->counters()->gc_scavenger()
603 : isolate_->counters()->gc_compactor();
605 next_gc_likely_to_collect_more =
606 PerformGarbageCollection(collector, &tracer);
609 GarbageCollectionEpilogue();
612 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
613 if (incremental_marking()->IsStopped()) {
614 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
615 incremental_marking()->Start();
619 return next_gc_likely_to_collect_more;
623 void Heap::PerformScavenge() {
624 GCTracer tracer(this, NULL, NULL);
625 if (incremental_marking()->IsStopped()) {
626 PerformGarbageCollection(SCAVENGER, &tracer);
628 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
634 // Helper class for verifying the symbol table.
635 class SymbolTableVerifier : public ObjectVisitor {
637 void VisitPointers(Object** start, Object** end) {
638 // Visit all HeapObject pointers in [start, end).
639 for (Object** p = start; p < end; p++) {
640 if ((*p)->IsHeapObject()) {
641 // Check that the symbol is actually a symbol.
642 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
650 static void VerifySymbolTable() {
652 SymbolTableVerifier verifier;
653 HEAP->symbol_table()->IterateElements(&verifier);
658 static bool AbortIncrementalMarkingAndCollectGarbage(
660 AllocationSpace space,
661 const char* gc_reason = NULL) {
662 heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
663 bool result = heap->CollectGarbage(space, gc_reason);
664 heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
669 void Heap::ReserveSpace(
671 int pointer_space_size,
676 int large_object_size) {
677 NewSpace* new_space = Heap::new_space();
678 PagedSpace* old_pointer_space = Heap::old_pointer_space();
679 PagedSpace* old_data_space = Heap::old_data_space();
680 PagedSpace* code_space = Heap::code_space();
681 PagedSpace* map_space = Heap::map_space();
682 PagedSpace* cell_space = Heap::cell_space();
683 LargeObjectSpace* lo_space = Heap::lo_space();
684 bool gc_performed = true;
686 static const int kThreshold = 20;
687 while (gc_performed && counter++ < kThreshold) {
688 gc_performed = false;
689 if (!new_space->ReserveSpace(new_space_size)) {
690 Heap::CollectGarbage(NEW_SPACE,
691 "failed to reserve space in the new space");
694 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
695 AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
696 "failed to reserve space in the old pointer space");
699 if (!(old_data_space->ReserveSpace(data_space_size))) {
700 AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
701 "failed to reserve space in the old data space");
704 if (!(code_space->ReserveSpace(code_space_size))) {
705 AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
706 "failed to reserve space in the code space");
709 if (!(map_space->ReserveSpace(map_space_size))) {
710 AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
711 "failed to reserve space in the map space");
714 if (!(cell_space->ReserveSpace(cell_space_size))) {
715 AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
716 "failed to reserve space in the cell space");
719 // We add a slack-factor of 2 in order to have space for a series of
720 // large-object allocations that are only just larger than the page size.
721 large_object_size *= 2;
722 // The ReserveSpace method on the large object space checks how much
723 // we can expand the old generation. This includes expansion caused by
724 // allocation in the other spaces.
725 large_object_size += cell_space_size + map_space_size + code_space_size +
726 data_space_size + pointer_space_size;
727 if (!(lo_space->ReserveSpace(large_object_size))) {
728 AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
729 "failed to reserve space in the large object space");
735 // Failed to reserve the space after several attempts.
736 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
741 void Heap::EnsureFromSpaceIsCommitted() {
742 if (new_space_.CommitFromSpaceIfNeeded()) return;
744 // Committing memory to from space failed.
745 // Try shrinking and try again.
747 if (new_space_.CommitFromSpaceIfNeeded()) return;
749 // Committing memory to from space failed again.
750 // Memory is exhausted and we will die.
751 V8::FatalProcessOutOfMemory("Committing semi space failed.");
755 void Heap::ClearJSFunctionResultCaches() {
756 if (isolate_->bootstrapper()->IsActive()) return;
758 Object* context = native_contexts_list_;
759 while (!context->IsUndefined()) {
760 // Get the caches for this context. GC can happen when the context
761 // is not fully initialized, so the caches can be undefined.
762 Object* caches_or_undefined =
763 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
764 if (!caches_or_undefined->IsUndefined()) {
765 FixedArray* caches = FixedArray::cast(caches_or_undefined);
767 int length = caches->length();
768 for (int i = 0; i < length; i++) {
769 JSFunctionResultCache::cast(caches->get(i))->Clear();
772 // Get the next context:
773 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
779 void Heap::ClearNormalizedMapCaches() {
780 if (isolate_->bootstrapper()->IsActive() &&
781 !incremental_marking()->IsMarking()) {
785 Object* context = native_contexts_list_;
786 while (!context->IsUndefined()) {
787 // GC can happen when the context is not fully initialized,
788 // so the cache can be undefined.
790 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
791 if (!cache->IsUndefined()) {
792 NormalizedMapCache::cast(cache)->Clear();
794 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
799 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
800 double survival_rate =
801 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
802 start_new_space_size;
804 if (survival_rate > kYoungSurvivalRateHighThreshold) {
805 high_survival_rate_period_length_++;
807 high_survival_rate_period_length_ = 0;
810 if (survival_rate < kYoungSurvivalRateLowThreshold) {
811 low_survival_rate_period_length_++;
813 low_survival_rate_period_length_ = 0;
816 double survival_rate_diff = survival_rate_ - survival_rate;
818 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
819 set_survival_rate_trend(DECREASING);
820 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
821 set_survival_rate_trend(INCREASING);
823 set_survival_rate_trend(STABLE);
826 survival_rate_ = survival_rate;
829 bool Heap::PerformGarbageCollection(GarbageCollector collector,
831 bool next_gc_likely_to_collect_more = false;
833 if (collector != SCAVENGER) {
834 PROFILE(isolate_, CodeMovingGCEvent());
837 if (FLAG_verify_heap) {
840 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
841 ASSERT(!allocation_allowed_);
842 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
843 global_gc_prologue_callback_();
847 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
849 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
850 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
851 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
855 EnsureFromSpaceIsCommitted();
857 int start_new_space_size = Heap::new_space()->SizeAsInt();
859 if (IsHighSurvivalRate()) {
860 // We speed up the incremental marker if it is running so that it
861 // does not fall behind the rate of promotion, which would cause a
862 // constantly growing old space.
863 incremental_marking()->NotifyOfHighPromotionRate();
866 if (collector == MARK_COMPACTOR) {
867 // Perform mark-sweep with optional compaction.
870 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
871 IsStableOrIncreasingSurvivalTrend();
873 UpdateSurvivalRateTrend(start_new_space_size);
875 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
877 if (high_survival_rate_during_scavenges &&
878 IsStableOrIncreasingSurvivalTrend()) {
879 // Stable high survival rates of young objects both during partial and
880 // full collection indicate that mutator is either building or modifying
881 // a structure with a long lifetime.
882 // In this case we aggressively raise old generation memory limits to
883 // postpone subsequent mark-sweep collection and thus trade memory
884 // space for the mutation speed.
885 old_gen_limit_factor_ = 2;
887 old_gen_limit_factor_ = 1;
890 old_gen_promotion_limit_ =
891 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
892 old_gen_allocation_limit_ =
893 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
895 old_gen_exhausted_ = false;
901 UpdateSurvivalRateTrend(start_new_space_size);
904 if (!new_space_high_promotion_mode_active_ &&
905 new_space_.Capacity() == new_space_.MaximumCapacity() &&
906 IsStableOrIncreasingSurvivalTrend() &&
907 IsHighSurvivalRate()) {
908 // Stable high survival rates even though young generation is at
909 // maximum capacity indicates that most objects will be promoted.
910 // To decrease scavenger pauses and final mark-sweep pauses, we
911 // have to limit maximal capacity of the young generation.
912 new_space_high_promotion_mode_active_ = true;
914 PrintPID("Limited new space size due to high promotion rate: %d MB\n",
915 new_space_.InitialCapacity() / MB);
917 } else if (new_space_high_promotion_mode_active_ &&
918 IsStableOrDecreasingSurvivalTrend() &&
919 IsLowSurvivalRate()) {
920 // Decreasing low survival rates might indicate that the above high
921 // promotion mode is over and we should allow the young generation
923 new_space_high_promotion_mode_active_ = false;
925 PrintPID("Unlimited new space size due to low promotion rate: %d MB\n",
926 new_space_.MaximumCapacity() / MB);
930 if (new_space_high_promotion_mode_active_ &&
931 new_space_.Capacity() > new_space_.InitialCapacity()) {
935 isolate_->counters()->objs_since_last_young()->Set(0);
937 gc_post_processing_depth_++;
938 { DisableAssertNoAllocation allow_allocation;
939 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
940 next_gc_likely_to_collect_more =
941 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
943 gc_post_processing_depth_--;
945 // Update relocatables.
946 Relocatable::PostGarbageCollectionProcessing();
948 if (collector == MARK_COMPACTOR) {
949 // Register the amount of external allocated memory.
950 amount_of_external_allocated_memory_at_last_global_gc_ =
951 amount_of_external_allocated_memory_;
954 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
955 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
956 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
957 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
961 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
962 ASSERT(!allocation_allowed_);
963 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
964 global_gc_epilogue_callback_();
966 if (FLAG_verify_heap) {
970 return next_gc_likely_to_collect_more;
974 void Heap::MarkCompact(GCTracer* tracer) {
975 gc_state_ = MARK_COMPACT;
976 LOG(isolate_, ResourceEvent("markcompact", "begin"));
978 mark_compact_collector_.Prepare(tracer);
981 tracer->set_full_gc_count(ms_count_);
983 MarkCompactPrologue();
985 mark_compact_collector_.CollectGarbage();
987 LOG(isolate_, ResourceEvent("markcompact", "end"));
989 gc_state_ = NOT_IN_GC;
991 isolate_->counters()->objs_since_last_full()->Set(0);
993 contexts_disposed_ = 0;
995 isolate_->set_context_exit_happened(false);
999 void Heap::MarkCompactPrologue() {
1000 // At any old GC clear the keyed lookup cache to enable collection of unused
1002 isolate_->keyed_lookup_cache()->Clear();
1003 isolate_->context_slot_cache()->Clear();
1004 isolate_->descriptor_lookup_cache()->Clear();
1005 RegExpResultsCache::Clear(string_split_cache());
1006 RegExpResultsCache::Clear(regexp_multiple_cache());
1008 isolate_->compilation_cache()->MarkCompactPrologue();
1010 CompletelyClearInstanceofCache();
1012 FlushNumberStringCache();
1013 if (FLAG_cleanup_code_caches_at_gc) {
1014 polymorphic_code_cache()->set_cache(undefined_value());
1017 ClearNormalizedMapCaches();
1021 Object* Heap::FindCodeObject(Address a) {
1022 return isolate()->inner_pointer_to_code_cache()->
1023 GcSafeFindCodeForInnerPointer(a);
1027 // Helper class for copying HeapObjects
1028 class ScavengeVisitor: public ObjectVisitor {
1030 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
1032 void VisitPointer(Object** p) { ScavengePointer(p); }
1034 void VisitPointers(Object** start, Object** end) {
1035 // Copy all HeapObject pointers in [start, end)
1036 for (Object** p = start; p < end; p++) ScavengePointer(p);
1040 void ScavengePointer(Object** p) {
1041 Object* object = *p;
1042 if (!heap_->InNewSpace(object)) return;
1043 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1044 reinterpret_cast<HeapObject*>(object));
1052 // Visitor class to verify pointers in code or data space do not point into
1054 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
1056 void VisitPointers(Object** start, Object**end) {
1057 for (Object** current = start; current < end; current++) {
1058 if ((*current)->IsHeapObject()) {
1059 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
1066 static void VerifyNonPointerSpacePointers() {
1067 // Verify that there are no pointers to new space in spaces where we
1068 // do not expect them.
1069 VerifyNonPointerSpacePointersVisitor v;
1070 HeapObjectIterator code_it(HEAP->code_space());
1071 for (HeapObject* object = code_it.Next();
1072 object != NULL; object = code_it.Next())
1073 object->Iterate(&v);
1075 // The old data space was normally swept conservatively so that the iterator
1076 // doesn't work, so we normally skip the next bit.
1077 if (!HEAP->old_data_space()->was_swept_conservatively()) {
1078 HeapObjectIterator data_it(HEAP->old_data_space());
1079 for (HeapObject* object = data_it.Next();
1080 object != NULL; object = data_it.Next())
1081 object->Iterate(&v);
1087 void Heap::CheckNewSpaceExpansionCriteria() {
1088 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1089 survived_since_last_expansion_ > new_space_.Capacity() &&
1090 !new_space_high_promotion_mode_active_) {
1091 // Grow the size of new space if there is room to grow, enough data
1092 // has survived scavenge since the last expansion and we are not in
1093 // high promotion mode.
1095 survived_since_last_expansion_ = 0;
1100 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1101 return heap->InNewSpace(*p) &&
1102 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1106 void Heap::ScavengeStoreBufferCallback(
1109 StoreBufferEvent event) {
1110 heap->store_buffer_rebuilder_.Callback(page, event);
1114 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1115 if (event == kStoreBufferStartScanningPagesEvent) {
1116 start_of_current_page_ = NULL;
1117 current_page_ = NULL;
1118 } else if (event == kStoreBufferScanningPageEvent) {
1119 if (current_page_ != NULL) {
1120 // If this page already overflowed the store buffer during this iteration.
1121 if (current_page_->scan_on_scavenge()) {
1122 // Then we should wipe out the entries that have been added for it.
1123 store_buffer_->SetTop(start_of_current_page_);
1124 } else if (store_buffer_->Top() - start_of_current_page_ >=
1125 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1126 // Did we find too many pointers in the previous page? The heuristic is
1127 // that no page can take more then 1/5 the remaining slots in the store
1129 current_page_->set_scan_on_scavenge(true);
1130 store_buffer_->SetTop(start_of_current_page_);
1132 // In this case the page we scanned took a reasonable number of slots in
1133 // the store buffer. It has now been rehabilitated and is no longer
1134 // marked scan_on_scavenge.
1135 ASSERT(!current_page_->scan_on_scavenge());
1138 start_of_current_page_ = store_buffer_->Top();
1139 current_page_ = page;
1140 } else if (event == kStoreBufferFullEvent) {
1141 // The current page overflowed the store buffer again. Wipe out its entries
1142 // in the store buffer and mark it scan-on-scavenge again. This may happen
1143 // several times while scanning.
1144 if (current_page_ == NULL) {
1145 // Store Buffer overflowed while scanning promoted objects. These are not
1146 // in any particular page, though they are likely to be clustered by the
1147 // allocation routines.
1148 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1150 // Store Buffer overflowed while scanning a particular old space page for
1151 // pointers to new space.
1152 ASSERT(current_page_ == page);
1153 ASSERT(page != NULL);
1154 current_page_->set_scan_on_scavenge(true);
1155 ASSERT(start_of_current_page_ != store_buffer_->Top());
1156 store_buffer_->SetTop(start_of_current_page_);
1164 void PromotionQueue::Initialize() {
1165 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1166 // entries (where each is a pair of intptr_t). This allows us to simplify
1167 // the test fpr when to switch pages.
1168 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1170 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1172 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1173 emergency_stack_ = NULL;
1178 void PromotionQueue::RelocateQueueHead() {
1179 ASSERT(emergency_stack_ == NULL);
1181 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1182 intptr_t* head_start = rear_;
1183 intptr_t* head_end =
1184 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1187 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1189 emergency_stack_ = new List<Entry>(2 * entries_count);
1191 while (head_start != head_end) {
1192 int size = static_cast<int>(*(head_start++));
1193 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1194 emergency_stack_->Add(Entry(obj, size));
1200 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1202 explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
1204 virtual Object* RetainAs(Object* object) {
1205 if (!heap_->InFromSpace(object)) {
1209 MapWord map_word = HeapObject::cast(object)->map_word();
1210 if (map_word.IsForwardingAddress()) {
1211 return map_word.ToForwardingAddress();
1221 void Heap::Scavenge() {
1222 RelocationLock relocation_lock(this);
1224 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1227 gc_state_ = SCAVENGE;
1229 // Implements Cheney's copying algorithm
1230 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1232 // Clear descriptor cache.
1233 isolate_->descriptor_lookup_cache()->Clear();
1235 // Used for updating survived_since_last_expansion_ at function end.
1236 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1238 CheckNewSpaceExpansionCriteria();
1240 SelectScavengingVisitorsTable();
1242 incremental_marking()->PrepareForScavenge();
1244 AdvanceSweepers(static_cast<int>(new_space_.Size()));
1246 // Flip the semispaces. After flipping, to space is empty, from space has
1249 new_space_.ResetAllocationInfo();
1251 // We need to sweep newly copied objects which can be either in the
1252 // to space or promoted to the old generation. For to-space
1253 // objects, we treat the bottom of the to space as a queue. Newly
1254 // copied and unswept objects lie between a 'front' mark and the
1255 // allocation pointer.
1257 // Promoted objects can go into various old-generation spaces, and
1258 // can be allocated internally in the spaces (from the free list).
1259 // We treat the top of the to space as a queue of addresses of
1260 // promoted objects. The addresses of newly promoted and unswept
1261 // objects lie between a 'front' mark and a 'rear' mark that is
1262 // updated as a side effect of promoting an object.
1264 // There is guaranteed to be enough room at the top of the to space
1265 // for the addresses of promoted objects: every object promoted
1266 // frees up its size in bytes from the top of the new space, and
1267 // objects are at least one pointer in size.
1268 Address new_space_front = new_space_.ToSpaceStart();
1269 promotion_queue_.Initialize();
1272 store_buffer()->Clean();
1275 ScavengeVisitor scavenge_visitor(this);
1277 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1279 // Copy objects reachable from the old generation.
1281 StoreBufferRebuildScope scope(this,
1283 &ScavengeStoreBufferCallback);
1284 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1287 // Copy objects reachable from cells by scavenging cell values directly.
1288 HeapObjectIterator cell_iterator(cell_space_);
1289 for (HeapObject* heap_object = cell_iterator.Next();
1290 heap_object != NULL;
1291 heap_object = cell_iterator.Next()) {
1292 if (heap_object->IsJSGlobalPropertyCell()) {
1293 JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(heap_object);
1294 Address value_address = cell->ValueAddress();
1295 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1299 // Scavenge object reachable from the native contexts list directly.
1300 scavenge_visitor.VisitPointer(BitCast<Object**>(&native_contexts_list_));
1302 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1303 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1304 &IsUnscavengedHeapObject);
1305 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1307 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1309 UpdateNewSpaceReferencesInExternalStringTable(
1310 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1312 promotion_queue_.Destroy();
1314 LiveObjectList::UpdateReferencesForScavengeGC();
1315 if (!FLAG_watch_ic_patching) {
1316 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1318 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1320 ScavengeWeakObjectRetainer weak_object_retainer(this);
1321 ProcessWeakReferences(&weak_object_retainer);
1323 ASSERT(new_space_front == new_space_.top());
1326 new_space_.set_age_mark(new_space_.top());
1328 new_space_.LowerInlineAllocationLimit(
1329 new_space_.inline_allocation_limit_step());
1331 // Update how much has survived scavenge.
1332 IncrementYoungSurvivorsCounter(static_cast<int>(
1333 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1335 LOG(isolate_, ResourceEvent("scavenge", "end"));
1337 gc_state_ = NOT_IN_GC;
1339 scavenges_since_last_idle_round_++;
1343 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1345 MapWord first_word = HeapObject::cast(*p)->map_word();
1347 if (!first_word.IsForwardingAddress()) {
1348 // Unreachable external string can be finalized.
1349 heap->FinalizeExternalString(String::cast(*p));
1353 // String is still reachable.
1354 return String::cast(first_word.ToForwardingAddress());
1358 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1359 ExternalStringTableUpdaterCallback updater_func) {
1360 if (FLAG_verify_heap) {
1361 external_string_table_.Verify();
1364 if (external_string_table_.new_space_strings_.is_empty()) return;
1366 Object** start = &external_string_table_.new_space_strings_[0];
1367 Object** end = start + external_string_table_.new_space_strings_.length();
1368 Object** last = start;
1370 for (Object** p = start; p < end; ++p) {
1371 ASSERT(InFromSpace(*p));
1372 String* target = updater_func(this, p);
1374 if (target == NULL) continue;
1376 ASSERT(target->IsExternalString());
1378 if (InNewSpace(target)) {
1379 // String is still in new space. Update the table entry.
1383 // String got promoted. Move it to the old string list.
1384 external_string_table_.AddOldString(target);
1388 ASSERT(last <= end);
1389 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1393 void Heap::UpdateReferencesInExternalStringTable(
1394 ExternalStringTableUpdaterCallback updater_func) {
1396 // Update old space string references.
1397 if (external_string_table_.old_space_strings_.length() > 0) {
1398 Object** start = &external_string_table_.old_space_strings_[0];
1399 Object** end = start + external_string_table_.old_space_strings_.length();
1400 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1403 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1407 static Object* ProcessFunctionWeakReferences(Heap* heap,
1409 WeakObjectRetainer* retainer,
1410 bool record_slots) {
1411 Object* undefined = heap->undefined_value();
1412 Object* head = undefined;
1413 JSFunction* tail = NULL;
1414 Object* candidate = function;
1415 while (candidate != undefined) {
1416 // Check whether to keep the candidate in the list.
1417 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1418 Object* retain = retainer->RetainAs(candidate);
1419 if (retain != NULL) {
1420 if (head == undefined) {
1421 // First element in the list.
1424 // Subsequent elements in the list.
1425 ASSERT(tail != NULL);
1426 tail->set_next_function_link(retain);
1428 Object** next_function =
1429 HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
1430 heap->mark_compact_collector()->RecordSlot(
1431 next_function, next_function, retain);
1434 // Retained function is new tail.
1435 candidate_function = reinterpret_cast<JSFunction*>(retain);
1436 tail = candidate_function;
1438 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1440 if (retain == undefined) break;
1443 // Move to next element in the list.
1444 candidate = candidate_function->next_function_link();
1447 // Terminate the list if there is one or more elements.
1449 tail->set_next_function_link(undefined);
1456 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1457 Object* undefined = undefined_value();
1458 Object* head = undefined;
1459 Context* tail = NULL;
1460 Object* candidate = native_contexts_list_;
1462 // We don't record weak slots during marking or scavenges.
1463 // Instead we do it once when we complete mark-compact cycle.
1464 // Note that write barrier has no effect if we are already in the middle of
1465 // compacting mark-sweep cycle and we have to record slots manually.
1467 gc_state() == MARK_COMPACT &&
1468 mark_compact_collector()->is_compacting();
1470 while (candidate != undefined) {
1471 // Check whether to keep the candidate in the list.
1472 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1473 Object* retain = retainer->RetainAs(candidate);
1474 if (retain != NULL) {
1475 if (head == undefined) {
1476 // First element in the list.
1479 // Subsequent elements in the list.
1480 ASSERT(tail != NULL);
1481 tail->set_unchecked(this,
1482 Context::NEXT_CONTEXT_LINK,
1484 UPDATE_WRITE_BARRIER);
1487 Object** next_context =
1488 HeapObject::RawField(
1489 tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
1490 mark_compact_collector()->RecordSlot(
1491 next_context, next_context, retain);
1494 // Retained context is new tail.
1495 candidate_context = reinterpret_cast<Context*>(retain);
1496 tail = candidate_context;
1498 if (retain == undefined) break;
1500 // Process the weak list of optimized functions for the context.
1501 Object* function_list_head =
1502 ProcessFunctionWeakReferences(
1504 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1507 candidate_context->set_unchecked(this,
1508 Context::OPTIMIZED_FUNCTIONS_LIST,
1510 UPDATE_WRITE_BARRIER);
1512 Object** optimized_functions =
1513 HeapObject::RawField(
1514 tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
1515 mark_compact_collector()->RecordSlot(
1516 optimized_functions, optimized_functions, function_list_head);
1520 // Move to next element in the list.
1521 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1524 // Terminate the list if there is one or more elements.
1526 tail->set_unchecked(this,
1527 Context::NEXT_CONTEXT_LINK,
1528 Heap::undefined_value(),
1529 UPDATE_WRITE_BARRIER);
1532 // Update the head of the list of contexts.
1533 native_contexts_list_ = head;
1537 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1538 AssertNoAllocation no_allocation;
1540 class VisitorAdapter : public ObjectVisitor {
1542 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1543 : visitor_(visitor) {}
1544 virtual void VisitPointers(Object** start, Object** end) {
1545 for (Object** p = start; p < end; p++) {
1546 if ((*p)->IsExternalString()) {
1547 visitor_->VisitExternalString(Utils::ToLocal(
1548 Handle<String>(String::cast(*p))));
1553 v8::ExternalResourceVisitor* visitor_;
1554 } visitor_adapter(visitor);
1555 external_string_table_.Iterate(&visitor_adapter);
1559 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1561 static inline void VisitPointer(Heap* heap, Object** p) {
1562 Object* object = *p;
1563 if (!heap->InNewSpace(object)) return;
1564 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1565 reinterpret_cast<HeapObject*>(object));
1570 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1571 Address new_space_front) {
1573 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1574 // The addresses new_space_front and new_space_.top() define a
1575 // queue of unprocessed copied objects. Process them until the
1577 while (new_space_front != new_space_.top()) {
1578 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1579 HeapObject* object = HeapObject::FromAddress(new_space_front);
1581 NewSpaceScavenger::IterateBody(object->map(), object);
1584 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1588 // Promote and process all the to-be-promoted objects.
1590 StoreBufferRebuildScope scope(this,
1592 &ScavengeStoreBufferCallback);
1593 while (!promotion_queue()->is_empty()) {
1596 promotion_queue()->remove(&target, &size);
1598 // Promoted object might be already partially visited
1599 // during old space pointer iteration. Thus we search specificly
1600 // for pointers to from semispace instead of looking for pointers
1602 ASSERT(!target->IsMap());
1603 IterateAndMarkPointersToFromSpace(target->address(),
1604 target->address() + size,
1609 // Take another spin if there are now unswept objects in new space
1610 // (there are currently no more unswept promoted objects).
1611 } while (new_space_front != new_space_.top());
1613 return new_space_front;
1617 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
1620 INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
1624 static HeapObject* EnsureDoubleAligned(Heap* heap,
1627 if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
1628 heap->CreateFillerObjectAt(object->address(), kPointerSize);
1629 return HeapObject::FromAddress(object->address() + kPointerSize);
1631 heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
1638 enum LoggingAndProfiling {
1639 LOGGING_AND_PROFILING_ENABLED,
1640 LOGGING_AND_PROFILING_DISABLED
1644 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1647 template<MarksHandling marks_handling,
1648 LoggingAndProfiling logging_and_profiling_mode>
1649 class ScavengingVisitor : public StaticVisitorBase {
1651 static void Initialize() {
1652 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1653 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1654 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1655 table_.Register(kVisitByteArray, &EvacuateByteArray);
1656 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1657 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1659 table_.Register(kVisitNativeContext,
1660 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1661 template VisitSpecialized<Context::kSize>);
1663 table_.Register(kVisitConsString,
1664 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1665 template VisitSpecialized<ConsString::kSize>);
1667 table_.Register(kVisitSlicedString,
1668 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1669 template VisitSpecialized<SlicedString::kSize>);
1671 table_.Register(kVisitSharedFunctionInfo,
1672 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1673 template VisitSpecialized<SharedFunctionInfo::kSize>);
1675 table_.Register(kVisitJSWeakMap,
1676 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1679 table_.Register(kVisitJSRegExp,
1680 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1683 if (marks_handling == IGNORE_MARKS) {
1684 table_.Register(kVisitJSFunction,
1685 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1686 template VisitSpecialized<JSFunction::kSize>);
1688 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1691 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1693 kVisitDataObjectGeneric>();
1695 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1697 kVisitJSObjectGeneric>();
1699 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1701 kVisitStructGeneric>();
1704 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1709 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1710 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1712 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1713 bool should_record = false;
1715 should_record = FLAG_heap_stats;
1717 should_record = should_record || FLAG_log_gc;
1718 if (should_record) {
1719 if (heap->new_space()->Contains(obj)) {
1720 heap->new_space()->RecordAllocation(obj);
1722 heap->new_space()->RecordPromotion(obj);
1727 // Helper function used by CopyObject to copy a source object to an
1728 // allocated target object and update the forwarding pointer in the source
1729 // object. Returns the target object.
1730 INLINE(static void MigrateObject(Heap* heap,
1734 // Copy the content of source to target.
1735 heap->CopyBlock(target->address(), source->address(), size);
1737 // Set the forwarding address.
1738 source->set_map_word(MapWord::FromForwardingAddress(target));
1740 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1741 // Update NewSpace stats if necessary.
1742 RecordCopiedObject(heap, target);
1743 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1744 Isolate* isolate = heap->isolate();
1745 if (isolate->logger()->is_logging_code_events() ||
1746 CpuProfiler::is_profiling(isolate)) {
1747 if (target->IsSharedFunctionInfo()) {
1748 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1749 source->address(), target->address()));
1754 if (marks_handling == TRANSFER_MARKS) {
1755 if (Marking::TransferColor(source, target)) {
1756 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1762 template<ObjectContents object_contents,
1763 SizeRestriction size_restriction,
1765 static inline void EvacuateObject(Map* map,
1769 SLOW_ASSERT((size_restriction != SMALL) ||
1770 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1771 SLOW_ASSERT(object->Size() == object_size);
1773 int allocation_size = object_size;
1774 if (alignment != kObjectAlignment) {
1775 ASSERT(alignment == kDoubleAlignment);
1776 allocation_size += kPointerSize;
1779 Heap* heap = map->GetHeap();
1780 if (heap->ShouldBePromoted(object->address(), object_size)) {
1781 MaybeObject* maybe_result;
1783 if ((size_restriction != SMALL) &&
1784 (allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
1785 maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
1788 if (object_contents == DATA_OBJECT) {
1789 maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
1792 heap->old_pointer_space()->AllocateRaw(allocation_size);
1796 Object* result = NULL; // Initialization to please compiler.
1797 if (maybe_result->ToObject(&result)) {
1798 HeapObject* target = HeapObject::cast(result);
1800 if (alignment != kObjectAlignment) {
1801 target = EnsureDoubleAligned(heap, target, allocation_size);
1804 // Order is important: slot might be inside of the target if target
1805 // was allocated over a dead object and slot comes from the store
1808 MigrateObject(heap, object, target, object_size);
1810 if (object_contents == POINTER_OBJECT) {
1811 if (map->instance_type() == JS_FUNCTION_TYPE) {
1812 heap->promotion_queue()->insert(
1813 target, JSFunction::kNonWeakFieldsEndOffset);
1815 heap->promotion_queue()->insert(target, object_size);
1819 heap->tracer()->increment_promoted_objects_size(object_size);
1823 MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
1824 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1825 Object* result = allocation->ToObjectUnchecked();
1826 HeapObject* target = HeapObject::cast(result);
1828 if (alignment != kObjectAlignment) {
1829 target = EnsureDoubleAligned(heap, target, allocation_size);
1832 // Order is important: slot might be inside of the target if target
1833 // was allocated over a dead object and slot comes from the store
1836 MigrateObject(heap, object, target, object_size);
1841 static inline void EvacuateJSFunction(Map* map,
1843 HeapObject* object) {
1844 ObjectEvacuationStrategy<POINTER_OBJECT>::
1845 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1847 HeapObject* target = *slot;
1848 MarkBit mark_bit = Marking::MarkBitFrom(target);
1849 if (Marking::IsBlack(mark_bit)) {
1850 // This object is black and it might not be rescanned by marker.
1851 // We should explicitly record code entry slot for compaction because
1852 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1853 // miss it as it is not HeapObject-tagged.
1854 Address code_entry_slot =
1855 target->address() + JSFunction::kCodeEntryOffset;
1856 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1857 map->GetHeap()->mark_compact_collector()->
1858 RecordCodeEntrySlot(code_entry_slot, code);
1863 static inline void EvacuateFixedArray(Map* map,
1865 HeapObject* object) {
1866 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1867 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
1874 static inline void EvacuateFixedDoubleArray(Map* map,
1876 HeapObject* object) {
1877 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1878 int object_size = FixedDoubleArray::SizeFor(length);
1879 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
1887 static inline void EvacuateByteArray(Map* map,
1889 HeapObject* object) {
1890 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1891 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1892 map, slot, object, object_size);
1896 static inline void EvacuateSeqAsciiString(Map* map,
1898 HeapObject* object) {
1899 int object_size = SeqAsciiString::cast(object)->
1900 SeqAsciiStringSize(map->instance_type());
1901 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1902 map, slot, object, object_size);
1906 static inline void EvacuateSeqTwoByteString(Map* map,
1908 HeapObject* object) {
1909 int object_size = SeqTwoByteString::cast(object)->
1910 SeqTwoByteStringSize(map->instance_type());
1911 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1912 map, slot, object, object_size);
1916 static inline bool IsShortcutCandidate(int type) {
1917 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1920 static inline void EvacuateShortcutCandidate(Map* map,
1922 HeapObject* object) {
1923 ASSERT(IsShortcutCandidate(map->instance_type()));
1925 Heap* heap = map->GetHeap();
1927 if (marks_handling == IGNORE_MARKS &&
1928 ConsString::cast(object)->unchecked_second() ==
1929 heap->empty_string()) {
1931 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1935 if (!heap->InNewSpace(first)) {
1936 object->set_map_word(MapWord::FromForwardingAddress(first));
1940 MapWord first_word = first->map_word();
1941 if (first_word.IsForwardingAddress()) {
1942 HeapObject* target = first_word.ToForwardingAddress();
1945 object->set_map_word(MapWord::FromForwardingAddress(target));
1949 heap->DoScavengeObject(first->map(), slot, first);
1950 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1954 int object_size = ConsString::kSize;
1955 EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
1956 map, slot, object, object_size);
1959 template<ObjectContents object_contents>
1960 class ObjectEvacuationStrategy {
1962 template<int object_size>
1963 static inline void VisitSpecialized(Map* map,
1965 HeapObject* object) {
1966 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1967 map, slot, object, object_size);
1970 static inline void Visit(Map* map,
1972 HeapObject* object) {
1973 int object_size = map->instance_size();
1974 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1975 map, slot, object, object_size);
1979 static VisitorDispatchTable<ScavengingCallback> table_;
1983 template<MarksHandling marks_handling,
1984 LoggingAndProfiling logging_and_profiling_mode>
1985 VisitorDispatchTable<ScavengingCallback>
1986 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1989 static void InitializeScavengingVisitorsTables() {
1990 ScavengingVisitor<TRANSFER_MARKS,
1991 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1992 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1993 ScavengingVisitor<TRANSFER_MARKS,
1994 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1995 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1999 void Heap::SelectScavengingVisitorsTable() {
2000 bool logging_and_profiling =
2001 isolate()->logger()->is_logging() ||
2002 CpuProfiler::is_profiling(isolate()) ||
2003 (isolate()->heap_profiler() != NULL &&
2004 isolate()->heap_profiler()->is_profiling());
2006 if (!incremental_marking()->IsMarking()) {
2007 if (!logging_and_profiling) {
2008 scavenging_visitors_table_.CopyFrom(
2009 ScavengingVisitor<IGNORE_MARKS,
2010 LOGGING_AND_PROFILING_DISABLED>::GetTable());
2012 scavenging_visitors_table_.CopyFrom(
2013 ScavengingVisitor<IGNORE_MARKS,
2014 LOGGING_AND_PROFILING_ENABLED>::GetTable());
2017 if (!logging_and_profiling) {
2018 scavenging_visitors_table_.CopyFrom(
2019 ScavengingVisitor<TRANSFER_MARKS,
2020 LOGGING_AND_PROFILING_DISABLED>::GetTable());
2022 scavenging_visitors_table_.CopyFrom(
2023 ScavengingVisitor<TRANSFER_MARKS,
2024 LOGGING_AND_PROFILING_ENABLED>::GetTable());
2027 if (incremental_marking()->IsCompacting()) {
2028 // When compacting forbid short-circuiting of cons-strings.
2029 // Scavenging code relies on the fact that new space object
2030 // can't be evacuated into evacuation candidate but
2031 // short-circuiting violates this assumption.
2032 scavenging_visitors_table_.Register(
2033 StaticVisitorBase::kVisitShortcutCandidate,
2034 scavenging_visitors_table_.GetVisitorById(
2035 StaticVisitorBase::kVisitConsString));
2041 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
2042 SLOW_ASSERT(HEAP->InFromSpace(object));
2043 MapWord first_word = object->map_word();
2044 SLOW_ASSERT(!first_word.IsForwardingAddress());
2045 Map* map = first_word.ToMap();
2046 map->GetHeap()->DoScavengeObject(map, p, object);
2050 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
2051 int instance_size) {
2053 MaybeObject* maybe_result = AllocateRawMap();
2054 if (!maybe_result->ToObject(&result)) return maybe_result;
2056 // Map::cast cannot be used due to uninitialized map field.
2057 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
2058 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
2059 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2060 reinterpret_cast<Map*>(result)->set_visitor_id(
2061 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2062 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2063 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
2064 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2065 reinterpret_cast<Map*>(result)->set_bit_field(0);
2066 reinterpret_cast<Map*>(result)->set_bit_field2(0);
2067 reinterpret_cast<Map*>(result)->set_bit_field3(0);
2072 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
2074 ElementsKind elements_kind) {
2076 MaybeObject* maybe_result = AllocateRawMap();
2077 if (!maybe_result->To(&result)) return maybe_result;
2079 Map* map = reinterpret_cast<Map*>(result);
2080 map->set_map_no_write_barrier(meta_map());
2081 map->set_instance_type(instance_type);
2082 map->set_visitor_id(
2083 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2084 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2085 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
2086 map->set_instance_size(instance_size);
2087 map->set_inobject_properties(0);
2088 map->set_pre_allocated_property_fields(0);
2089 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2090 map->init_back_pointer(undefined_value());
2091 map->set_unused_property_fields(0);
2092 map->set_bit_field(0);
2093 map->set_bit_field2(1 << Map::kIsExtensible);
2094 int bit_field3 = Map::EnumLengthBits::encode(Map::kInvalidEnumCache);
2095 map->set_bit_field3(bit_field3);
2096 map->set_elements_kind(elements_kind);
2098 // If the map object is aligned fill the padding area with Smi 0 objects.
2099 if (Map::kPadStart < Map::kSize) {
2100 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
2102 Map::kSize - Map::kPadStart);
2108 MaybeObject* Heap::AllocateCodeCache() {
2109 CodeCache* code_cache;
2110 { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
2111 if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
2113 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2114 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
2119 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
2120 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
2124 MaybeObject* Heap::AllocateAccessorPair() {
2125 AccessorPair* accessors;
2126 { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
2127 if (!maybe_accessors->To(&accessors)) return maybe_accessors;
2129 accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
2130 accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
2135 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
2136 TypeFeedbackInfo* info;
2137 { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
2138 if (!maybe_info->To(&info)) return maybe_info;
2140 info->initialize_storage();
2141 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
2142 SKIP_WRITE_BARRIER);
2147 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
2148 AliasedArgumentsEntry* entry;
2149 { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
2150 if (!maybe_entry->To(&entry)) return maybe_entry;
2152 entry->set_aliased_context_slot(aliased_context_slot);
2157 const Heap::StringTypeTable Heap::string_type_table[] = {
2158 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
2159 {type, size, k##camel_name##MapRootIndex},
2160 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2161 #undef STRING_TYPE_ELEMENT
2165 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
2166 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
2167 {contents, k##name##RootIndex},
2168 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
2169 #undef CONSTANT_SYMBOL_ELEMENT
2173 const Heap::StructTable Heap::struct_table[] = {
2174 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
2175 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
2176 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2177 #undef STRUCT_TABLE_ELEMENT
2181 bool Heap::CreateInitialMaps() {
2183 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2184 if (!maybe_obj->ToObject(&obj)) return false;
2186 // Map::cast cannot be used due to uninitialized map field.
2187 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2188 set_meta_map(new_meta_map);
2189 new_meta_map->set_map(new_meta_map);
2191 { MaybeObject* maybe_obj =
2192 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2193 if (!maybe_obj->ToObject(&obj)) return false;
2195 set_fixed_array_map(Map::cast(obj));
2197 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2198 if (!maybe_obj->ToObject(&obj)) return false;
2200 set_oddball_map(Map::cast(obj));
2202 // Allocate the empty array.
2203 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2204 if (!maybe_obj->ToObject(&obj)) return false;
2206 set_empty_fixed_array(FixedArray::cast(obj));
2208 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2209 if (!maybe_obj->ToObject(&obj)) return false;
2211 set_null_value(Oddball::cast(obj));
2212 Oddball::cast(obj)->set_kind(Oddball::kNull);
2214 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2215 if (!maybe_obj->ToObject(&obj)) return false;
2217 set_undefined_value(Oddball::cast(obj));
2218 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2219 ASSERT(!InNewSpace(undefined_value()));
2221 // Allocate the empty descriptor array.
2222 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2223 if (!maybe_obj->ToObject(&obj)) return false;
2225 set_empty_descriptor_array(DescriptorArray::cast(obj));
2227 // Fix the instance_descriptors for the existing maps.
2228 meta_map()->set_code_cache(empty_fixed_array());
2229 meta_map()->init_back_pointer(undefined_value());
2231 fixed_array_map()->set_code_cache(empty_fixed_array());
2232 fixed_array_map()->init_back_pointer(undefined_value());
2234 oddball_map()->set_code_cache(empty_fixed_array());
2235 oddball_map()->init_back_pointer(undefined_value());
2237 // Fix prototype object for existing maps.
2238 meta_map()->set_prototype(null_value());
2239 meta_map()->set_constructor(null_value());
2241 fixed_array_map()->set_prototype(null_value());
2242 fixed_array_map()->set_constructor(null_value());
2244 oddball_map()->set_prototype(null_value());
2245 oddball_map()->set_constructor(null_value());
2247 { MaybeObject* maybe_obj =
2248 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2249 if (!maybe_obj->ToObject(&obj)) return false;
2251 set_fixed_cow_array_map(Map::cast(obj));
2252 ASSERT(fixed_array_map() != fixed_cow_array_map());
2254 { MaybeObject* maybe_obj =
2255 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2256 if (!maybe_obj->ToObject(&obj)) return false;
2258 set_scope_info_map(Map::cast(obj));
2260 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2261 if (!maybe_obj->ToObject(&obj)) return false;
2263 set_heap_number_map(Map::cast(obj));
2265 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2266 if (!maybe_obj->ToObject(&obj)) return false;
2268 set_foreign_map(Map::cast(obj));
2270 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2271 const StringTypeTable& entry = string_type_table[i];
2272 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2273 if (!maybe_obj->ToObject(&obj)) return false;
2275 roots_[entry.index] = Map::cast(obj);
2278 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2279 if (!maybe_obj->ToObject(&obj)) return false;
2281 set_undetectable_string_map(Map::cast(obj));
2282 Map::cast(obj)->set_is_undetectable();
2284 { MaybeObject* maybe_obj =
2285 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2286 if (!maybe_obj->ToObject(&obj)) return false;
2288 set_undetectable_ascii_string_map(Map::cast(obj));
2289 Map::cast(obj)->set_is_undetectable();
2291 { MaybeObject* maybe_obj =
2292 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2293 if (!maybe_obj->ToObject(&obj)) return false;
2295 set_fixed_double_array_map(Map::cast(obj));
2297 { MaybeObject* maybe_obj =
2298 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2299 if (!maybe_obj->ToObject(&obj)) return false;
2301 set_byte_array_map(Map::cast(obj));
2303 { MaybeObject* maybe_obj =
2304 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2305 if (!maybe_obj->ToObject(&obj)) return false;
2307 set_free_space_map(Map::cast(obj));
2309 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2310 if (!maybe_obj->ToObject(&obj)) return false;
2312 set_empty_byte_array(ByteArray::cast(obj));
2314 { MaybeObject* maybe_obj =
2315 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2316 if (!maybe_obj->ToObject(&obj)) return false;
2318 set_external_pixel_array_map(Map::cast(obj));
2320 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2321 ExternalArray::kAlignedSize);
2322 if (!maybe_obj->ToObject(&obj)) return false;
2324 set_external_byte_array_map(Map::cast(obj));
2326 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2327 ExternalArray::kAlignedSize);
2328 if (!maybe_obj->ToObject(&obj)) return false;
2330 set_external_unsigned_byte_array_map(Map::cast(obj));
2332 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2333 ExternalArray::kAlignedSize);
2334 if (!maybe_obj->ToObject(&obj)) return false;
2336 set_external_short_array_map(Map::cast(obj));
2338 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2339 ExternalArray::kAlignedSize);
2340 if (!maybe_obj->ToObject(&obj)) return false;
2342 set_external_unsigned_short_array_map(Map::cast(obj));
2344 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2345 ExternalArray::kAlignedSize);
2346 if (!maybe_obj->ToObject(&obj)) return false;
2348 set_external_int_array_map(Map::cast(obj));
2350 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2351 ExternalArray::kAlignedSize);
2352 if (!maybe_obj->ToObject(&obj)) return false;
2354 set_external_unsigned_int_array_map(Map::cast(obj));
2356 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2357 ExternalArray::kAlignedSize);
2358 if (!maybe_obj->ToObject(&obj)) return false;
2360 set_external_float_array_map(Map::cast(obj));
2362 { MaybeObject* maybe_obj =
2363 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2364 if (!maybe_obj->ToObject(&obj)) return false;
2366 set_non_strict_arguments_elements_map(Map::cast(obj));
2368 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2369 ExternalArray::kAlignedSize);
2370 if (!maybe_obj->ToObject(&obj)) return false;
2372 set_external_double_array_map(Map::cast(obj));
2374 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2375 if (!maybe_obj->ToObject(&obj)) return false;
2377 set_code_map(Map::cast(obj));
2379 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2380 JSGlobalPropertyCell::kSize);
2381 if (!maybe_obj->ToObject(&obj)) return false;
2383 set_global_property_cell_map(Map::cast(obj));
2385 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2386 if (!maybe_obj->ToObject(&obj)) return false;
2388 set_one_pointer_filler_map(Map::cast(obj));
2390 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2391 if (!maybe_obj->ToObject(&obj)) return false;
2393 set_two_pointer_filler_map(Map::cast(obj));
2395 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2396 const StructTable& entry = struct_table[i];
2397 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2398 if (!maybe_obj->ToObject(&obj)) return false;
2400 roots_[entry.index] = Map::cast(obj);
2403 { MaybeObject* maybe_obj =
2404 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2405 if (!maybe_obj->ToObject(&obj)) return false;
2407 set_hash_table_map(Map::cast(obj));
2409 { MaybeObject* maybe_obj =
2410 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2411 if (!maybe_obj->ToObject(&obj)) return false;
2413 set_function_context_map(Map::cast(obj));
2415 { MaybeObject* maybe_obj =
2416 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2417 if (!maybe_obj->ToObject(&obj)) return false;
2419 set_catch_context_map(Map::cast(obj));
2421 { MaybeObject* maybe_obj =
2422 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2423 if (!maybe_obj->ToObject(&obj)) return false;
2425 set_with_context_map(Map::cast(obj));
2427 { MaybeObject* maybe_obj =
2428 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2429 if (!maybe_obj->ToObject(&obj)) return false;
2431 set_block_context_map(Map::cast(obj));
2433 { MaybeObject* maybe_obj =
2434 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2435 if (!maybe_obj->ToObject(&obj)) return false;
2437 set_module_context_map(Map::cast(obj));
2439 { MaybeObject* maybe_obj =
2440 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2441 if (!maybe_obj->ToObject(&obj)) return false;
2443 set_global_context_map(Map::cast(obj));
2445 { MaybeObject* maybe_obj =
2446 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2447 if (!maybe_obj->ToObject(&obj)) return false;
2449 Map* native_context_map = Map::cast(obj);
2450 native_context_map->set_dictionary_map(true);
2451 native_context_map->set_visitor_id(StaticVisitorBase::kVisitNativeContext);
2452 set_native_context_map(native_context_map);
2454 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2455 SharedFunctionInfo::kAlignedSize);
2456 if (!maybe_obj->ToObject(&obj)) return false;
2458 set_shared_function_info_map(Map::cast(obj));
2460 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2461 JSMessageObject::kSize);
2462 if (!maybe_obj->ToObject(&obj)) return false;
2464 set_message_object_map(Map::cast(obj));
2466 ASSERT(!InNewSpace(empty_fixed_array()));
2471 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2472 // Statically ensure that it is safe to allocate heap numbers in paged
2474 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2475 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2478 { MaybeObject* maybe_result =
2479 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2480 if (!maybe_result->ToObject(&result)) return maybe_result;
2483 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2484 HeapNumber::cast(result)->set_value(value);
2489 MaybeObject* Heap::AllocateHeapNumber(double value) {
2490 // Use general version, if we're forced to always allocate.
2491 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2493 // This version of AllocateHeapNumber is optimized for
2494 // allocation in new space.
2495 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2496 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2498 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2499 if (!maybe_result->ToObject(&result)) return maybe_result;
2501 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2502 HeapNumber::cast(result)->set_value(value);
2507 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2509 { MaybeObject* maybe_result = AllocateRawCell();
2510 if (!maybe_result->ToObject(&result)) return maybe_result;
2512 HeapObject::cast(result)->set_map_no_write_barrier(
2513 global_property_cell_map());
2514 JSGlobalPropertyCell::cast(result)->set_value(value);
2519 MaybeObject* Heap::CreateOddball(const char* to_string,
2523 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2524 if (!maybe_result->ToObject(&result)) return maybe_result;
2526 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2530 bool Heap::CreateApiObjects() {
2533 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2534 if (!maybe_obj->ToObject(&obj)) return false;
2536 // Don't use Smi-only elements optimizations for objects with the neander
2537 // map. There are too many cases where element values are set directly with a
2538 // bottleneck to trap the Smi-only -> fast elements transition, and there
2539 // appears to be no benefit for optimize this case.
2540 Map* new_neander_map = Map::cast(obj);
2541 new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
2542 set_neander_map(new_neander_map);
2544 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2545 if (!maybe_obj->ToObject(&obj)) return false;
2548 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2549 if (!maybe_elements->ToObject(&elements)) return false;
2551 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2552 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2553 set_message_listeners(JSObject::cast(obj));
2559 void Heap::CreateJSEntryStub() {
2561 set_js_entry_code(*stub.GetCode());
2565 void Heap::CreateJSConstructEntryStub() {
2566 JSConstructEntryStub stub;
2567 set_js_construct_entry_code(*stub.GetCode());
2571 void Heap::CreateFixedStubs() {
2572 // Here we create roots for fixed stubs. They are needed at GC
2573 // for cooking and uncooking (check out frames.cc).
2574 // The eliminates the need for doing dictionary lookup in the
2575 // stub cache for these stubs.
2577 // gcc-4.4 has problem generating correct code of following snippet:
2578 // { JSEntryStub stub;
2579 // js_entry_code_ = *stub.GetCode();
2581 // { JSConstructEntryStub stub;
2582 // js_construct_entry_code_ = *stub.GetCode();
2584 // To workaround the problem, make separate functions without inlining.
2585 Heap::CreateJSEntryStub();
2586 Heap::CreateJSConstructEntryStub();
2588 // Create stubs that should be there, so we don't unexpectedly have to
2589 // create them if we need them during the creation of another stub.
2590 // Stub creation mixes raw pointers and handles in an unsafe manner so
2591 // we cannot create stubs while we are creating stubs.
2592 CodeStub::GenerateStubsAheadOfTime();
2596 bool Heap::CreateInitialObjects() {
2599 // The -0 value must be set before NumberFromDouble works.
2600 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2601 if (!maybe_obj->ToObject(&obj)) return false;
2603 set_minus_zero_value(HeapNumber::cast(obj));
2604 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2606 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2607 if (!maybe_obj->ToObject(&obj)) return false;
2609 set_nan_value(HeapNumber::cast(obj));
2611 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2612 if (!maybe_obj->ToObject(&obj)) return false;
2614 set_infinity_value(HeapNumber::cast(obj));
2616 // The hole has not been created yet, but we want to put something
2617 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2618 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2620 // Allocate initial symbol table.
2621 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2622 if (!maybe_obj->ToObject(&obj)) return false;
2624 // Don't use set_symbol_table() due to asserts.
2625 roots_[kSymbolTableRootIndex] = obj;
2627 // Finish initializing oddballs after creating symboltable.
2628 { MaybeObject* maybe_obj =
2629 undefined_value()->Initialize("undefined",
2631 Oddball::kUndefined);
2632 if (!maybe_obj->ToObject(&obj)) return false;
2635 // Initialize the null_value.
2636 { MaybeObject* maybe_obj =
2637 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2638 if (!maybe_obj->ToObject(&obj)) return false;
2641 { MaybeObject* maybe_obj = CreateOddball("true",
2644 if (!maybe_obj->ToObject(&obj)) return false;
2646 set_true_value(Oddball::cast(obj));
2648 { MaybeObject* maybe_obj = CreateOddball("false",
2651 if (!maybe_obj->ToObject(&obj)) return false;
2653 set_false_value(Oddball::cast(obj));
2655 { MaybeObject* maybe_obj = CreateOddball("hole",
2658 if (!maybe_obj->ToObject(&obj)) return false;
2660 set_the_hole_value(Oddball::cast(obj));
2662 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2664 Oddball::kArgumentMarker);
2665 if (!maybe_obj->ToObject(&obj)) return false;
2667 set_arguments_marker(Oddball::cast(obj));
2669 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2672 if (!maybe_obj->ToObject(&obj)) return false;
2674 set_no_interceptor_result_sentinel(obj);
2676 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2679 if (!maybe_obj->ToObject(&obj)) return false;
2681 set_termination_exception(obj);
2683 // Allocate the empty string.
2684 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2685 if (!maybe_obj->ToObject(&obj)) return false;
2687 set_empty_string(String::cast(obj));
2689 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2690 { MaybeObject* maybe_obj =
2691 LookupAsciiSymbol(constant_symbol_table[i].contents);
2692 if (!maybe_obj->ToObject(&obj)) return false;
2694 roots_[constant_symbol_table[i].index] = String::cast(obj);
2697 // Allocate the hidden symbol which is used to identify the hidden properties
2698 // in JSObjects. The hash code has a special value so that it will not match
2699 // the empty string when searching for the property. It cannot be part of the
2700 // loop above because it needs to be allocated manually with the special
2701 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2702 // that it will always be at the first entry in property descriptors.
2703 { MaybeObject* maybe_obj =
2704 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2705 if (!maybe_obj->ToObject(&obj)) return false;
2707 hidden_symbol_ = String::cast(obj);
2709 // Allocate the foreign for __proto__.
2710 { MaybeObject* maybe_obj =
2711 AllocateForeign((Address) &Accessors::ObjectPrototype);
2712 if (!maybe_obj->ToObject(&obj)) return false;
2714 set_prototype_accessors(Foreign::cast(obj));
2716 // Allocate the code_stubs dictionary. The initial size is set to avoid
2717 // expanding the dictionary during bootstrapping.
2718 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2719 if (!maybe_obj->ToObject(&obj)) return false;
2721 set_code_stubs(UnseededNumberDictionary::cast(obj));
2724 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2725 // is set to avoid expanding the dictionary during bootstrapping.
2726 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2727 if (!maybe_obj->ToObject(&obj)) return false;
2729 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2731 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2732 if (!maybe_obj->ToObject(&obj)) return false;
2734 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2736 set_instanceof_cache_function(Smi::FromInt(0));
2737 set_instanceof_cache_map(Smi::FromInt(0));
2738 set_instanceof_cache_answer(Smi::FromInt(0));
2742 // Allocate the dictionary of intrinsic function names.
2743 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2744 if (!maybe_obj->ToObject(&obj)) return false;
2746 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2748 if (!maybe_obj->ToObject(&obj)) return false;
2750 set_intrinsic_function_names(StringDictionary::cast(obj));
2752 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2753 if (!maybe_obj->ToObject(&obj)) return false;
2755 set_number_string_cache(FixedArray::cast(obj));
2757 // Allocate cache for single character ASCII strings.
2758 { MaybeObject* maybe_obj =
2759 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2760 if (!maybe_obj->ToObject(&obj)) return false;
2762 set_single_character_string_cache(FixedArray::cast(obj));
2764 // Allocate cache for string split.
2765 { MaybeObject* maybe_obj = AllocateFixedArray(
2766 RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
2767 if (!maybe_obj->ToObject(&obj)) return false;
2769 set_string_split_cache(FixedArray::cast(obj));
2771 { MaybeObject* maybe_obj = AllocateFixedArray(
2772 RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
2773 if (!maybe_obj->ToObject(&obj)) return false;
2775 set_regexp_multiple_cache(FixedArray::cast(obj));
2777 // Allocate cache for external strings pointing to native source code.
2778 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2779 if (!maybe_obj->ToObject(&obj)) return false;
2781 set_natives_source_cache(FixedArray::cast(obj));
2783 // Handling of script id generation is in FACTORY->NewScript.
2784 set_last_script_id(undefined_value());
2786 // Initialize keyed lookup cache.
2787 isolate_->keyed_lookup_cache()->Clear();
2789 // Initialize context slot cache.
2790 isolate_->context_slot_cache()->Clear();
2792 // Initialize descriptor cache.
2793 isolate_->descriptor_lookup_cache()->Clear();
2795 // Initialize compilation cache.
2796 isolate_->compilation_cache()->Clear();
2802 Object* RegExpResultsCache::Lookup(Heap* heap,
2804 Object* key_pattern,
2805 ResultsCacheType type) {
2807 if (!key_string->IsSymbol()) return Smi::FromInt(0);
2808 if (type == STRING_SPLIT_SUBSTRINGS) {
2809 ASSERT(key_pattern->IsString());
2810 if (!key_pattern->IsSymbol()) return Smi::FromInt(0);
2811 cache = heap->string_split_cache();
2813 ASSERT(type == REGEXP_MULTIPLE_INDICES);
2814 ASSERT(key_pattern->IsFixedArray());
2815 cache = heap->regexp_multiple_cache();
2818 uint32_t hash = key_string->Hash();
2819 uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
2820 ~(kArrayEntriesPerCacheEntry - 1));
2821 if (cache->get(index + kStringOffset) == key_string &&
2822 cache->get(index + kPatternOffset) == key_pattern) {
2823 return cache->get(index + kArrayOffset);
2826 ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
2827 if (cache->get(index + kStringOffset) == key_string &&
2828 cache->get(index + kPatternOffset) == key_pattern) {
2829 return cache->get(index + kArrayOffset);
2831 return Smi::FromInt(0);
2835 void RegExpResultsCache::Enter(Heap* heap,
2837 Object* key_pattern,
2838 FixedArray* value_array,
2839 ResultsCacheType type) {
2841 if (!key_string->IsSymbol()) return;
2842 if (type == STRING_SPLIT_SUBSTRINGS) {
2843 ASSERT(key_pattern->IsString());
2844 if (!key_pattern->IsSymbol()) return;
2845 cache = heap->string_split_cache();
2847 ASSERT(type == REGEXP_MULTIPLE_INDICES);
2848 ASSERT(key_pattern->IsFixedArray());
2849 cache = heap->regexp_multiple_cache();
2852 uint32_t hash = key_string->Hash();
2853 uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
2854 ~(kArrayEntriesPerCacheEntry - 1));
2855 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2856 cache->set(index + kStringOffset, key_string);
2857 cache->set(index + kPatternOffset, key_pattern);
2858 cache->set(index + kArrayOffset, value_array);
2861 ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
2862 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2863 cache->set(index2 + kStringOffset, key_string);
2864 cache->set(index2 + kPatternOffset, key_pattern);
2865 cache->set(index2 + kArrayOffset, value_array);
2867 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2868 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2869 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2870 cache->set(index + kStringOffset, key_string);
2871 cache->set(index + kPatternOffset, key_pattern);
2872 cache->set(index + kArrayOffset, value_array);
2875 // If the array is a reasonably short list of substrings, convert it into a
2877 if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) {
2878 for (int i = 0; i < value_array->length(); i++) {
2879 String* str = String::cast(value_array->get(i));
2881 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2882 if (maybe_symbol->ToObject(&symbol)) {
2883 value_array->set(i, symbol);
2887 // Convert backing store to a copy-on-write array.
2888 value_array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2892 void RegExpResultsCache::Clear(FixedArray* cache) {
2893 for (int i = 0; i < kRegExpResultsCacheSize; i++) {
2894 cache->set(i, Smi::FromInt(0));
2899 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2900 MaybeObject* maybe_obj =
2901 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2906 int Heap::FullSizeNumberStringCacheLength() {
2907 // Compute the size of the number string cache based on the max newspace size.
2908 // The number string cache has a minimum size based on twice the initial cache
2909 // size to ensure that it is bigger after being made 'full size'.
2910 int number_string_cache_size = max_semispace_size_ / 512;
2911 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2912 Min(0x4000, number_string_cache_size));
2913 // There is a string and a number per entry so the length is twice the number
2915 return number_string_cache_size * 2;
2919 void Heap::AllocateFullSizeNumberStringCache() {
2920 // The idea is to have a small number string cache in the snapshot to keep
2921 // boot-time memory usage down. If we expand the number string cache already
2922 // while creating the snapshot then that didn't work out.
2923 ASSERT(!Serializer::enabled() || FLAG_extra_code != NULL);
2924 MaybeObject* maybe_obj =
2925 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2927 if (maybe_obj->ToObject(&new_cache)) {
2928 // We don't bother to repopulate the cache with entries from the old cache.
2929 // It will be repopulated soon enough with new strings.
2930 set_number_string_cache(FixedArray::cast(new_cache));
2932 // If allocation fails then we just return without doing anything. It is only
2933 // a cache, so best effort is OK here.
2937 void Heap::FlushNumberStringCache() {
2938 // Flush the number to string cache.
2939 int len = number_string_cache()->length();
2940 for (int i = 0; i < len; i++) {
2941 number_string_cache()->set_undefined(this, i);
2946 static inline int double_get_hash(double d) {
2947 DoubleRepresentation rep(d);
2948 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2952 static inline int smi_get_hash(Smi* smi) {
2953 return smi->value();
2957 Object* Heap::GetNumberStringCache(Object* number) {
2959 int mask = (number_string_cache()->length() >> 1) - 1;
2960 if (number->IsSmi()) {
2961 hash = smi_get_hash(Smi::cast(number)) & mask;
2963 hash = double_get_hash(number->Number()) & mask;
2965 Object* key = number_string_cache()->get(hash * 2);
2966 if (key == number) {
2967 return String::cast(number_string_cache()->get(hash * 2 + 1));
2968 } else if (key->IsHeapNumber() &&
2969 number->IsHeapNumber() &&
2970 key->Number() == number->Number()) {
2971 return String::cast(number_string_cache()->get(hash * 2 + 1));
2973 return undefined_value();
2977 void Heap::SetNumberStringCache(Object* number, String* string) {
2979 int mask = (number_string_cache()->length() >> 1) - 1;
2980 if (number->IsSmi()) {
2981 hash = smi_get_hash(Smi::cast(number)) & mask;
2983 hash = double_get_hash(number->Number()) & mask;
2985 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2986 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2987 // The first time we have a hash collision, we move to the full sized
2988 // number string cache.
2989 AllocateFullSizeNumberStringCache();
2992 number_string_cache()->set(hash * 2, number);
2993 number_string_cache()->set(hash * 2 + 1, string);
2997 MaybeObject* Heap::NumberToString(Object* number,
2998 bool check_number_string_cache) {
2999 isolate_->counters()->number_to_string_runtime()->Increment();
3000 if (check_number_string_cache) {
3001 Object* cached = GetNumberStringCache(number);
3002 if (cached != undefined_value()) {
3008 Vector<char> buffer(arr, ARRAY_SIZE(arr));
3010 if (number->IsSmi()) {
3011 int num = Smi::cast(number)->value();
3012 str = IntToCString(num, buffer);
3014 double num = HeapNumber::cast(number)->value();
3015 str = DoubleToCString(num, buffer);
3019 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
3020 if (maybe_js_string->ToObject(&js_string)) {
3021 SetNumberStringCache(number, String::cast(js_string));
3023 return maybe_js_string;
3027 MaybeObject* Heap::Uint32ToString(uint32_t value,
3028 bool check_number_string_cache) {
3030 MaybeObject* maybe = NumberFromUint32(value);
3031 if (!maybe->To<Object>(&number)) return maybe;
3032 return NumberToString(number, check_number_string_cache);
3036 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
3037 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
3041 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
3042 ExternalArrayType array_type) {
3043 switch (array_type) {
3044 case kExternalByteArray:
3045 return kExternalByteArrayMapRootIndex;
3046 case kExternalUnsignedByteArray:
3047 return kExternalUnsignedByteArrayMapRootIndex;
3048 case kExternalShortArray:
3049 return kExternalShortArrayMapRootIndex;
3050 case kExternalUnsignedShortArray:
3051 return kExternalUnsignedShortArrayMapRootIndex;
3052 case kExternalIntArray:
3053 return kExternalIntArrayMapRootIndex;
3054 case kExternalUnsignedIntArray:
3055 return kExternalUnsignedIntArrayMapRootIndex;
3056 case kExternalFloatArray:
3057 return kExternalFloatArrayMapRootIndex;
3058 case kExternalDoubleArray:
3059 return kExternalDoubleArrayMapRootIndex;
3060 case kExternalPixelArray:
3061 return kExternalPixelArrayMapRootIndex;
3064 return kUndefinedValueRootIndex;
3069 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
3070 // We need to distinguish the minus zero value and this cannot be
3071 // done after conversion to int. Doing this by comparing bit
3072 // patterns is faster than using fpclassify() et al.
3073 static const DoubleRepresentation minus_zero(-0.0);
3075 DoubleRepresentation rep(value);
3076 if (rep.bits == minus_zero.bits) {
3077 return AllocateHeapNumber(-0.0, pretenure);
3080 int int_value = FastD2I(value);
3081 if (value == int_value && Smi::IsValid(int_value)) {
3082 return Smi::FromInt(int_value);
3085 // Materialize the value in the heap.
3086 return AllocateHeapNumber(value, pretenure);
3090 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
3091 // Statically ensure that it is safe to allocate foreigns in paged spaces.
3092 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
3093 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3095 MaybeObject* maybe_result = Allocate(foreign_map(), space);
3096 if (!maybe_result->To(&result)) return maybe_result;
3097 result->set_foreign_address(address);
3102 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
3103 SharedFunctionInfo* share;
3104 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
3105 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
3107 // Set pointer fields.
3108 share->set_name(name);
3109 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
3110 share->set_code(illegal);
3111 share->ClearOptimizedCodeMap();
3112 share->set_scope_info(ScopeInfo::Empty());
3113 Code* construct_stub =
3114 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
3115 share->set_construct_stub(construct_stub);
3116 share->set_instance_class_name(Object_symbol());
3117 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
3118 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
3119 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
3120 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
3121 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
3122 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
3123 share->set_ast_node_count(0);
3124 share->set_stress_deopt_counter(FLAG_deopt_every_n_times);
3125 share->set_counters(0);
3127 // Set integer fields (smi or int, depending on the architecture).
3128 share->set_length(0);
3129 share->set_formal_parameter_count(0);
3130 share->set_expected_nof_properties(0);
3131 share->set_num_literals(0);
3132 share->set_start_position_and_type(0);
3133 share->set_end_position(0);
3134 share->set_function_token_position(0);
3135 // All compiler hints default to false or 0.
3136 share->set_compiler_hints(0);
3137 share->set_this_property_assignments_count(0);
3138 share->set_opt_count(0);
3144 MaybeObject* Heap::AllocateJSMessageObject(String* type,
3149 Object* stack_trace,
3150 Object* stack_frames) {
3152 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
3153 if (!maybe_result->ToObject(&result)) return maybe_result;
3155 JSMessageObject* message = JSMessageObject::cast(result);
3156 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3157 message->initialize_elements();
3158 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3159 message->set_type(type);
3160 message->set_arguments(arguments);
3161 message->set_start_position(start_position);
3162 message->set_end_position(end_position);
3163 message->set_script(script);
3164 message->set_stack_trace(stack_trace);
3165 message->set_stack_frames(stack_frames);
3171 // Returns true for a character in a range. Both limits are inclusive.
3172 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
3173 // This makes uses of the the unsigned wraparound.
3174 return character - from <= to - from;
3178 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
3183 // Numeric strings have a different hash algorithm not known by
3184 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
3185 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
3186 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
3188 // Now we know the length is 2, we might as well make use of that fact
3189 // when building the new string.
3190 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
3191 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
3193 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
3194 if (!maybe_result->ToObject(&result)) return maybe_result;
3196 char* dest = SeqAsciiString::cast(result)->GetChars();
3202 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
3203 if (!maybe_result->ToObject(&result)) return maybe_result;
3205 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3213 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
3214 int first_length = first->length();
3215 if (first_length == 0) {
3219 int second_length = second->length();
3220 if (second_length == 0) {
3224 int length = first_length + second_length;
3226 // Optimization for 2-byte strings often used as keys in a decompression
3227 // dictionary. Check whether we already have the string in the symbol
3228 // table to prevent creation of many unneccesary strings.
3230 unsigned c1 = first->Get(0);
3231 unsigned c2 = second->Get(0);
3232 return MakeOrFindTwoCharacterString(this, c1, c2);
3235 bool first_is_ascii = first->IsAsciiRepresentation();
3236 bool second_is_ascii = second->IsAsciiRepresentation();
3237 bool is_ascii = first_is_ascii && second_is_ascii;
3239 // Make sure that an out of memory exception is thrown if the length
3240 // of the new cons string is too large.
3241 if (length > String::kMaxLength || length < 0) {
3242 isolate()->context()->mark_out_of_memory();
3243 return Failure::OutOfMemoryException();
3246 bool is_ascii_data_in_two_byte_string = false;
3248 // At least one of the strings uses two-byte representation so we
3249 // can't use the fast case code for short ASCII strings below, but
3250 // we can try to save memory if all chars actually fit in ASCII.
3251 is_ascii_data_in_two_byte_string =
3252 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3253 if (is_ascii_data_in_two_byte_string) {
3254 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3258 // If the resulting string is small make a flat string.
3259 if (length < ConsString::kMinLength) {
3260 // Note that neither of the two inputs can be a slice because:
3261 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3262 ASSERT(first->IsFlat());
3263 ASSERT(second->IsFlat());
3266 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3267 if (!maybe_result->ToObject(&result)) return maybe_result;
3269 // Copy the characters into the new object.
3270 char* dest = SeqAsciiString::cast(result)->GetChars();
3273 if (first->IsExternalString()) {
3274 src = ExternalAsciiString::cast(first)->GetChars();
3276 src = SeqAsciiString::cast(first)->GetChars();
3278 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3279 // Copy second part.
3280 if (second->IsExternalString()) {
3281 src = ExternalAsciiString::cast(second)->GetChars();
3283 src = SeqAsciiString::cast(second)->GetChars();
3285 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3288 if (is_ascii_data_in_two_byte_string) {
3290 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3291 if (!maybe_result->ToObject(&result)) return maybe_result;
3293 // Copy the characters into the new object.
3294 char* dest = SeqAsciiString::cast(result)->GetChars();
3295 String::WriteToFlat(first, dest, 0, first_length);
3296 String::WriteToFlat(second, dest + first_length, 0, second_length);
3297 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3302 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3303 if (!maybe_result->ToObject(&result)) return maybe_result;
3305 // Copy the characters into the new object.
3306 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3307 String::WriteToFlat(first, dest, 0, first_length);
3308 String::WriteToFlat(second, dest + first_length, 0, second_length);
3313 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3314 cons_ascii_string_map() : cons_string_map();
3317 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3318 if (!maybe_result->ToObject(&result)) return maybe_result;
3321 AssertNoAllocation no_gc;
3322 ConsString* cons_string = ConsString::cast(result);
3323 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3324 cons_string->set_length(length);
3325 cons_string->set_hash_field(String::kEmptyHashField);
3326 cons_string->set_first(first, mode);
3327 cons_string->set_second(second, mode);
3332 MaybeObject* Heap::AllocateSubString(String* buffer,
3335 PretenureFlag pretenure) {
3336 int length = end - start;
3338 return empty_string();
3339 } else if (length == 1) {
3340 return LookupSingleCharacterStringFromCode(buffer->Get(start));
3341 } else if (length == 2) {
3342 // Optimization for 2-byte strings often used as keys in a decompression
3343 // dictionary. Check whether we already have the string in the symbol
3344 // table to prevent creation of many unneccesary strings.
3345 unsigned c1 = buffer->Get(start);
3346 unsigned c2 = buffer->Get(start + 1);
3347 return MakeOrFindTwoCharacterString(this, c1, c2);
3350 // Make an attempt to flatten the buffer to reduce access time.
3351 buffer = buffer->TryFlattenGetString();
3353 if (!FLAG_string_slices ||
3354 !buffer->IsFlat() ||
3355 length < SlicedString::kMinLength ||
3356 pretenure == TENURED) {
3358 // WriteToFlat takes care of the case when an indirect string has a
3359 // different encoding from its underlying string. These encodings may
3360 // differ because of externalization.
3361 bool is_ascii = buffer->IsAsciiRepresentation();
3362 { MaybeObject* maybe_result = is_ascii
3363 ? AllocateRawAsciiString(length, pretenure)
3364 : AllocateRawTwoByteString(length, pretenure);
3365 if (!maybe_result->ToObject(&result)) return maybe_result;
3367 String* string_result = String::cast(result);
3368 // Copy the characters into the new object.
3370 ASSERT(string_result->IsAsciiRepresentation());
3371 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3372 String::WriteToFlat(buffer, dest, start, end);
3374 ASSERT(string_result->IsTwoByteRepresentation());
3375 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3376 String::WriteToFlat(buffer, dest, start, end);
3381 ASSERT(buffer->IsFlat());
3383 if (FLAG_verify_heap) {
3384 buffer->StringVerify();
3389 // When slicing an indirect string we use its encoding for a newly created
3390 // slice and don't check the encoding of the underlying string. This is safe
3391 // even if the encodings are different because of externalization. If an
3392 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3393 // codes of the underlying string must still fit into ASCII (because
3394 // externalization must not change char codes).
3395 { Map* map = buffer->IsAsciiRepresentation()
3396 ? sliced_ascii_string_map()
3397 : sliced_string_map();
3398 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3399 if (!maybe_result->ToObject(&result)) return maybe_result;
3402 AssertNoAllocation no_gc;
3403 SlicedString* sliced_string = SlicedString::cast(result);
3404 sliced_string->set_length(length);
3405 sliced_string->set_hash_field(String::kEmptyHashField);
3406 if (buffer->IsConsString()) {
3407 ConsString* cons = ConsString::cast(buffer);
3408 ASSERT(cons->second()->length() == 0);
3409 sliced_string->set_parent(cons->first());
3410 sliced_string->set_offset(start);
3411 } else if (buffer->IsSlicedString()) {
3412 // Prevent nesting sliced strings.
3413 SlicedString* parent_slice = SlicedString::cast(buffer);
3414 sliced_string->set_parent(parent_slice->parent());
3415 sliced_string->set_offset(start + parent_slice->offset());
3417 sliced_string->set_parent(buffer);
3418 sliced_string->set_offset(start);
3420 ASSERT(sliced_string->parent()->IsSeqString() ||
3421 sliced_string->parent()->IsExternalString());
3426 MaybeObject* Heap::AllocateExternalStringFromAscii(
3427 const ExternalAsciiString::Resource* resource) {
3428 size_t length = resource->length();
3429 if (length > static_cast<size_t>(String::kMaxLength)) {
3430 isolate()->context()->mark_out_of_memory();
3431 return Failure::OutOfMemoryException();
3434 ASSERT(String::IsAscii(resource->data(), static_cast<int>(length)));
3436 Map* map = external_ascii_string_map();
3438 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3439 if (!maybe_result->ToObject(&result)) return maybe_result;
3442 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3443 external_string->set_length(static_cast<int>(length));
3444 external_string->set_hash_field(String::kEmptyHashField);
3445 external_string->set_resource(resource);
3451 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3452 const ExternalTwoByteString::Resource* resource) {
3453 size_t length = resource->length();
3454 if (length > static_cast<size_t>(String::kMaxLength)) {
3455 isolate()->context()->mark_out_of_memory();
3456 return Failure::OutOfMemoryException();
3459 // For small strings we check whether the resource contains only
3460 // ASCII characters. If yes, we use a different string map.
3461 static const size_t kAsciiCheckLengthLimit = 32;
3462 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3463 String::IsAscii(resource->data(), static_cast<int>(length));
3464 Map* map = is_ascii ?
3465 external_string_with_ascii_data_map() : external_string_map();
3467 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3468 if (!maybe_result->ToObject(&result)) return maybe_result;
3471 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3472 external_string->set_length(static_cast<int>(length));
3473 external_string->set_hash_field(String::kEmptyHashField);
3474 external_string->set_resource(resource);
3480 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3481 if (code <= String::kMaxAsciiCharCode) {
3482 Object* value = single_character_string_cache()->get(code);
3483 if (value != undefined_value()) return value;
3486 buffer[0] = static_cast<char>(code);
3488 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3490 if (!maybe_result->ToObject(&result)) return maybe_result;
3491 single_character_string_cache()->set(code, result);
3496 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3497 if (!maybe_result->ToObject(&result)) return maybe_result;
3499 String* answer = String::cast(result);
3500 answer->Set(0, code);
3505 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3506 if (length < 0 || length > ByteArray::kMaxLength) {
3507 return Failure::OutOfMemoryException();
3509 if (pretenure == NOT_TENURED) {
3510 return AllocateByteArray(length);
3512 int size = ByteArray::SizeFor(length);
3514 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3515 ? old_data_space_->AllocateRaw(size)
3516 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3517 if (!maybe_result->ToObject(&result)) return maybe_result;
3520 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3522 reinterpret_cast<ByteArray*>(result)->set_length(length);
3527 MaybeObject* Heap::AllocateByteArray(int length) {
3528 if (length < 0 || length > ByteArray::kMaxLength) {
3529 return Failure::OutOfMemoryException();
3531 int size = ByteArray::SizeFor(length);
3532 AllocationSpace space =
3533 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3535 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3536 if (!maybe_result->ToObject(&result)) return maybe_result;
3539 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3541 reinterpret_cast<ByteArray*>(result)->set_length(length);
3546 void Heap::CreateFillerObjectAt(Address addr, int size) {
3547 if (size == 0) return;
3548 HeapObject* filler = HeapObject::FromAddress(addr);
3549 if (size == kPointerSize) {
3550 filler->set_map_no_write_barrier(one_pointer_filler_map());
3551 } else if (size == 2 * kPointerSize) {
3552 filler->set_map_no_write_barrier(two_pointer_filler_map());
3554 filler->set_map_no_write_barrier(free_space_map());
3555 FreeSpace::cast(filler)->set_size(size);
3560 MaybeObject* Heap::AllocateExternalArray(int length,
3561 ExternalArrayType array_type,
3562 void* external_pointer,
3563 PretenureFlag pretenure) {
3564 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3566 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3569 if (!maybe_result->ToObject(&result)) return maybe_result;
3572 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3573 MapForExternalArrayType(array_type));
3574 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3575 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3582 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3584 Handle<Object> self_reference,
3586 // Allocate ByteArray before the Code object, so that we do not risk
3587 // leaving uninitialized Code object (and breaking the heap).
3588 ByteArray* reloc_info;
3589 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3590 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3593 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3594 int obj_size = Code::SizeFor(body_size);
3595 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3596 MaybeObject* maybe_result;
3597 // Large code objects and code objects which should stay at a fixed address
3598 // are allocated in large object space.
3599 if (obj_size > code_space()->AreaSize() || immovable) {
3600 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3602 maybe_result = code_space_->AllocateRaw(obj_size);
3606 if (!maybe_result->ToObject(&result)) return maybe_result;
3608 // Initialize the object
3609 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3610 Code* code = Code::cast(result);
3611 ASSERT(!isolate_->code_range()->exists() ||
3612 isolate_->code_range()->contains(code->address()));
3613 code->set_instruction_size(desc.instr_size);
3614 code->set_relocation_info(reloc_info);
3615 code->set_flags(flags);
3616 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3617 code->set_check_type(RECEIVER_MAP_CHECK);
3619 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3620 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3621 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3622 code->set_gc_metadata(Smi::FromInt(0));
3623 code->set_ic_age(global_ic_age_);
3624 // Allow self references to created code object by patching the handle to
3625 // point to the newly allocated Code object.
3626 if (!self_reference.is_null()) {
3627 *(self_reference.location()) = code;
3629 // Migrate generated code.
3630 // The generated code can contain Object** values (typically from handles)
3631 // that are dereferenced during the copy to point directly to the actual heap
3632 // objects. These pointers can include references to the code object itself,
3633 // through the self_reference parameter.
3634 code->CopyFrom(desc);
3637 if (FLAG_verify_heap) {
3645 MaybeObject* Heap::CopyCode(Code* code) {
3646 // Allocate an object the same size as the code object.
3647 int obj_size = code->Size();
3648 MaybeObject* maybe_result;
3649 if (obj_size > code_space()->AreaSize()) {
3650 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3652 maybe_result = code_space_->AllocateRaw(obj_size);
3656 if (!maybe_result->ToObject(&result)) return maybe_result;
3658 // Copy code object.
3659 Address old_addr = code->address();
3660 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3661 CopyBlock(new_addr, old_addr, obj_size);
3662 // Relocate the copy.
3663 Code* new_code = Code::cast(result);
3664 ASSERT(!isolate_->code_range()->exists() ||
3665 isolate_->code_range()->contains(code->address()));
3666 new_code->Relocate(new_addr - old_addr);
3671 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3672 // Allocate ByteArray before the Code object, so that we do not risk
3673 // leaving uninitialized Code object (and breaking the heap).
3674 Object* reloc_info_array;
3675 { MaybeObject* maybe_reloc_info_array =
3676 AllocateByteArray(reloc_info.length(), TENURED);
3677 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3678 return maybe_reloc_info_array;
3682 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3684 int new_obj_size = Code::SizeFor(new_body_size);
3686 Address old_addr = code->address();
3688 size_t relocation_offset =
3689 static_cast<size_t>(code->instruction_end() - old_addr);
3691 MaybeObject* maybe_result;
3692 if (new_obj_size > code_space()->AreaSize()) {
3693 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3695 maybe_result = code_space_->AllocateRaw(new_obj_size);
3699 if (!maybe_result->ToObject(&result)) return maybe_result;
3701 // Copy code object.
3702 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3704 // Copy header and instructions.
3705 memcpy(new_addr, old_addr, relocation_offset);
3707 Code* new_code = Code::cast(result);
3708 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3710 // Copy patched rinfo.
3711 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3713 // Relocate the copy.
3714 ASSERT(!isolate_->code_range()->exists() ||
3715 isolate_->code_range()->contains(code->address()));
3716 new_code->Relocate(new_addr - old_addr);
3719 if (FLAG_verify_heap) {
3727 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3728 ASSERT(gc_state_ == NOT_IN_GC);
3729 ASSERT(map->instance_type() != MAP_TYPE);
3730 // If allocation failures are disallowed, we may allocate in a different
3731 // space when new space is full and the object is not a large object.
3732 AllocationSpace retry_space =
3733 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3735 { MaybeObject* maybe_result =
3736 AllocateRaw(map->instance_size(), space, retry_space);
3737 if (!maybe_result->ToObject(&result)) return maybe_result;
3739 // No need for write barrier since object is white and map is in old space.
3740 HeapObject::cast(result)->set_map_no_write_barrier(map);
3745 void Heap::InitializeFunction(JSFunction* function,
3746 SharedFunctionInfo* shared,
3747 Object* prototype) {
3748 ASSERT(!prototype->IsMap());
3749 function->initialize_properties();
3750 function->initialize_elements();
3751 function->set_shared(shared);
3752 function->set_code(shared->code());
3753 function->set_prototype_or_initial_map(prototype);
3754 function->set_context(undefined_value());
3755 function->set_literals_or_bindings(empty_fixed_array());
3756 function->set_next_function_link(undefined_value());
3760 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3761 // Allocate the prototype. Make sure to use the object function
3762 // from the function's context, since the function can be from a
3763 // different context.
3764 JSFunction* object_function =
3765 function->context()->native_context()->object_function();
3767 // Each function prototype gets a copy of the object function map.
3768 // This avoid unwanted sharing of maps between prototypes of different
3771 ASSERT(object_function->has_initial_map());
3772 MaybeObject* maybe_map = object_function->initial_map()->Copy();
3773 if (!maybe_map->To(&new_map)) return maybe_map;
3776 MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3777 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3779 // When creating the prototype for the function we must set its
3780 // constructor to the function.
3781 MaybeObject* maybe_failure =
3782 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3783 constructor_symbol(), function, DONT_ENUM);
3784 if (maybe_failure->IsFailure()) return maybe_failure;
3790 MaybeObject* Heap::AllocateFunction(Map* function_map,
3791 SharedFunctionInfo* shared,
3793 PretenureFlag pretenure) {
3794 AllocationSpace space =
3795 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3797 { MaybeObject* maybe_result = Allocate(function_map, space);
3798 if (!maybe_result->ToObject(&result)) return maybe_result;
3800 InitializeFunction(JSFunction::cast(result), shared, prototype);
3805 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3806 // To get fast allocation and map sharing for arguments objects we
3807 // allocate them based on an arguments boilerplate.
3809 JSObject* boilerplate;
3810 int arguments_object_size;
3811 bool strict_mode_callee = callee->IsJSFunction() &&
3812 !JSFunction::cast(callee)->shared()->is_classic_mode();
3813 if (strict_mode_callee) {
3815 isolate()->context()->native_context()->
3816 strict_mode_arguments_boilerplate();
3817 arguments_object_size = kArgumentsObjectSizeStrict;
3820 isolate()->context()->native_context()->arguments_boilerplate();
3821 arguments_object_size = kArgumentsObjectSize;
3824 // This calls Copy directly rather than using Heap::AllocateRaw so we
3825 // duplicate the check here.
3826 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3828 // Check that the size of the boilerplate matches our
3829 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3830 // on the size being a known constant.
3831 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3833 // Do the allocation.
3835 { MaybeObject* maybe_result =
3836 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3837 if (!maybe_result->ToObject(&result)) return maybe_result;
3840 // Copy the content. The arguments boilerplate doesn't have any
3841 // fields that point to new space so it's safe to skip the write
3843 CopyBlock(HeapObject::cast(result)->address(),
3844 boilerplate->address(),
3845 JSObject::kHeaderSize);
3847 // Set the length property.
3848 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3849 Smi::FromInt(length),
3850 SKIP_WRITE_BARRIER);
3851 // Set the callee property for non-strict mode arguments object only.
3852 if (!strict_mode_callee) {
3853 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3857 // Check the state of the object
3858 ASSERT(JSObject::cast(result)->HasFastProperties());
3859 ASSERT(JSObject::cast(result)->HasFastObjectElements());
3865 static bool HasDuplicates(DescriptorArray* descriptors) {
3866 int count = descriptors->number_of_descriptors();
3868 String* prev_key = descriptors->GetKey(0);
3869 for (int i = 1; i != count; i++) {
3870 String* current_key = descriptors->GetKey(i);
3871 if (prev_key == current_key) return true;
3872 prev_key = current_key;
3879 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3880 ASSERT(!fun->has_initial_map());
3882 // First create a new map with the size and number of in-object properties
3883 // suggested by the function.
3884 int instance_size = fun->shared()->CalculateInstanceSize();
3885 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3887 MaybeObject* maybe_map = AllocateMap(JS_OBJECT_TYPE, instance_size);
3888 if (!maybe_map->To(&map)) return maybe_map;
3890 // Fetch or allocate prototype.
3892 if (fun->has_instance_prototype()) {
3893 prototype = fun->instance_prototype();
3895 MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3896 if (!maybe_prototype->To(&prototype)) return maybe_prototype;
3898 map->set_inobject_properties(in_object_properties);
3899 map->set_unused_property_fields(in_object_properties);
3900 map->set_prototype(prototype);
3901 ASSERT(map->has_fast_object_elements());
3903 // If the function has only simple this property assignments add
3904 // field descriptors for these to the initial map as the object
3905 // cannot be constructed without having these properties. Guard by
3906 // the inline_new flag so we only change the map if we generate a
3907 // specialized construct stub.
3908 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3909 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3910 int count = fun->shared()->this_property_assignments_count();
3911 if (count > in_object_properties) {
3912 // Inline constructor can only handle inobject properties.
3913 fun->shared()->ForbidInlineConstructor();
3915 DescriptorArray* descriptors;
3916 MaybeObject* maybe_descriptors = DescriptorArray::Allocate(count);
3917 if (!maybe_descriptors->To(&descriptors)) return maybe_descriptors;
3919 DescriptorArray::WhitenessWitness witness(descriptors);
3920 for (int i = 0; i < count; i++) {
3921 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3922 ASSERT(name->IsSymbol());
3923 FieldDescriptor field(name, i, NONE, i + 1);
3924 descriptors->Set(i, &field, witness);
3926 descriptors->Sort();
3928 // The descriptors may contain duplicates because the compiler does not
3929 // guarantee the uniqueness of property names (it would have required
3930 // quadratic time). Once the descriptors are sorted we can check for
3931 // duplicates in linear time.
3932 if (HasDuplicates(descriptors)) {
3933 fun->shared()->ForbidInlineConstructor();
3935 MaybeObject* maybe_failure = map->InitializeDescriptors(descriptors);
3936 if (maybe_failure->IsFailure()) return maybe_failure;
3937 map->set_pre_allocated_property_fields(count);
3938 map->set_unused_property_fields(in_object_properties - count);
3943 fun->shared()->StartInobjectSlackTracking(map);
3949 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3950 FixedArray* properties,
3952 obj->set_properties(properties);
3953 obj->initialize_elements();
3954 // TODO(1240798): Initialize the object's body using valid initial values
3955 // according to the object's initial map. For example, if the map's
3956 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3957 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3958 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3959 // verification code has to cope with (temporarily) invalid objects. See
3960 // for example, JSArray::JSArrayVerify).
3962 // We cannot always fill with one_pointer_filler_map because objects
3963 // created from API functions expect their internal fields to be initialized
3964 // with undefined_value.
3965 // Pre-allocated fields need to be initialized with undefined_value as well
3966 // so that object accesses before the constructor completes (e.g. in the
3967 // debugger) will not cause a crash.
3968 if (map->constructor()->IsJSFunction() &&
3969 JSFunction::cast(map->constructor())->shared()->
3970 IsInobjectSlackTrackingInProgress()) {
3971 // We might want to shrink the object later.
3972 ASSERT(obj->GetInternalFieldCount() == 0);
3973 filler = Heap::one_pointer_filler_map();
3975 filler = Heap::undefined_value();
3977 obj->InitializeBody(map, Heap::undefined_value(), filler);
3981 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3982 // JSFunctions should be allocated using AllocateFunction to be
3983 // properly initialized.
3984 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3986 // Both types of global objects should be allocated using
3987 // AllocateGlobalObject to be properly initialized.
3988 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3989 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3991 // Allocate the backing storage for the properties.
3993 map->pre_allocated_property_fields() +
3994 map->unused_property_fields() -
3995 map->inobject_properties();
3996 ASSERT(prop_size >= 0);
3998 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3999 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4002 // Allocate the JSObject.
4003 AllocationSpace space =
4004 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4005 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
4007 { MaybeObject* maybe_obj = Allocate(map, space);
4008 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4011 // Initialize the JSObject.
4012 InitializeJSObjectFromMap(JSObject::cast(obj),
4013 FixedArray::cast(properties),
4015 ASSERT(JSObject::cast(obj)->HasFastSmiOrObjectElements());
4020 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
4021 PretenureFlag pretenure) {
4022 // Allocate the initial map if absent.
4023 if (!constructor->has_initial_map()) {
4024 Object* initial_map;
4025 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
4026 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
4028 constructor->set_initial_map(Map::cast(initial_map));
4029 Map::cast(initial_map)->set_constructor(constructor);
4031 // Allocate the object based on the constructors initial map.
4032 MaybeObject* result = AllocateJSObjectFromMap(
4033 constructor->initial_map(), pretenure);
4035 // Make sure result is NOT a global object if valid.
4036 Object* non_failure;
4037 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
4043 MaybeObject* Heap::AllocateJSModule(Context* context, ScopeInfo* scope_info) {
4044 // Allocate a fresh map. Modules do not have a prototype.
4046 MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
4047 if (!maybe_map->To(&map)) return maybe_map;
4048 // Allocate the object based on the map.
4050 MaybeObject* maybe_module = AllocateJSObjectFromMap(map, TENURED);
4051 if (!maybe_module->To(&module)) return maybe_module;
4052 module->set_context(context);
4053 module->set_scope_info(scope_info);
4058 MaybeObject* Heap::AllocateJSArrayAndStorage(
4059 ElementsKind elements_kind,
4062 ArrayStorageAllocationMode mode,
4063 PretenureFlag pretenure) {
4064 ASSERT(capacity >= length);
4065 if (length != 0 && mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE) {
4066 elements_kind = GetHoleyElementsKind(elements_kind);
4068 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4070 if (!maybe_array->To(&array)) return maybe_array;
4072 if (capacity == 0) {
4073 array->set_length(Smi::FromInt(0));
4074 array->set_elements(empty_fixed_array());
4078 FixedArrayBase* elms;
4079 MaybeObject* maybe_elms = NULL;
4080 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4081 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
4082 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
4084 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
4085 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
4088 ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
4089 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
4090 maybe_elms = AllocateUninitializedFixedArray(capacity);
4092 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
4093 maybe_elms = AllocateFixedArrayWithHoles(capacity);
4096 if (!maybe_elms->To(&elms)) return maybe_elms;
4098 array->set_elements(elms);
4099 array->set_length(Smi::FromInt(length));
4104 MaybeObject* Heap::AllocateJSArrayWithElements(
4105 FixedArrayBase* elements,
4106 ElementsKind elements_kind,
4107 PretenureFlag pretenure) {
4108 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4110 if (!maybe_array->To(&array)) return maybe_array;
4112 array->set_elements(elements);
4113 array->set_length(Smi::FromInt(elements->length()));
4114 array->ValidateElements();
4119 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
4121 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4122 // maps. Will probably depend on the identity of the handler object, too.
4124 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
4125 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4126 map->set_prototype(prototype);
4128 // Allocate the proxy object.
4130 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4131 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
4132 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4133 result->set_handler(handler);
4134 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4139 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
4141 Object* construct_trap,
4142 Object* prototype) {
4144 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4145 // maps. Will probably depend on the identity of the handler object, too.
4147 MaybeObject* maybe_map_obj =
4148 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
4149 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4150 map->set_prototype(prototype);
4152 // Allocate the proxy object.
4153 JSFunctionProxy* result;
4154 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4155 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
4156 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4157 result->set_handler(handler);
4158 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4159 result->set_call_trap(call_trap);
4160 result->set_construct_trap(construct_trap);
4165 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
4166 ASSERT(constructor->has_initial_map());
4167 Map* map = constructor->initial_map();
4168 ASSERT(map->is_dictionary_map());
4170 // Make sure no field properties are described in the initial map.
4171 // This guarantees us that normalizing the properties does not
4172 // require us to change property values to JSGlobalPropertyCells.
4173 ASSERT(map->NextFreePropertyIndex() == 0);
4175 // Make sure we don't have a ton of pre-allocated slots in the
4176 // global objects. They will be unused once we normalize the object.
4177 ASSERT(map->unused_property_fields() == 0);
4178 ASSERT(map->inobject_properties() == 0);
4180 // Initial size of the backing store to avoid resize of the storage during
4181 // bootstrapping. The size differs between the JS global object ad the
4183 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
4185 // Allocate a dictionary object for backing storage.
4186 StringDictionary* dictionary;
4187 MaybeObject* maybe_dictionary =
4188 StringDictionary::Allocate(
4189 map->NumberOfDescribedProperties() * 2 + initial_size);
4190 if (!maybe_dictionary->To(&dictionary)) return maybe_dictionary;
4192 // The global object might be created from an object template with accessors.
4193 // Fill these accessors into the dictionary.
4194 DescriptorArray* descs = map->instance_descriptors();
4195 for (int i = 0; i < descs->number_of_descriptors(); i++) {
4196 PropertyDetails details = descs->GetDetails(i);
4197 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
4198 PropertyDetails d = PropertyDetails(details.attributes(),
4200 details.descriptor_index());
4201 Object* value = descs->GetCallbacksObject(i);
4202 MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
4203 if (!maybe_value->ToObject(&value)) return maybe_value;
4205 MaybeObject* maybe_added = dictionary->Add(descs->GetKey(i), value, d);
4206 if (!maybe_added->To(&dictionary)) return maybe_added;
4209 // Allocate the global object and initialize it with the backing store.
4211 MaybeObject* maybe_global = Allocate(map, OLD_POINTER_SPACE);
4212 if (!maybe_global->To(&global)) return maybe_global;
4214 InitializeJSObjectFromMap(global, dictionary, map);
4216 // Create a new map for the global object.
4218 MaybeObject* maybe_map = map->CopyDropDescriptors();
4219 if (!maybe_map->To(&new_map)) return maybe_map;
4220 new_map->set_dictionary_map(true);
4222 // Set up the global object as a normalized object.
4223 global->set_map(new_map);
4224 global->set_properties(dictionary);
4226 // Make sure result is a global object with properties in dictionary.
4227 ASSERT(global->IsGlobalObject());
4228 ASSERT(!global->HasFastProperties());
4233 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4234 // Never used to copy functions. If functions need to be copied we
4235 // have to be careful to clear the literals array.
4236 SLOW_ASSERT(!source->IsJSFunction());
4239 Map* map = source->map();
4240 int object_size = map->instance_size();
4243 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4245 // If we're forced to always allocate, we use the general allocation
4246 // functions which may leave us with an object in old space.
4247 if (always_allocate()) {
4248 { MaybeObject* maybe_clone =
4249 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4250 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4252 Address clone_address = HeapObject::cast(clone)->address();
4253 CopyBlock(clone_address,
4256 // Update write barrier for all fields that lie beyond the header.
4257 RecordWrites(clone_address,
4258 JSObject::kHeaderSize,
4259 (object_size - JSObject::kHeaderSize) / kPointerSize);
4261 wb_mode = SKIP_WRITE_BARRIER;
4262 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4263 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4265 SLOW_ASSERT(InNewSpace(clone));
4266 // Since we know the clone is allocated in new space, we can copy
4267 // the contents without worrying about updating the write barrier.
4268 CopyBlock(HeapObject::cast(clone)->address(),
4274 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4275 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4276 FixedArray* properties = FixedArray::cast(source->properties());
4277 // Update elements if necessary.
4278 if (elements->length() > 0) {
4280 { MaybeObject* maybe_elem;
4281 if (elements->map() == fixed_cow_array_map()) {
4282 maybe_elem = FixedArray::cast(elements);
4283 } else if (source->HasFastDoubleElements()) {
4284 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4286 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4288 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4290 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4292 // Update properties if necessary.
4293 if (properties->length() > 0) {
4295 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4296 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4298 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4300 // Return the new clone.
4305 MaybeObject* Heap::ReinitializeJSReceiver(
4306 JSReceiver* object, InstanceType type, int size) {
4307 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4309 // Allocate fresh map.
4310 // TODO(rossberg): Once we optimize proxies, cache these maps.
4312 MaybeObject* maybe = AllocateMap(type, size);
4313 if (!maybe->To<Map>(&map)) return maybe;
4315 // Check that the receiver has at least the size of the fresh object.
4316 int size_difference = object->map()->instance_size() - map->instance_size();
4317 ASSERT(size_difference >= 0);
4319 map->set_prototype(object->map()->prototype());
4321 // Allocate the backing storage for the properties.
4322 int prop_size = map->unused_property_fields() - map->inobject_properties();
4324 maybe = AllocateFixedArray(prop_size, TENURED);
4325 if (!maybe->ToObject(&properties)) return maybe;
4327 // Functions require some allocation, which might fail here.
4328 SharedFunctionInfo* shared = NULL;
4329 if (type == JS_FUNCTION_TYPE) {
4331 maybe = LookupAsciiSymbol("<freezing call trap>");
4332 if (!maybe->To<String>(&name)) return maybe;
4333 maybe = AllocateSharedFunctionInfo(name);
4334 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4337 // Because of possible retries of this function after failure,
4338 // we must NOT fail after this point, where we have changed the type!
4340 // Reset the map for the object.
4341 object->set_map(map);
4342 JSObject* jsobj = JSObject::cast(object);
4344 // Reinitialize the object from the constructor map.
4345 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4347 // Functions require some minimal initialization.
4348 if (type == JS_FUNCTION_TYPE) {
4349 map->set_function_with_prototype(true);
4350 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4351 JSFunction::cast(object)->set_context(
4352 isolate()->context()->native_context());
4355 // Put in filler if the new object is smaller than the old.
4356 if (size_difference > 0) {
4357 CreateFillerObjectAt(
4358 object->address() + map->instance_size(), size_difference);
4365 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4366 JSGlobalProxy* object) {
4367 ASSERT(constructor->has_initial_map());
4368 Map* map = constructor->initial_map();
4370 // Check that the already allocated object has the same size and type as
4371 // objects allocated using the constructor.
4372 ASSERT(map->instance_size() == object->map()->instance_size());
4373 ASSERT(map->instance_type() == object->map()->instance_type());
4375 // Allocate the backing storage for the properties.
4376 int prop_size = map->unused_property_fields() - map->inobject_properties();
4378 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4379 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4382 // Reset the map for the object.
4383 object->set_map(constructor->initial_map());
4385 // Reinitialize the object from the constructor map.
4386 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4391 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4392 PretenureFlag pretenure) {
4393 if (string.length() == 1) {
4394 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4397 { MaybeObject* maybe_result =
4398 AllocateRawAsciiString(string.length(), pretenure);
4399 if (!maybe_result->ToObject(&result)) return maybe_result;
4402 // Copy the characters into the new object.
4403 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4404 for (int i = 0; i < string.length(); i++) {
4405 string_result->SeqAsciiStringSet(i, string[i]);
4411 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4412 PretenureFlag pretenure) {
4413 // Count the number of characters in the UTF-8 string and check if
4414 // it is an ASCII string.
4415 Access<UnicodeCache::Utf8Decoder>
4416 decoder(isolate_->unicode_cache()->utf8_decoder());
4417 decoder->Reset(string.start(), string.length());
4419 while (decoder->has_more()) {
4420 uint32_t r = decoder->GetNext();
4421 if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4429 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4430 if (!maybe_result->ToObject(&result)) return maybe_result;
4433 // Convert and copy the characters into the new object.
4434 String* string_result = String::cast(result);
4435 decoder->Reset(string.start(), string.length());
4438 uint32_t r = decoder->GetNext();
4439 if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4440 string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4441 string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4443 string_result->Set(i++, r);
4450 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4451 PretenureFlag pretenure) {
4452 // Check if the string is an ASCII string.
4453 MaybeObject* maybe_result;
4454 if (String::IsAscii(string.start(), string.length())) {
4455 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4456 } else { // It's not an ASCII string.
4457 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4460 if (!maybe_result->ToObject(&result)) return maybe_result;
4462 // Copy the characters into the new object, which may be either ASCII or
4464 String* string_result = String::cast(result);
4465 for (int i = 0; i < string.length(); i++) {
4466 string_result->Set(i, string[i]);
4472 Map* Heap::SymbolMapForString(String* string) {
4473 // If the string is in new space it cannot be used as a symbol.
4474 if (InNewSpace(string)) return NULL;
4476 // Find the corresponding symbol map for strings.
4477 switch (string->map()->instance_type()) {
4478 case STRING_TYPE: return symbol_map();
4479 case ASCII_STRING_TYPE: return ascii_symbol_map();
4480 case CONS_STRING_TYPE: return cons_symbol_map();
4481 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4482 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4483 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4484 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4485 return external_symbol_with_ascii_data_map();
4486 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4487 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4488 return short_external_ascii_symbol_map();
4489 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4490 return short_external_symbol_with_ascii_data_map();
4491 default: return NULL; // No match found.
4496 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4498 uint32_t hash_field) {
4500 // Ensure the chars matches the number of characters in the buffer.
4501 ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4502 // Determine whether the string is ASCII.
4503 bool is_ascii = true;
4504 while (buffer->has_more()) {
4505 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4512 // Compute map and object size.
4517 if (chars > SeqAsciiString::kMaxLength) {
4518 return Failure::OutOfMemoryException();
4520 map = ascii_symbol_map();
4521 size = SeqAsciiString::SizeFor(chars);
4523 if (chars > SeqTwoByteString::kMaxLength) {
4524 return Failure::OutOfMemoryException();
4527 size = SeqTwoByteString::SizeFor(chars);
4532 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4533 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4534 : old_data_space_->AllocateRaw(size);
4535 if (!maybe_result->ToObject(&result)) return maybe_result;
4538 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4539 // Set length and hash fields of the allocated string.
4540 String* answer = String::cast(result);
4541 answer->set_length(chars);
4542 answer->set_hash_field(hash_field);
4544 ASSERT_EQ(size, answer->Size());
4546 // Fill in the characters.
4549 uint32_t character = buffer->GetNext();
4550 if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4551 answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4552 answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4554 answer->Set(i++, character);
4561 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4562 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4563 return Failure::OutOfMemoryException();
4566 int size = SeqAsciiString::SizeFor(length);
4567 ASSERT(size <= SeqAsciiString::kMaxSize);
4569 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4570 AllocationSpace retry_space = OLD_DATA_SPACE;
4572 if (space == NEW_SPACE) {
4573 if (size > kMaxObjectSizeInNewSpace) {
4574 // Allocate in large object space, retry space will be ignored.
4576 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4577 // Allocate in new space, retry in large object space.
4578 retry_space = LO_SPACE;
4580 } else if (space == OLD_DATA_SPACE &&
4581 size > Page::kMaxNonCodeHeapObjectSize) {
4585 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4586 if (!maybe_result->ToObject(&result)) return maybe_result;
4589 // Partially initialize the object.
4590 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4591 String::cast(result)->set_length(length);
4592 String::cast(result)->set_hash_field(String::kEmptyHashField);
4593 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4596 if (FLAG_verify_heap) {
4597 // Initialize string's content to ensure ASCII-ness (character range 0-127)
4598 // as required when verifying the heap.
4599 char* dest = SeqAsciiString::cast(result)->GetChars();
4600 memset(dest, 0x0F, length * kCharSize);
4608 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4609 PretenureFlag pretenure) {
4610 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4611 return Failure::OutOfMemoryException();
4613 int size = SeqTwoByteString::SizeFor(length);
4614 ASSERT(size <= SeqTwoByteString::kMaxSize);
4615 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4616 AllocationSpace retry_space = OLD_DATA_SPACE;
4618 if (space == NEW_SPACE) {
4619 if (size > kMaxObjectSizeInNewSpace) {
4620 // Allocate in large object space, retry space will be ignored.
4622 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4623 // Allocate in new space, retry in large object space.
4624 retry_space = LO_SPACE;
4626 } else if (space == OLD_DATA_SPACE &&
4627 size > Page::kMaxNonCodeHeapObjectSize) {
4631 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4632 if (!maybe_result->ToObject(&result)) return maybe_result;
4635 // Partially initialize the object.
4636 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4637 String::cast(result)->set_length(length);
4638 String::cast(result)->set_hash_field(String::kEmptyHashField);
4639 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4644 MaybeObject* Heap::AllocateJSArray(
4645 ElementsKind elements_kind,
4646 PretenureFlag pretenure) {
4647 Context* native_context = isolate()->context()->native_context();
4648 JSFunction* array_function = native_context->array_function();
4649 Map* map = array_function->initial_map();
4650 Object* maybe_map_array = native_context->js_array_maps();
4651 if (!maybe_map_array->IsUndefined()) {
4652 Object* maybe_transitioned_map =
4653 FixedArray::cast(maybe_map_array)->get(elements_kind);
4654 if (!maybe_transitioned_map->IsUndefined()) {
4655 map = Map::cast(maybe_transitioned_map);
4659 return AllocateJSObjectFromMap(map, pretenure);
4663 MaybeObject* Heap::AllocateEmptyFixedArray() {
4664 int size = FixedArray::SizeFor(0);
4666 { MaybeObject* maybe_result =
4667 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4668 if (!maybe_result->ToObject(&result)) return maybe_result;
4670 // Initialize the object.
4671 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4673 reinterpret_cast<FixedArray*>(result)->set_length(0);
4678 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4679 if (length < 0 || length > FixedArray::kMaxLength) {
4680 return Failure::OutOfMemoryException();
4683 // Use the general function if we're forced to always allocate.
4684 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4685 // Allocate the raw data for a fixed array.
4686 int size = FixedArray::SizeFor(length);
4687 return size <= kMaxObjectSizeInNewSpace
4688 ? new_space_.AllocateRaw(size)
4689 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4693 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4694 int len = src->length();
4696 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4697 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4699 if (InNewSpace(obj)) {
4700 HeapObject* dst = HeapObject::cast(obj);
4701 dst->set_map_no_write_barrier(map);
4702 CopyBlock(dst->address() + kPointerSize,
4703 src->address() + kPointerSize,
4704 FixedArray::SizeFor(len) - kPointerSize);
4707 HeapObject::cast(obj)->set_map_no_write_barrier(map);
4708 FixedArray* result = FixedArray::cast(obj);
4709 result->set_length(len);
4712 AssertNoAllocation no_gc;
4713 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4714 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4719 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4721 int len = src->length();
4723 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4724 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4726 HeapObject* dst = HeapObject::cast(obj);
4727 dst->set_map_no_write_barrier(map);
4729 dst->address() + FixedDoubleArray::kLengthOffset,
4730 src->address() + FixedDoubleArray::kLengthOffset,
4731 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4736 MaybeObject* Heap::AllocateFixedArray(int length) {
4737 ASSERT(length >= 0);
4738 if (length == 0) return empty_fixed_array();
4740 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4741 if (!maybe_result->ToObject(&result)) return maybe_result;
4743 // Initialize header.
4744 FixedArray* array = reinterpret_cast<FixedArray*>(result);
4745 array->set_map_no_write_barrier(fixed_array_map());
4746 array->set_length(length);
4748 ASSERT(!InNewSpace(undefined_value()));
4749 MemsetPointer(array->data_start(), undefined_value(), length);
4754 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4755 if (length < 0 || length > FixedArray::kMaxLength) {
4756 return Failure::OutOfMemoryException();
4759 AllocationSpace space =
4760 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4761 int size = FixedArray::SizeFor(length);
4762 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4763 // Too big for new space.
4765 } else if (space == OLD_POINTER_SPACE &&
4766 size > Page::kMaxNonCodeHeapObjectSize) {
4767 // Too big for old pointer space.
4771 AllocationSpace retry_space =
4772 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4774 return AllocateRaw(size, space, retry_space);
4778 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4781 PretenureFlag pretenure,
4783 ASSERT(length >= 0);
4784 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4785 if (length == 0) return heap->empty_fixed_array();
4787 ASSERT(!heap->InNewSpace(filler));
4789 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4790 if (!maybe_result->ToObject(&result)) return maybe_result;
4793 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4794 FixedArray* array = FixedArray::cast(result);
4795 array->set_length(length);
4796 MemsetPointer(array->data_start(), filler, length);
4801 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4802 return AllocateFixedArrayWithFiller(this,
4809 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4810 PretenureFlag pretenure) {
4811 return AllocateFixedArrayWithFiller(this,
4818 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4819 if (length == 0) return empty_fixed_array();
4822 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4823 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4826 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4828 FixedArray::cast(obj)->set_length(length);
4833 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4834 int size = FixedDoubleArray::SizeFor(0);
4836 { MaybeObject* maybe_result =
4837 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4838 if (!maybe_result->ToObject(&result)) return maybe_result;
4840 // Initialize the object.
4841 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4842 fixed_double_array_map());
4843 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4848 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4850 PretenureFlag pretenure) {
4851 if (length == 0) return empty_fixed_array();
4853 Object* elements_object;
4854 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4855 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4856 FixedDoubleArray* elements =
4857 reinterpret_cast<FixedDoubleArray*>(elements_object);
4859 elements->set_map_no_write_barrier(fixed_double_array_map());
4860 elements->set_length(length);
4865 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4867 PretenureFlag pretenure) {
4868 if (length == 0) return empty_fixed_array();
4870 Object* elements_object;
4871 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4872 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4873 FixedDoubleArray* elements =
4874 reinterpret_cast<FixedDoubleArray*>(elements_object);
4876 for (int i = 0; i < length; ++i) {
4877 elements->set_the_hole(i);
4880 elements->set_map_no_write_barrier(fixed_double_array_map());
4881 elements->set_length(length);
4886 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4887 PretenureFlag pretenure) {
4888 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4889 return Failure::OutOfMemoryException();
4892 AllocationSpace space =
4893 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4894 int size = FixedDoubleArray::SizeFor(length);
4896 #ifndef V8_HOST_ARCH_64_BIT
4897 size += kPointerSize;
4900 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4901 // Too big for new space.
4903 } else if (space == OLD_DATA_SPACE &&
4904 size > Page::kMaxNonCodeHeapObjectSize) {
4905 // Too big for old data space.
4909 AllocationSpace retry_space =
4910 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4913 { MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
4914 if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
4917 return EnsureDoubleAligned(this, object, size);
4921 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4923 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4924 if (!maybe_result->ToObject(&result)) return maybe_result;
4926 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4928 ASSERT(result->IsHashTable());
4933 MaybeObject* Heap::AllocateNativeContext() {
4935 { MaybeObject* maybe_result =
4936 AllocateFixedArray(Context::NATIVE_CONTEXT_SLOTS);
4937 if (!maybe_result->ToObject(&result)) return maybe_result;
4939 Context* context = reinterpret_cast<Context*>(result);
4940 context->set_map_no_write_barrier(native_context_map());
4941 context->set_js_array_maps(undefined_value());
4942 ASSERT(context->IsNativeContext());
4943 ASSERT(result->IsContext());
4948 MaybeObject* Heap::AllocateGlobalContext(JSFunction* function,
4949 ScopeInfo* scope_info) {
4951 { MaybeObject* maybe_result =
4952 AllocateFixedArray(scope_info->ContextLength(), TENURED);
4953 if (!maybe_result->ToObject(&result)) return maybe_result;
4955 Context* context = reinterpret_cast<Context*>(result);
4956 context->set_map_no_write_barrier(global_context_map());
4957 context->set_closure(function);
4958 context->set_previous(function->context());
4959 context->set_extension(scope_info);
4960 context->set_global_object(function->context()->global_object());
4961 ASSERT(context->IsGlobalContext());
4962 ASSERT(result->IsContext());
4967 MaybeObject* Heap::AllocateModuleContext(ScopeInfo* scope_info) {
4969 { MaybeObject* maybe_result =
4970 AllocateFixedArray(scope_info->ContextLength(), TENURED);
4971 if (!maybe_result->ToObject(&result)) return maybe_result;
4973 Context* context = reinterpret_cast<Context*>(result);
4974 context->set_map_no_write_barrier(module_context_map());
4975 // Context links will be set later.
4976 context->set_extension(Smi::FromInt(0));
4981 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4982 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4984 { MaybeObject* maybe_result = AllocateFixedArray(length);
4985 if (!maybe_result->ToObject(&result)) return maybe_result;
4987 Context* context = reinterpret_cast<Context*>(result);
4988 context->set_map_no_write_barrier(function_context_map());
4989 context->set_closure(function);
4990 context->set_previous(function->context());
4991 context->set_extension(Smi::FromInt(0));
4992 context->set_global_object(function->context()->global_object());
4997 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
5000 Object* thrown_object) {
5001 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
5003 { MaybeObject* maybe_result =
5004 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
5005 if (!maybe_result->ToObject(&result)) return maybe_result;
5007 Context* context = reinterpret_cast<Context*>(result);
5008 context->set_map_no_write_barrier(catch_context_map());
5009 context->set_closure(function);
5010 context->set_previous(previous);
5011 context->set_extension(name);
5012 context->set_global_object(previous->global_object());
5013 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
5018 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
5020 JSObject* extension) {
5022 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
5023 if (!maybe_result->ToObject(&result)) return maybe_result;
5025 Context* context = reinterpret_cast<Context*>(result);
5026 context->set_map_no_write_barrier(with_context_map());
5027 context->set_closure(function);
5028 context->set_previous(previous);
5029 context->set_extension(extension);
5030 context->set_global_object(previous->global_object());
5035 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
5037 ScopeInfo* scope_info) {
5039 { MaybeObject* maybe_result =
5040 AllocateFixedArrayWithHoles(scope_info->ContextLength());
5041 if (!maybe_result->ToObject(&result)) return maybe_result;
5043 Context* context = reinterpret_cast<Context*>(result);
5044 context->set_map_no_write_barrier(block_context_map());
5045 context->set_closure(function);
5046 context->set_previous(previous);
5047 context->set_extension(scope_info);
5048 context->set_global_object(previous->global_object());
5053 MaybeObject* Heap::AllocateScopeInfo(int length) {
5054 FixedArray* scope_info;
5055 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
5056 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
5057 scope_info->set_map_no_write_barrier(scope_info_map());
5062 MaybeObject* Heap::AllocateStruct(InstanceType type) {
5065 #define MAKE_CASE(NAME, Name, name) \
5066 case NAME##_TYPE: map = name##_map(); break;
5067 STRUCT_LIST(MAKE_CASE)
5071 return Failure::InternalError();
5073 int size = map->instance_size();
5074 AllocationSpace space =
5075 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
5077 { MaybeObject* maybe_result = Allocate(map, space);
5078 if (!maybe_result->ToObject(&result)) return maybe_result;
5080 Struct::cast(result)->InitializeBody(size);
5085 bool Heap::IsHeapIterable() {
5086 return (!old_pointer_space()->was_swept_conservatively() &&
5087 !old_data_space()->was_swept_conservatively());
5091 void Heap::EnsureHeapIsIterable() {
5092 ASSERT(IsAllocationAllowed());
5093 if (!IsHeapIterable()) {
5094 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
5096 ASSERT(IsHeapIterable());
5100 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
5101 incremental_marking()->Step(step_size,
5102 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
5104 if (incremental_marking()->IsComplete()) {
5105 bool uncommit = false;
5106 if (gc_count_at_last_idle_gc_ == gc_count_) {
5107 // No GC since the last full GC, the mutator is probably not active.
5108 isolate_->compilation_cache()->Clear();
5111 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
5112 gc_count_at_last_idle_gc_ = gc_count_;
5114 new_space_.Shrink();
5115 UncommitFromSpace();
5121 bool Heap::IdleNotification(int hint) {
5122 // Hints greater than this value indicate that
5123 // the embedder is requesting a lot of GC work.
5124 const int kMaxHint = 1000;
5125 // Minimal hint that allows to do full GC.
5126 const int kMinHintForFullGC = 100;
5127 intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
5128 // The size factor is in range [5..250]. The numbers here are chosen from
5129 // experiments. If you changes them, make sure to test with
5130 // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
5131 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
5133 if (contexts_disposed_ > 0) {
5134 if (hint >= kMaxHint) {
5135 // The embedder is requesting a lot of GC work after context disposal,
5136 // we age inline caches so that they don't keep objects from
5137 // the old context alive.
5140 int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
5141 if (hint >= mark_sweep_time && !FLAG_expose_gc &&
5142 incremental_marking()->IsStopped()) {
5143 HistogramTimerScope scope(isolate_->counters()->gc_context());
5144 CollectAllGarbage(kReduceMemoryFootprintMask,
5145 "idle notification: contexts disposed");
5147 AdvanceIdleIncrementalMarking(step_size);
5148 contexts_disposed_ = 0;
5150 // Make sure that we have no pending context disposals.
5151 // Take into account that we might have decided to delay full collection
5152 // because incremental marking is in progress.
5153 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
5154 // After context disposal there is likely a lot of garbage remaining, reset
5155 // the idle notification counters in order to trigger more incremental GCs
5156 // on subsequent idle notifications.
5161 if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
5162 return IdleGlobalGC();
5165 // By doing small chunks of GC work in each IdleNotification,
5166 // perform a round of incremental GCs and after that wait until
5167 // the mutator creates enough garbage to justify a new round.
5168 // An incremental GC progresses as follows:
5169 // 1. many incremental marking steps,
5170 // 2. one old space mark-sweep-compact,
5171 // 3. many lazy sweep steps.
5172 // Use mark-sweep-compact events to count incremental GCs in a round.
5175 if (incremental_marking()->IsStopped()) {
5176 if (!IsSweepingComplete() &&
5177 !AdvanceSweepers(static_cast<int>(step_size))) {
5182 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5183 if (EnoughGarbageSinceLastIdleRound()) {
5190 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
5191 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
5192 ms_count_at_last_idle_notification_ = ms_count_;
5194 int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound -
5195 mark_sweeps_since_idle_round_started_;
5197 if (remaining_mark_sweeps <= 0) {
5202 if (incremental_marking()->IsStopped()) {
5203 // If there are no more than two GCs left in this idle round and we are
5204 // allowed to do a full GC, then make those GCs full in order to compact
5206 // TODO(ulan): Once we enable code compaction for incremental marking,
5207 // we can get rid of this special case and always start incremental marking.
5208 if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) {
5209 CollectAllGarbage(kReduceMemoryFootprintMask,
5210 "idle notification: finalize idle round");
5212 incremental_marking()->Start();
5215 if (!incremental_marking()->IsStopped()) {
5216 AdvanceIdleIncrementalMarking(step_size);
5222 bool Heap::IdleGlobalGC() {
5223 static const int kIdlesBeforeScavenge = 4;
5224 static const int kIdlesBeforeMarkSweep = 7;
5225 static const int kIdlesBeforeMarkCompact = 8;
5226 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
5227 static const unsigned int kGCsBetweenCleanup = 4;
5229 if (!last_idle_notification_gc_count_init_) {
5230 last_idle_notification_gc_count_ = gc_count_;
5231 last_idle_notification_gc_count_init_ = true;
5234 bool uncommit = true;
5235 bool finished = false;
5237 // Reset the number of idle notifications received when a number of
5238 // GCs have taken place. This allows another round of cleanup based
5239 // on idle notifications if enough work has been carried out to
5240 // provoke a number of garbage collections.
5241 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
5242 number_idle_notifications_ =
5243 Min(number_idle_notifications_ + 1, kMaxIdleCount);
5245 number_idle_notifications_ = 0;
5246 last_idle_notification_gc_count_ = gc_count_;
5249 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
5250 CollectGarbage(NEW_SPACE, "idle notification");
5251 new_space_.Shrink();
5252 last_idle_notification_gc_count_ = gc_count_;
5253 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
5254 // Before doing the mark-sweep collections we clear the
5255 // compilation cache to avoid hanging on to source code and
5256 // generated code for cached functions.
5257 isolate_->compilation_cache()->Clear();
5259 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5260 new_space_.Shrink();
5261 last_idle_notification_gc_count_ = gc_count_;
5263 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
5264 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5265 new_space_.Shrink();
5266 last_idle_notification_gc_count_ = gc_count_;
5267 number_idle_notifications_ = 0;
5269 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
5270 // If we have received more than kIdlesBeforeMarkCompact idle
5271 // notifications we do not perform any cleanup because we don't
5272 // expect to gain much by doing so.
5276 if (uncommit) UncommitFromSpace();
5284 void Heap::Print() {
5285 if (!HasBeenSetUp()) return;
5286 isolate()->PrintStack();
5288 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
5293 void Heap::ReportCodeStatistics(const char* title) {
5294 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5295 PagedSpace::ResetCodeStatistics();
5296 // We do not look for code in new space, map space, or old space. If code
5297 // somehow ends up in those spaces, we would miss it here.
5298 code_space_->CollectCodeStatistics();
5299 lo_space_->CollectCodeStatistics();
5300 PagedSpace::ReportCodeStatistics();
5304 // This function expects that NewSpace's allocated objects histogram is
5305 // populated (via a call to CollectStatistics or else as a side effect of a
5306 // just-completed scavenge collection).
5307 void Heap::ReportHeapStatistics(const char* title) {
5309 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5311 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5312 old_gen_promotion_limit_);
5313 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5314 old_gen_allocation_limit_);
5315 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5318 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5319 isolate_->global_handles()->PrintStats();
5322 PrintF("Heap statistics : ");
5323 isolate_->memory_allocator()->ReportStatistics();
5324 PrintF("To space : ");
5325 new_space_.ReportStatistics();
5326 PrintF("Old pointer space : ");
5327 old_pointer_space_->ReportStatistics();
5328 PrintF("Old data space : ");
5329 old_data_space_->ReportStatistics();
5330 PrintF("Code space : ");
5331 code_space_->ReportStatistics();
5332 PrintF("Map space : ");
5333 map_space_->ReportStatistics();
5334 PrintF("Cell space : ");
5335 cell_space_->ReportStatistics();
5336 PrintF("Large object space : ");
5337 lo_space_->ReportStatistics();
5338 PrintF(">>>>>> ========================================= >>>>>>\n");
5343 bool Heap::Contains(HeapObject* value) {
5344 return Contains(value->address());
5348 bool Heap::Contains(Address addr) {
5349 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5350 return HasBeenSetUp() &&
5351 (new_space_.ToSpaceContains(addr) ||
5352 old_pointer_space_->Contains(addr) ||
5353 old_data_space_->Contains(addr) ||
5354 code_space_->Contains(addr) ||
5355 map_space_->Contains(addr) ||
5356 cell_space_->Contains(addr) ||
5357 lo_space_->SlowContains(addr));
5361 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5362 return InSpace(value->address(), space);
5366 bool Heap::InSpace(Address addr, AllocationSpace space) {
5367 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5368 if (!HasBeenSetUp()) return false;
5372 return new_space_.ToSpaceContains(addr);
5373 case OLD_POINTER_SPACE:
5374 return old_pointer_space_->Contains(addr);
5375 case OLD_DATA_SPACE:
5376 return old_data_space_->Contains(addr);
5378 return code_space_->Contains(addr);
5380 return map_space_->Contains(addr);
5382 return cell_space_->Contains(addr);
5384 return lo_space_->SlowContains(addr);
5392 void Heap::Verify() {
5393 ASSERT(HasBeenSetUp());
5395 store_buffer()->Verify();
5397 VerifyPointersVisitor visitor;
5398 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5400 new_space_.Verify();
5402 old_pointer_space_->Verify(&visitor);
5403 map_space_->Verify(&visitor);
5405 VerifyPointersVisitor no_dirty_regions_visitor;
5406 old_data_space_->Verify(&no_dirty_regions_visitor);
5407 code_space_->Verify(&no_dirty_regions_visitor);
5408 cell_space_->Verify(&no_dirty_regions_visitor);
5410 lo_space_->Verify();
5417 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5418 Object* symbol = NULL;
5420 { MaybeObject* maybe_new_table =
5421 symbol_table()->LookupSymbol(string, &symbol);
5422 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5424 // Can't use set_symbol_table because SymbolTable::cast knows that
5425 // SymbolTable is a singleton and checks for identity.
5426 roots_[kSymbolTableRootIndex] = new_table;
5427 ASSERT(symbol != NULL);
5432 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5433 Object* symbol = NULL;
5435 { MaybeObject* maybe_new_table =
5436 symbol_table()->LookupAsciiSymbol(string, &symbol);
5437 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5439 // Can't use set_symbol_table because SymbolTable::cast knows that
5440 // SymbolTable is a singleton and checks for identity.
5441 roots_[kSymbolTableRootIndex] = new_table;
5442 ASSERT(symbol != NULL);
5447 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5450 Object* symbol = NULL;
5452 { MaybeObject* maybe_new_table =
5453 symbol_table()->LookupSubStringAsciiSymbol(string,
5457 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5459 // Can't use set_symbol_table because SymbolTable::cast knows that
5460 // SymbolTable is a singleton and checks for identity.
5461 roots_[kSymbolTableRootIndex] = new_table;
5462 ASSERT(symbol != NULL);
5467 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5468 Object* symbol = NULL;
5470 { MaybeObject* maybe_new_table =
5471 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5472 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5474 // Can't use set_symbol_table because SymbolTable::cast knows that
5475 // SymbolTable is a singleton and checks for identity.
5476 roots_[kSymbolTableRootIndex] = new_table;
5477 ASSERT(symbol != NULL);
5482 MaybeObject* Heap::LookupSymbol(String* string) {
5483 if (string->IsSymbol()) return string;
5484 Object* symbol = NULL;
5486 { MaybeObject* maybe_new_table =
5487 symbol_table()->LookupString(string, &symbol);
5488 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5490 // Can't use set_symbol_table because SymbolTable::cast knows that
5491 // SymbolTable is a singleton and checks for identity.
5492 roots_[kSymbolTableRootIndex] = new_table;
5493 ASSERT(symbol != NULL);
5498 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5499 if (string->IsSymbol()) {
5503 return symbol_table()->LookupSymbolIfExists(string, symbol);
5508 void Heap::ZapFromSpace() {
5509 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5510 new_space_.FromSpaceEnd());
5511 while (it.has_next()) {
5512 NewSpacePage* page = it.next();
5513 for (Address cursor = page->area_start(), limit = page->area_end();
5515 cursor += kPointerSize) {
5516 Memory::Address_at(cursor) = kFromSpaceZapValue;
5523 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5525 ObjectSlotCallback callback) {
5526 Address slot_address = start;
5528 // We are not collecting slots on new space objects during mutation
5529 // thus we have to scan for pointers to evacuation candidates when we
5530 // promote objects. But we should not record any slots in non-black
5531 // objects. Grey object's slots would be rescanned.
5532 // White object might not survive until the end of collection
5533 // it would be a violation of the invariant to record it's slots.
5534 bool record_slots = false;
5535 if (incremental_marking()->IsCompacting()) {
5536 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5537 record_slots = Marking::IsBlack(mark_bit);
5540 while (slot_address < end) {
5541 Object** slot = reinterpret_cast<Object**>(slot_address);
5542 Object* object = *slot;
5543 // If the store buffer becomes overfull we mark pages as being exempt from
5544 // the store buffer. These pages are scanned to find pointers that point
5545 // to the new space. In that case we may hit newly promoted objects and
5546 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5547 if (object->IsHeapObject()) {
5548 if (Heap::InFromSpace(object)) {
5549 callback(reinterpret_cast<HeapObject**>(slot),
5550 HeapObject::cast(object));
5551 Object* new_object = *slot;
5552 if (InNewSpace(new_object)) {
5553 SLOW_ASSERT(Heap::InToSpace(new_object));
5554 SLOW_ASSERT(new_object->IsHeapObject());
5555 store_buffer_.EnterDirectlyIntoStoreBuffer(
5556 reinterpret_cast<Address>(slot));
5558 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5559 } else if (record_slots &&
5560 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5561 mark_compact_collector()->RecordSlot(slot, slot, object);
5564 slot_address += kPointerSize;
5570 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5573 bool IsAMapPointerAddress(Object** addr) {
5574 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5575 int mod = a % Map::kSize;
5576 return mod >= Map::kPointerFieldsBeginOffset &&
5577 mod < Map::kPointerFieldsEndOffset;
5581 bool EverythingsAPointer(Object** addr) {
5586 static void CheckStoreBuffer(Heap* heap,
5589 Object**** store_buffer_position,
5590 Object*** store_buffer_top,
5591 CheckStoreBufferFilter filter,
5592 Address special_garbage_start,
5593 Address special_garbage_end) {
5594 Map* free_space_map = heap->free_space_map();
5595 for ( ; current < limit; current++) {
5596 Object* o = *current;
5597 Address current_address = reinterpret_cast<Address>(current);
5599 if (o == free_space_map) {
5600 Address current_address = reinterpret_cast<Address>(current);
5601 FreeSpace* free_space =
5602 FreeSpace::cast(HeapObject::FromAddress(current_address));
5603 int skip = free_space->Size();
5604 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5606 current_address += skip - kPointerSize;
5607 current = reinterpret_cast<Object**>(current_address);
5610 // Skip the current linear allocation space between top and limit which is
5611 // unmarked with the free space map, but can contain junk.
5612 if (current_address == special_garbage_start &&
5613 special_garbage_end != special_garbage_start) {
5614 current_address = special_garbage_end - kPointerSize;
5615 current = reinterpret_cast<Object**>(current_address);
5618 if (!(*filter)(current)) continue;
5619 ASSERT(current_address < special_garbage_start ||
5620 current_address >= special_garbage_end);
5621 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5622 // We have to check that the pointer does not point into new space
5623 // without trying to cast it to a heap object since the hash field of
5624 // a string can contain values like 1 and 3 which are tagged null
5626 if (!heap->InNewSpace(o)) continue;
5627 while (**store_buffer_position < current &&
5628 *store_buffer_position < store_buffer_top) {
5629 (*store_buffer_position)++;
5631 if (**store_buffer_position != current ||
5632 *store_buffer_position == store_buffer_top) {
5633 Object** obj_start = current;
5634 while (!(*obj_start)->IsMap()) obj_start--;
5641 // Check that the store buffer contains all intergenerational pointers by
5642 // scanning a page and ensuring that all pointers to young space are in the
5644 void Heap::OldPointerSpaceCheckStoreBuffer() {
5645 OldSpace* space = old_pointer_space();
5646 PageIterator pages(space);
5648 store_buffer()->SortUniq();
5650 while (pages.has_next()) {
5651 Page* page = pages.next();
5652 Object** current = reinterpret_cast<Object**>(page->area_start());
5654 Address end = page->area_end();
5656 Object*** store_buffer_position = store_buffer()->Start();
5657 Object*** store_buffer_top = store_buffer()->Top();
5659 Object** limit = reinterpret_cast<Object**>(end);
5660 CheckStoreBuffer(this,
5663 &store_buffer_position,
5665 &EverythingsAPointer,
5672 void Heap::MapSpaceCheckStoreBuffer() {
5673 MapSpace* space = map_space();
5674 PageIterator pages(space);
5676 store_buffer()->SortUniq();
5678 while (pages.has_next()) {
5679 Page* page = pages.next();
5680 Object** current = reinterpret_cast<Object**>(page->area_start());
5682 Address end = page->area_end();
5684 Object*** store_buffer_position = store_buffer()->Start();
5685 Object*** store_buffer_top = store_buffer()->Top();
5687 Object** limit = reinterpret_cast<Object**>(end);
5688 CheckStoreBuffer(this,
5691 &store_buffer_position,
5693 &IsAMapPointerAddress,
5700 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5701 LargeObjectIterator it(lo_space());
5702 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5703 // We only have code, sequential strings, or fixed arrays in large
5704 // object space, and only fixed arrays can possibly contain pointers to
5705 // the young generation.
5706 if (object->IsFixedArray()) {
5707 Object*** store_buffer_position = store_buffer()->Start();
5708 Object*** store_buffer_top = store_buffer()->Top();
5709 Object** current = reinterpret_cast<Object**>(object->address());
5711 reinterpret_cast<Object**>(object->address() + object->Size());
5712 CheckStoreBuffer(this,
5715 &store_buffer_position,
5717 &EverythingsAPointer,
5726 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5727 IterateStrongRoots(v, mode);
5728 IterateWeakRoots(v, mode);
5732 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5733 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5734 v->Synchronize(VisitorSynchronization::kSymbolTable);
5735 if (mode != VISIT_ALL_IN_SCAVENGE &&
5736 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5737 // Scavenge collections have special processing for this.
5738 external_string_table_.Iterate(v);
5740 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5744 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5745 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5746 v->Synchronize(VisitorSynchronization::kStrongRootList);
5748 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5749 v->Synchronize(VisitorSynchronization::kSymbol);
5751 isolate_->bootstrapper()->Iterate(v);
5752 v->Synchronize(VisitorSynchronization::kBootstrapper);
5753 isolate_->Iterate(v);
5754 v->Synchronize(VisitorSynchronization::kTop);
5755 Relocatable::Iterate(v);
5756 v->Synchronize(VisitorSynchronization::kRelocatable);
5758 #ifdef ENABLE_DEBUGGER_SUPPORT
5759 isolate_->debug()->Iterate(v);
5760 if (isolate_->deoptimizer_data() != NULL) {
5761 isolate_->deoptimizer_data()->Iterate(v);
5764 v->Synchronize(VisitorSynchronization::kDebug);
5765 isolate_->compilation_cache()->Iterate(v);
5766 v->Synchronize(VisitorSynchronization::kCompilationCache);
5768 // Iterate over local handles in handle scopes.
5769 isolate_->handle_scope_implementer()->Iterate(v);
5770 isolate_->IterateDeferredHandles(v);
5771 v->Synchronize(VisitorSynchronization::kHandleScope);
5773 // Iterate over the builtin code objects and code stubs in the
5774 // heap. Note that it is not necessary to iterate over code objects
5775 // on scavenge collections.
5776 if (mode != VISIT_ALL_IN_SCAVENGE) {
5777 isolate_->builtins()->IterateBuiltins(v);
5779 v->Synchronize(VisitorSynchronization::kBuiltins);
5781 // Iterate over global handles.
5783 case VISIT_ONLY_STRONG:
5784 isolate_->global_handles()->IterateStrongRoots(v);
5786 case VISIT_ALL_IN_SCAVENGE:
5787 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5789 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5791 isolate_->global_handles()->IterateAllRoots(v);
5794 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5796 // Iterate over pointers being held by inactive threads.
5797 isolate_->thread_manager()->Iterate(v);
5798 v->Synchronize(VisitorSynchronization::kThreadManager);
5800 // Iterate over the pointers the Serialization/Deserialization code is
5802 // During garbage collection this keeps the partial snapshot cache alive.
5803 // During deserialization of the startup snapshot this creates the partial
5804 // snapshot cache and deserializes the objects it refers to. During
5805 // serialization this does nothing, since the partial snapshot cache is
5806 // empty. However the next thing we do is create the partial snapshot,
5807 // filling up the partial snapshot cache with objects it needs as we go.
5808 SerializerDeserializer::Iterate(v);
5809 // We don't do a v->Synchronize call here, because in debug mode that will
5810 // output a flag to the snapshot. However at this point the serializer and
5811 // deserializer are deliberately a little unsynchronized (see above) so the
5812 // checking of the sync flag in the snapshot would fail.
5816 // TODO(1236194): Since the heap size is configurable on the command line
5817 // and through the API, we should gracefully handle the case that the heap
5818 // size is not big enough to fit all the initial objects.
5819 bool Heap::ConfigureHeap(int max_semispace_size,
5820 intptr_t max_old_gen_size,
5821 intptr_t max_executable_size) {
5822 if (HasBeenSetUp()) return false;
5824 if (FLAG_stress_compaction) {
5825 // This will cause more frequent GCs when stressing.
5826 max_semispace_size_ = Page::kPageSize;
5829 if (max_semispace_size > 0) {
5830 if (max_semispace_size < Page::kPageSize) {
5831 max_semispace_size = Page::kPageSize;
5832 if (FLAG_trace_gc) {
5833 PrintPID("Max semispace size cannot be less than %dkbytes\n",
5834 Page::kPageSize >> 10);
5837 max_semispace_size_ = max_semispace_size;
5840 if (Snapshot::IsEnabled()) {
5841 // If we are using a snapshot we always reserve the default amount
5842 // of memory for each semispace because code in the snapshot has
5843 // write-barrier code that relies on the size and alignment of new
5844 // space. We therefore cannot use a larger max semispace size
5845 // than the default reserved semispace size.
5846 if (max_semispace_size_ > reserved_semispace_size_) {
5847 max_semispace_size_ = reserved_semispace_size_;
5848 if (FLAG_trace_gc) {
5849 PrintPID("Max semispace size cannot be more than %dkbytes\n",
5850 reserved_semispace_size_ >> 10);
5854 // If we are not using snapshots we reserve space for the actual
5855 // max semispace size.
5856 reserved_semispace_size_ = max_semispace_size_;
5859 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5860 if (max_executable_size > 0) {
5861 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5864 // The max executable size must be less than or equal to the max old
5866 if (max_executable_size_ > max_old_generation_size_) {
5867 max_executable_size_ = max_old_generation_size_;
5870 // The new space size must be a power of two to support single-bit testing
5872 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5873 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5874 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5875 external_allocation_limit_ = 16 * max_semispace_size_;
5877 // The old generation is paged and needs at least one page for each space.
5878 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5879 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5881 RoundUp(max_old_generation_size_,
5889 bool Heap::ConfigureHeapDefault() {
5890 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5891 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5892 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5896 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5897 *stats->start_marker = HeapStats::kStartMarker;
5898 *stats->end_marker = HeapStats::kEndMarker;
5899 *stats->new_space_size = new_space_.SizeAsInt();
5900 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5901 *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5902 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5903 *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5904 *stats->old_data_space_capacity = old_data_space_->Capacity();
5905 *stats->code_space_size = code_space_->SizeOfObjects();
5906 *stats->code_space_capacity = code_space_->Capacity();
5907 *stats->map_space_size = map_space_->SizeOfObjects();
5908 *stats->map_space_capacity = map_space_->Capacity();
5909 *stats->cell_space_size = cell_space_->SizeOfObjects();
5910 *stats->cell_space_capacity = cell_space_->Capacity();
5911 *stats->lo_space_size = lo_space_->Size();
5912 isolate_->global_handles()->RecordStats(stats);
5913 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5914 *stats->memory_allocator_capacity =
5915 isolate()->memory_allocator()->Size() +
5916 isolate()->memory_allocator()->Available();
5917 *stats->os_error = OS::GetLastError();
5918 isolate()->memory_allocator()->Available();
5919 if (take_snapshot) {
5920 HeapIterator iterator;
5921 for (HeapObject* obj = iterator.next();
5923 obj = iterator.next()) {
5924 InstanceType type = obj->map()->instance_type();
5925 ASSERT(0 <= type && type <= LAST_TYPE);
5926 stats->objects_per_type[type]++;
5927 stats->size_per_type[type] += obj->Size();
5933 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5934 return old_pointer_space_->SizeOfObjects()
5935 + old_data_space_->SizeOfObjects()
5936 + code_space_->SizeOfObjects()
5937 + map_space_->SizeOfObjects()
5938 + cell_space_->SizeOfObjects()
5939 + lo_space_->SizeOfObjects();
5943 intptr_t Heap::PromotedExternalMemorySize() {
5944 if (amount_of_external_allocated_memory_
5945 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5946 return amount_of_external_allocated_memory_
5947 - amount_of_external_allocated_memory_at_last_global_gc_;
5952 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5953 static const int kMarkTag = 2;
5956 class HeapDebugUtils {
5958 explicit HeapDebugUtils(Heap* heap)
5959 : search_for_any_global_(false),
5960 search_target_(NULL),
5961 found_target_(false),
5966 class MarkObjectVisitor : public ObjectVisitor {
5968 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5970 void VisitPointers(Object** start, Object** end) {
5971 // Copy all HeapObject pointers in [start, end)
5972 for (Object** p = start; p < end; p++) {
5973 if ((*p)->IsHeapObject())
5974 utils_->MarkObjectRecursively(p);
5978 HeapDebugUtils* utils_;
5981 void MarkObjectRecursively(Object** p) {
5982 if (!(*p)->IsHeapObject()) return;
5984 HeapObject* obj = HeapObject::cast(*p);
5986 Object* map = obj->map();
5988 if (!map->IsHeapObject()) return; // visited before
5990 if (found_target_) return; // stop if target found
5991 object_stack_.Add(obj);
5992 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5993 (!search_for_any_global_ && (obj == search_target_))) {
5994 found_target_ = true;
5999 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6001 Address map_addr = map_p->address();
6003 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6005 MarkObjectRecursively(&map);
6007 MarkObjectVisitor mark_visitor(this);
6009 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
6012 if (!found_target_) // don't pop if found the target
6013 object_stack_.RemoveLast();
6017 class UnmarkObjectVisitor : public ObjectVisitor {
6019 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6021 void VisitPointers(Object** start, Object** end) {
6022 // Copy all HeapObject pointers in [start, end)
6023 for (Object** p = start; p < end; p++) {
6024 if ((*p)->IsHeapObject())
6025 utils_->UnmarkObjectRecursively(p);
6029 HeapDebugUtils* utils_;
6033 void UnmarkObjectRecursively(Object** p) {
6034 if (!(*p)->IsHeapObject()) return;
6036 HeapObject* obj = HeapObject::cast(*p);
6038 Object* map = obj->map();
6040 if (map->IsHeapObject()) return; // unmarked already
6042 Address map_addr = reinterpret_cast<Address>(map);
6044 map_addr -= kMarkTag;
6046 ASSERT_TAG_ALIGNED(map_addr);
6048 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6050 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6052 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
6054 UnmarkObjectVisitor unmark_visitor(this);
6056 obj->IterateBody(Map::cast(map_p)->instance_type(),
6057 obj->SizeFromMap(Map::cast(map_p)),
6062 void MarkRootObjectRecursively(Object** root) {
6063 if (search_for_any_global_) {
6064 ASSERT(search_target_ == NULL);
6066 ASSERT(search_target_->IsHeapObject());
6068 found_target_ = false;
6069 object_stack_.Clear();
6071 MarkObjectRecursively(root);
6072 UnmarkObjectRecursively(root);
6074 if (found_target_) {
6075 PrintF("=====================================\n");
6076 PrintF("==== Path to object ====\n");
6077 PrintF("=====================================\n\n");
6079 ASSERT(!object_stack_.is_empty());
6080 for (int i = 0; i < object_stack_.length(); i++) {
6081 if (i > 0) PrintF("\n |\n |\n V\n\n");
6082 Object* obj = object_stack_[i];
6085 PrintF("=====================================\n");
6089 // Helper class for visiting HeapObjects recursively.
6090 class MarkRootVisitor: public ObjectVisitor {
6092 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6094 void VisitPointers(Object** start, Object** end) {
6095 // Visit all HeapObject pointers in [start, end)
6096 for (Object** p = start; p < end; p++) {
6097 if ((*p)->IsHeapObject())
6098 utils_->MarkRootObjectRecursively(p);
6102 HeapDebugUtils* utils_;
6105 bool search_for_any_global_;
6106 Object* search_target_;
6108 List<Object*> object_stack_;
6117 V8_DECLARE_ONCE(initialize_gc_once);
6119 static void InitializeGCOnce() {
6120 InitializeScavengingVisitorsTables();
6121 NewSpaceScavenger::Initialize();
6122 MarkCompactCollector::Initialize();
6125 bool Heap::SetUp(bool create_heap_objects) {
6127 allocation_timeout_ = FLAG_gc_interval;
6128 debug_utils_ = new HeapDebugUtils(this);
6131 // Initialize heap spaces and initial maps and objects. Whenever something
6132 // goes wrong, just return false. The caller should check the results and
6133 // call Heap::TearDown() to release allocated memory.
6135 // If the heap is not yet configured (e.g. through the API), configure it.
6136 // Configuration is based on the flags new-space-size (really the semispace
6137 // size) and old-space-size if set or the initial values of semispace_size_
6138 // and old_generation_size_ otherwise.
6140 if (!ConfigureHeapDefault()) return false;
6143 CallOnce(&initialize_gc_once, &InitializeGCOnce);
6145 MarkMapPointersAsEncoded(false);
6147 // Set up memory allocator.
6148 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
6151 // Set up new space.
6152 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
6156 // Initialize old pointer space.
6157 old_pointer_space_ =
6159 max_old_generation_size_,
6162 if (old_pointer_space_ == NULL) return false;
6163 if (!old_pointer_space_->SetUp()) return false;
6165 // Initialize old data space.
6168 max_old_generation_size_,
6171 if (old_data_space_ == NULL) return false;
6172 if (!old_data_space_->SetUp()) return false;
6174 // Initialize the code space, set its maximum capacity to the old
6175 // generation size. It needs executable memory.
6176 // On 64-bit platform(s), we put all code objects in a 2 GB range of
6177 // virtual address space, so that they can call each other with near calls.
6178 if (code_range_size_ > 0) {
6179 if (!isolate_->code_range()->SetUp(code_range_size_)) {
6185 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
6186 if (code_space_ == NULL) return false;
6187 if (!code_space_->SetUp()) return false;
6189 // Initialize map space.
6190 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
6191 if (map_space_ == NULL) return false;
6192 if (!map_space_->SetUp()) return false;
6194 // Initialize global property cell space.
6195 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
6196 if (cell_space_ == NULL) return false;
6197 if (!cell_space_->SetUp()) return false;
6199 // The large object code space may contain code or data. We set the memory
6200 // to be non-executable here for safety, but this means we need to enable it
6201 // explicitly when allocating large code objects.
6202 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
6203 if (lo_space_ == NULL) return false;
6204 if (!lo_space_->SetUp()) return false;
6206 // Set up the seed that is used to randomize the string hash function.
6207 ASSERT(hash_seed() == 0);
6208 if (FLAG_randomize_hashes) {
6209 if (FLAG_hash_seed == 0) {
6211 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
6213 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
6217 if (create_heap_objects) {
6218 // Create initial maps.
6219 if (!CreateInitialMaps()) return false;
6220 if (!CreateApiObjects()) return false;
6222 // Create initial objects
6223 if (!CreateInitialObjects()) return false;
6225 native_contexts_list_ = undefined_value();
6228 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
6229 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
6231 store_buffer()->SetUp();
6233 if (FLAG_parallel_recompilation) relocation_mutex_ = OS::CreateMutex();
6239 void Heap::SetStackLimits() {
6240 ASSERT(isolate_ != NULL);
6241 ASSERT(isolate_ == isolate());
6242 // On 64 bit machines, pointers are generally out of range of Smis. We write
6243 // something that looks like an out of range Smi to the GC.
6245 // Set up the special root array entries containing the stack limits.
6246 // These are actually addresses, but the tag makes the GC ignore it.
6247 roots_[kStackLimitRootIndex] =
6248 reinterpret_cast<Object*>(
6249 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
6250 roots_[kRealStackLimitRootIndex] =
6251 reinterpret_cast<Object*>(
6252 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
6256 void Heap::TearDown() {
6258 if (FLAG_verify_heap) {
6262 if (FLAG_print_cumulative_gc_stat) {
6264 PrintF("gc_count=%d ", gc_count_);
6265 PrintF("mark_sweep_count=%d ", ms_count_);
6266 PrintF("max_gc_pause=%d ", get_max_gc_pause());
6267 PrintF("total_gc_time=%d ", total_gc_time_ms_);
6268 PrintF("min_in_mutator=%d ", get_min_in_mutator());
6269 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
6270 get_max_alive_after_gc());
6274 isolate_->global_handles()->TearDown();
6276 external_string_table_.TearDown();
6278 new_space_.TearDown();
6280 if (old_pointer_space_ != NULL) {
6281 old_pointer_space_->TearDown();
6282 delete old_pointer_space_;
6283 old_pointer_space_ = NULL;
6286 if (old_data_space_ != NULL) {
6287 old_data_space_->TearDown();
6288 delete old_data_space_;
6289 old_data_space_ = NULL;
6292 if (code_space_ != NULL) {
6293 code_space_->TearDown();
6298 if (map_space_ != NULL) {
6299 map_space_->TearDown();
6304 if (cell_space_ != NULL) {
6305 cell_space_->TearDown();
6310 if (lo_space_ != NULL) {
6311 lo_space_->TearDown();
6316 store_buffer()->TearDown();
6317 incremental_marking()->TearDown();
6319 isolate_->memory_allocator()->TearDown();
6321 delete relocation_mutex_;
6324 delete debug_utils_;
6325 debug_utils_ = NULL;
6330 void Heap::Shrink() {
6331 // Try to shrink all paged spaces.
6333 for (PagedSpace* space = spaces.next();
6335 space = spaces.next()) {
6336 space->ReleaseAllUnusedPages();
6341 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6342 ASSERT(callback != NULL);
6343 GCPrologueCallbackPair pair(callback, gc_type);
6344 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6345 return gc_prologue_callbacks_.Add(pair);
6349 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6350 ASSERT(callback != NULL);
6351 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6352 if (gc_prologue_callbacks_[i].callback == callback) {
6353 gc_prologue_callbacks_.Remove(i);
6361 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6362 ASSERT(callback != NULL);
6363 GCEpilogueCallbackPair pair(callback, gc_type);
6364 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6365 return gc_epilogue_callbacks_.Add(pair);
6369 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6370 ASSERT(callback != NULL);
6371 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6372 if (gc_epilogue_callbacks_[i].callback == callback) {
6373 gc_epilogue_callbacks_.Remove(i);
6383 class PrintHandleVisitor: public ObjectVisitor {
6385 void VisitPointers(Object** start, Object** end) {
6386 for (Object** p = start; p < end; p++)
6387 PrintF(" handle %p to %p\n",
6388 reinterpret_cast<void*>(p),
6389 reinterpret_cast<void*>(*p));
6393 void Heap::PrintHandles() {
6394 PrintF("Handles:\n");
6395 PrintHandleVisitor v;
6396 isolate_->handle_scope_implementer()->Iterate(&v);
6402 Space* AllSpaces::next() {
6403 switch (counter_++) {
6405 return HEAP->new_space();
6406 case OLD_POINTER_SPACE:
6407 return HEAP->old_pointer_space();
6408 case OLD_DATA_SPACE:
6409 return HEAP->old_data_space();
6411 return HEAP->code_space();
6413 return HEAP->map_space();
6415 return HEAP->cell_space();
6417 return HEAP->lo_space();
6424 PagedSpace* PagedSpaces::next() {
6425 switch (counter_++) {
6426 case OLD_POINTER_SPACE:
6427 return HEAP->old_pointer_space();
6428 case OLD_DATA_SPACE:
6429 return HEAP->old_data_space();
6431 return HEAP->code_space();
6433 return HEAP->map_space();
6435 return HEAP->cell_space();
6443 OldSpace* OldSpaces::next() {
6444 switch (counter_++) {
6445 case OLD_POINTER_SPACE:
6446 return HEAP->old_pointer_space();
6447 case OLD_DATA_SPACE:
6448 return HEAP->old_data_space();
6450 return HEAP->code_space();
6457 SpaceIterator::SpaceIterator()
6458 : current_space_(FIRST_SPACE),
6464 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6465 : current_space_(FIRST_SPACE),
6467 size_func_(size_func) {
6471 SpaceIterator::~SpaceIterator() {
6472 // Delete active iterator if any.
6477 bool SpaceIterator::has_next() {
6478 // Iterate until no more spaces.
6479 return current_space_ != LAST_SPACE;
6483 ObjectIterator* SpaceIterator::next() {
6484 if (iterator_ != NULL) {
6487 // Move to the next space
6489 if (current_space_ > LAST_SPACE) {
6494 // Return iterator for the new current space.
6495 return CreateIterator();
6499 // Create an iterator for the space to iterate.
6500 ObjectIterator* SpaceIterator::CreateIterator() {
6501 ASSERT(iterator_ == NULL);
6503 switch (current_space_) {
6505 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6507 case OLD_POINTER_SPACE:
6508 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6510 case OLD_DATA_SPACE:
6511 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6514 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6517 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6520 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6523 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6527 // Return the newly allocated iterator;
6528 ASSERT(iterator_ != NULL);
6533 class HeapObjectsFilter {
6535 virtual ~HeapObjectsFilter() {}
6536 virtual bool SkipObject(HeapObject* object) = 0;
6540 class UnreachableObjectsFilter : public HeapObjectsFilter {
6542 UnreachableObjectsFilter() {
6543 MarkReachableObjects();
6546 ~UnreachableObjectsFilter() {
6547 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6550 bool SkipObject(HeapObject* object) {
6551 MarkBit mark_bit = Marking::MarkBitFrom(object);
6552 return !mark_bit.Get();
6556 class MarkingVisitor : public ObjectVisitor {
6558 MarkingVisitor() : marking_stack_(10) {}
6560 void VisitPointers(Object** start, Object** end) {
6561 for (Object** p = start; p < end; p++) {
6562 if (!(*p)->IsHeapObject()) continue;
6563 HeapObject* obj = HeapObject::cast(*p);
6564 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6565 if (!mark_bit.Get()) {
6567 marking_stack_.Add(obj);
6572 void TransitiveClosure() {
6573 while (!marking_stack_.is_empty()) {
6574 HeapObject* obj = marking_stack_.RemoveLast();
6580 List<HeapObject*> marking_stack_;
6583 void MarkReachableObjects() {
6584 Heap* heap = Isolate::Current()->heap();
6585 MarkingVisitor visitor;
6586 heap->IterateRoots(&visitor, VISIT_ALL);
6587 visitor.TransitiveClosure();
6590 AssertNoAllocation no_alloc;
6594 HeapIterator::HeapIterator()
6595 : filtering_(HeapIterator::kNoFiltering),
6601 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6602 : filtering_(filtering),
6608 HeapIterator::~HeapIterator() {
6613 void HeapIterator::Init() {
6614 // Start the iteration.
6615 space_iterator_ = new SpaceIterator;
6616 switch (filtering_) {
6617 case kFilterUnreachable:
6618 filter_ = new UnreachableObjectsFilter;
6623 object_iterator_ = space_iterator_->next();
6627 void HeapIterator::Shutdown() {
6629 // Assert that in filtering mode we have iterated through all
6630 // objects. Otherwise, heap will be left in an inconsistent state.
6631 if (filtering_ != kNoFiltering) {
6632 ASSERT(object_iterator_ == NULL);
6635 // Make sure the last iterator is deallocated.
6636 delete space_iterator_;
6637 space_iterator_ = NULL;
6638 object_iterator_ = NULL;
6644 HeapObject* HeapIterator::next() {
6645 if (filter_ == NULL) return NextObject();
6647 HeapObject* obj = NextObject();
6648 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6653 HeapObject* HeapIterator::NextObject() {
6654 // No iterator means we are done.
6655 if (object_iterator_ == NULL) return NULL;
6657 if (HeapObject* obj = object_iterator_->next_object()) {
6658 // If the current iterator has more objects we are fine.
6661 // Go though the spaces looking for one that has objects.
6662 while (space_iterator_->has_next()) {
6663 object_iterator_ = space_iterator_->next();
6664 if (HeapObject* obj = object_iterator_->next_object()) {
6669 // Done with the last space.
6670 object_iterator_ = NULL;
6675 void HeapIterator::reset() {
6676 // Restart the iterator.
6682 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6684 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6686 class PathTracer::MarkVisitor: public ObjectVisitor {
6688 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6689 void VisitPointers(Object** start, Object** end) {
6690 // Scan all HeapObject pointers in [start, end)
6691 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6692 if ((*p)->IsHeapObject())
6693 tracer_->MarkRecursively(p, this);
6698 PathTracer* tracer_;
6702 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6704 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6705 void VisitPointers(Object** start, Object** end) {
6706 // Scan all HeapObject pointers in [start, end)
6707 for (Object** p = start; p < end; p++) {
6708 if ((*p)->IsHeapObject())
6709 tracer_->UnmarkRecursively(p, this);
6714 PathTracer* tracer_;
6718 void PathTracer::VisitPointers(Object** start, Object** end) {
6719 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6720 // Visit all HeapObject pointers in [start, end)
6721 for (Object** p = start; !done && (p < end); p++) {
6722 if ((*p)->IsHeapObject()) {
6724 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6730 void PathTracer::Reset() {
6731 found_target_ = false;
6732 object_stack_.Clear();
6736 void PathTracer::TracePathFrom(Object** root) {
6737 ASSERT((search_target_ == kAnyGlobalObject) ||
6738 search_target_->IsHeapObject());
6739 found_target_in_trace_ = false;
6742 MarkVisitor mark_visitor(this);
6743 MarkRecursively(root, &mark_visitor);
6745 UnmarkVisitor unmark_visitor(this);
6746 UnmarkRecursively(root, &unmark_visitor);
6752 static bool SafeIsNativeContext(HeapObject* obj) {
6753 return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map();
6757 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6758 if (!(*p)->IsHeapObject()) return;
6760 HeapObject* obj = HeapObject::cast(*p);
6762 Object* map = obj->map();
6764 if (!map->IsHeapObject()) return; // visited before
6766 if (found_target_in_trace_) return; // stop if target found
6767 object_stack_.Add(obj);
6768 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6769 (obj == search_target_)) {
6770 found_target_in_trace_ = true;
6771 found_target_ = true;
6775 bool is_native_context = SafeIsNativeContext(obj);
6778 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6780 Address map_addr = map_p->address();
6782 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6784 // Scan the object body.
6785 if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6786 // This is specialized to scan Context's properly.
6787 Object** start = reinterpret_cast<Object**>(obj->address() +
6788 Context::kHeaderSize);
6789 Object** end = reinterpret_cast<Object**>(obj->address() +
6790 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6791 mark_visitor->VisitPointers(start, end);
6793 obj->IterateBody(map_p->instance_type(),
6794 obj->SizeFromMap(map_p),
6798 // Scan the map after the body because the body is a lot more interesting
6799 // when doing leak detection.
6800 MarkRecursively(&map, mark_visitor);
6802 if (!found_target_in_trace_) // don't pop if found the target
6803 object_stack_.RemoveLast();
6807 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6808 if (!(*p)->IsHeapObject()) return;
6810 HeapObject* obj = HeapObject::cast(*p);
6812 Object* map = obj->map();
6814 if (map->IsHeapObject()) return; // unmarked already
6816 Address map_addr = reinterpret_cast<Address>(map);
6818 map_addr -= kMarkTag;
6820 ASSERT_TAG_ALIGNED(map_addr);
6822 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6824 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6826 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6828 obj->IterateBody(Map::cast(map_p)->instance_type(),
6829 obj->SizeFromMap(Map::cast(map_p)),
6834 void PathTracer::ProcessResults() {
6835 if (found_target_) {
6836 PrintF("=====================================\n");
6837 PrintF("==== Path to object ====\n");
6838 PrintF("=====================================\n\n");
6840 ASSERT(!object_stack_.is_empty());
6841 for (int i = 0; i < object_stack_.length(); i++) {
6842 if (i > 0) PrintF("\n |\n |\n V\n\n");
6843 Object* obj = object_stack_[i];
6846 PrintF("=====================================\n");
6849 #endif // DEBUG || LIVE_OBJECT_LIST
6853 // Triggers a depth-first traversal of reachable objects from one
6854 // given root object and finds a path to a specific heap object and
6856 void Heap::TracePathToObjectFrom(Object* target, Object* root) {
6857 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6858 tracer.VisitPointer(&root);
6862 // Triggers a depth-first traversal of reachable objects from roots
6863 // and finds a path to a specific heap object and prints it.
6864 void Heap::TracePathToObject(Object* target) {
6865 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6866 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6870 // Triggers a depth-first traversal of reachable objects from roots
6871 // and finds a path to any global object and prints it. Useful for
6872 // determining the source for leaks of global objects.
6873 void Heap::TracePathToGlobal() {
6874 PathTracer tracer(PathTracer::kAnyGlobalObject,
6875 PathTracer::FIND_ALL,
6877 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6882 static intptr_t CountTotalHolesSize() {
6883 intptr_t holes_size = 0;
6885 for (OldSpace* space = spaces.next();
6887 space = spaces.next()) {
6888 holes_size += space->Waste() + space->Available();
6894 GCTracer::GCTracer(Heap* heap,
6895 const char* gc_reason,
6896 const char* collector_reason)
6898 start_object_size_(0),
6899 start_memory_size_(0),
6902 allocated_since_last_gc_(0),
6903 spent_in_mutator_(0),
6904 promoted_objects_size_(0),
6906 gc_reason_(gc_reason),
6907 collector_reason_(collector_reason) {
6908 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6909 start_time_ = OS::TimeCurrentMillis();
6910 start_object_size_ = heap_->SizeOfObjects();
6911 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6913 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6917 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6919 allocated_since_last_gc_ =
6920 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6922 if (heap_->last_gc_end_timestamp_ > 0) {
6923 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6926 steps_count_ = heap_->incremental_marking()->steps_count();
6927 steps_took_ = heap_->incremental_marking()->steps_took();
6928 longest_step_ = heap_->incremental_marking()->longest_step();
6929 steps_count_since_last_gc_ =
6930 heap_->incremental_marking()->steps_count_since_last_gc();
6931 steps_took_since_last_gc_ =
6932 heap_->incremental_marking()->steps_took_since_last_gc();
6936 GCTracer::~GCTracer() {
6937 // Printf ONE line iff flag is set.
6938 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6940 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6942 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6943 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6945 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6947 // Update cumulative GC statistics if required.
6948 if (FLAG_print_cumulative_gc_stat) {
6949 heap_->total_gc_time_ms_ += time;
6950 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6951 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6952 heap_->alive_after_last_gc_);
6954 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6955 static_cast<int>(spent_in_mutator_));
6957 } else if (FLAG_trace_gc_verbose) {
6958 heap_->total_gc_time_ms_ += time;
6961 if (collector_ == SCAVENGER && FLAG_trace_gc_ignore_scavenger) return;
6963 PrintPID("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6965 if (!FLAG_trace_gc_nvp) {
6966 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6968 double end_memory_size_mb =
6969 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6971 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6973 static_cast<double>(start_object_size_) / MB,
6974 static_cast<double>(start_memory_size_) / MB,
6975 SizeOfHeapObjects(),
6976 end_memory_size_mb);
6978 if (external_time > 0) PrintF("%d / ", external_time);
6979 PrintF("%d ms", time);
6980 if (steps_count_ > 0) {
6981 if (collector_ == SCAVENGER) {
6982 PrintF(" (+ %d ms in %d steps since last GC)",
6983 static_cast<int>(steps_took_since_last_gc_),
6984 steps_count_since_last_gc_);
6986 PrintF(" (+ %d ms in %d steps since start of marking, "
6987 "biggest step %f ms)",
6988 static_cast<int>(steps_took_),
6994 if (gc_reason_ != NULL) {
6995 PrintF(" [%s]", gc_reason_);
6998 if (collector_reason_ != NULL) {
6999 PrintF(" [%s]", collector_reason_);
7004 PrintF("pause=%d ", time);
7005 PrintF("mutator=%d ", static_cast<int>(spent_in_mutator_));
7007 switch (collector_) {
7011 case MARK_COMPACTOR:
7019 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
7020 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
7021 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
7022 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
7023 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
7024 PrintF("new_new=%d ",
7025 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
7026 PrintF("root_new=%d ",
7027 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
7028 PrintF("old_new=%d ",
7029 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
7030 PrintF("compaction_ptrs=%d ",
7031 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
7032 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
7033 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
7034 PrintF("misc_compaction=%d ",
7035 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
7037 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
7038 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
7039 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
7040 in_free_list_or_wasted_before_gc_);
7041 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
7043 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
7044 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
7046 if (collector_ == SCAVENGER) {
7047 PrintF("stepscount=%d ", steps_count_since_last_gc_);
7048 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
7050 PrintF("stepscount=%d ", steps_count_);
7051 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
7057 heap_->PrintShortHeapStatistics();
7061 const char* GCTracer::CollectorString() {
7062 switch (collector_) {
7065 case MARK_COMPACTOR:
7066 return "Mark-sweep";
7068 return "Unknown GC";
7072 int KeyedLookupCache::Hash(Map* map, String* name) {
7073 // Uses only lower 32 bits if pointers are larger.
7074 uintptr_t addr_hash =
7075 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
7076 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
7080 int KeyedLookupCache::Lookup(Map* map, String* name) {
7081 int index = (Hash(map, name) & kHashMask);
7082 for (int i = 0; i < kEntriesPerBucket; i++) {
7083 Key& key = keys_[index + i];
7084 if ((key.map == map) && key.name->Equals(name)) {
7085 return field_offsets_[index + i];
7092 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
7094 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
7095 int index = (Hash(map, symbol) & kHashMask);
7096 // After a GC there will be free slots, so we use them in order (this may
7097 // help to get the most frequently used one in position 0).
7098 for (int i = 0; i< kEntriesPerBucket; i++) {
7099 Key& key = keys_[index];
7100 Object* free_entry_indicator = NULL;
7101 if (key.map == free_entry_indicator) {
7104 field_offsets_[index + i] = field_offset;
7108 // No free entry found in this bucket, so we move them all down one and
7109 // put the new entry at position zero.
7110 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
7111 Key& key = keys_[index + i];
7112 Key& key2 = keys_[index + i - 1];
7114 field_offsets_[index + i] = field_offsets_[index + i - 1];
7117 // Write the new first entry.
7118 Key& key = keys_[index];
7121 field_offsets_[index] = field_offset;
7126 void KeyedLookupCache::Clear() {
7127 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
7131 void DescriptorLookupCache::Clear() {
7132 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
7137 void Heap::GarbageCollectionGreedyCheck() {
7138 ASSERT(FLAG_gc_greedy);
7139 if (isolate_->bootstrapper()->IsActive()) return;
7140 if (disallow_allocation_failure()) return;
7141 CollectGarbage(NEW_SPACE);
7146 TranscendentalCache::SubCache::SubCache(Type t)
7148 isolate_(Isolate::Current()) {
7149 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
7150 uint32_t in1 = 0xffffffffu; // generated by the FPU.
7151 for (int i = 0; i < kCacheSize; i++) {
7152 elements_[i].in[0] = in0;
7153 elements_[i].in[1] = in1;
7154 elements_[i].output = NULL;
7159 void TranscendentalCache::Clear() {
7160 for (int i = 0; i < kNumberOfCaches; i++) {
7161 if (caches_[i] != NULL) {
7169 void ExternalStringTable::CleanUp() {
7171 for (int i = 0; i < new_space_strings_.length(); ++i) {
7172 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7175 if (heap_->InNewSpace(new_space_strings_[i])) {
7176 new_space_strings_[last++] = new_space_strings_[i];
7178 old_space_strings_.Add(new_space_strings_[i]);
7181 new_space_strings_.Rewind(last);
7183 for (int i = 0; i < old_space_strings_.length(); ++i) {
7184 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7187 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
7188 old_space_strings_[last++] = old_space_strings_[i];
7190 old_space_strings_.Rewind(last);
7191 if (FLAG_verify_heap) {
7197 void ExternalStringTable::TearDown() {
7198 new_space_strings_.Free();
7199 old_space_strings_.Free();
7203 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
7204 chunk->set_next_chunk(chunks_queued_for_free_);
7205 chunks_queued_for_free_ = chunk;
7209 void Heap::FreeQueuedChunks() {
7210 if (chunks_queued_for_free_ == NULL) return;
7213 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7214 next = chunk->next_chunk();
7215 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7217 if (chunk->owner()->identity() == LO_SPACE) {
7218 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
7219 // If FromAnyPointerAddress encounters a slot that belongs to a large
7220 // chunk queued for deletion it will fail to find the chunk because
7221 // it try to perform a search in the list of pages owned by of the large
7222 // object space and queued chunks were detached from that list.
7223 // To work around this we split large chunk into normal kPageSize aligned
7224 // pieces and initialize size, owner and flags field of every piece.
7225 // If FromAnyPointerAddress encounters a slot that belongs to one of
7226 // these smaller pieces it will treat it as a slot on a normal Page.
7227 Address chunk_end = chunk->address() + chunk->size();
7228 MemoryChunk* inner = MemoryChunk::FromAddress(
7229 chunk->address() + Page::kPageSize);
7230 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
7231 while (inner <= inner_last) {
7232 // Size of a large chunk is always a multiple of
7233 // OS::AllocateAlignment() so there is always
7234 // enough space for a fake MemoryChunk header.
7235 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
7236 // Guard against overflow.
7237 if (area_end < inner->address()) area_end = chunk_end;
7238 inner->SetArea(inner->address(), area_end);
7239 inner->set_size(Page::kPageSize);
7240 inner->set_owner(lo_space());
7241 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7242 inner = MemoryChunk::FromAddress(
7243 inner->address() + Page::kPageSize);
7247 isolate_->heap()->store_buffer()->Compact();
7248 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
7249 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7250 next = chunk->next_chunk();
7251 isolate_->memory_allocator()->Free(chunk);
7253 chunks_queued_for_free_ = NULL;
7257 void Heap::RememberUnmappedPage(Address page, bool compacted) {
7258 uintptr_t p = reinterpret_cast<uintptr_t>(page);
7259 // Tag the page pointer to make it findable in the dump file.
7261 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
7263 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
7265 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
7266 reinterpret_cast<Address>(p);
7267 remembered_unmapped_pages_index_++;
7268 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
7272 void Heap::ClearObjectStats(bool clear_last_time_stats) {
7273 memset(object_counts_, 0, sizeof(object_counts_));
7274 memset(object_sizes_, 0, sizeof(object_sizes_));
7275 if (clear_last_time_stats) {
7276 memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_));
7277 memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_));
7282 static LazyMutex checkpoint_object_stats_mutex = LAZY_MUTEX_INITIALIZER;
7285 void Heap::CheckpointObjectStats() {
7286 ScopedLock lock(checkpoint_object_stats_mutex.Pointer());
7287 Counters* counters = isolate()->counters();
7288 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
7289 counters->count_of_##name()->Increment( \
7290 static_cast<int>(object_counts_[name])); \
7291 counters->count_of_##name()->Decrement( \
7292 static_cast<int>(object_counts_last_time_[name])); \
7293 counters->size_of_##name()->Increment( \
7294 static_cast<int>(object_sizes_[name])); \
7295 counters->size_of_##name()->Decrement( \
7296 static_cast<int>(object_sizes_last_time_[name]));
7297 INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7298 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7300 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
7301 index = FIRST_CODE_KIND_SUB_TYPE + Code::name; \
7302 counters->count_of_CODE_TYPE_##name()->Increment( \
7303 static_cast<int>(object_counts_[index])); \
7304 counters->count_of_CODE_TYPE_##name()->Decrement( \
7305 static_cast<int>(object_counts_last_time_[index])); \
7306 counters->size_of_CODE_TYPE_##name()->Increment( \
7307 static_cast<int>(object_sizes_[index])); \
7308 counters->size_of_CODE_TYPE_##name()->Decrement( \
7309 static_cast<int>(object_sizes_last_time_[index]));
7310 CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7311 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7312 #define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
7313 index = FIRST_FIXED_ARRAY_SUB_TYPE + name; \
7314 counters->count_of_FIXED_ARRAY_##name()->Increment( \
7315 static_cast<int>(object_counts_[index])); \
7316 counters->count_of_FIXED_ARRAY_##name()->Decrement( \
7317 static_cast<int>(object_counts_last_time_[index])); \
7318 counters->size_of_FIXED_ARRAY_##name()->Increment( \
7319 static_cast<int>(object_sizes_[index])); \
7320 counters->size_of_FIXED_ARRAY_##name()->Decrement( \
7321 static_cast<int>(object_sizes_last_time_[index]));
7322 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7323 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7325 memcpy(object_counts_last_time_, object_counts_, sizeof(object_counts_));
7326 memcpy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_));
7330 } } // namespace v8::internal