1 // Copyright 2011 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 "liveobjectlist-inl.h"
40 #include "mark-compact.h"
42 #include "objects-visiting.h"
43 #include "runtime-profiler.h"
44 #include "scopeinfo.h"
46 #include "v8threads.h"
47 #include "vm-state-inl.h"
48 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
49 #include "regexp-macro-assembler.h"
50 #include "arm/regexp-macro-assembler-arm.h"
52 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
53 #include "regexp-macro-assembler.h"
54 #include "mips/regexp-macro-assembler-mips.h"
61 static const intptr_t kMinimumPromotionLimit = 2 * MB;
62 static const intptr_t kMinimumAllocationLimit = 8 * MB;
65 static Mutex* gc_initializer_mutex = OS::CreateMutex();
70 // semispace_size_ should be a power of 2 and old_generation_size_ should be
71 // a multiple of Page::kPageSize.
73 reserved_semispace_size_(2*MB),
74 max_semispace_size_(2*MB),
75 initial_semispace_size_(128*KB),
76 max_old_generation_size_(192*MB),
77 max_executable_size_(max_old_generation_size_),
79 #elif defined(V8_TARGET_ARCH_X64)
80 reserved_semispace_size_(16*MB),
81 max_semispace_size_(16*MB),
82 initial_semispace_size_(1*MB),
83 max_old_generation_size_(1400*MB),
84 max_executable_size_(256*MB),
85 code_range_size_(512*MB),
87 reserved_semispace_size_(8*MB),
88 max_semispace_size_(8*MB),
89 initial_semispace_size_(512*KB),
90 max_old_generation_size_(700*MB),
91 max_executable_size_(128*MB),
94 // Variables set based on semispace_size_ and old_generation_size_ in
95 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
96 // Will be 4 * reserved_semispace_size_ to ensure that young
97 // generation can be aligned to its size.
98 survived_since_last_expansion_(0),
100 always_allocate_scope_depth_(0),
101 linear_allocation_scope_depth_(0),
102 contexts_disposed_(0),
104 old_pointer_space_(NULL),
105 old_data_space_(NULL),
110 gc_state_(NOT_IN_GC),
111 gc_post_processing_depth_(0),
115 unflattened_strings_length_(0),
117 allocation_allowed_(true),
118 allocation_timeout_(0),
119 disallow_allocation_failure_(false),
122 old_gen_promotion_limit_(kMinimumPromotionLimit),
123 old_gen_allocation_limit_(kMinimumAllocationLimit),
124 external_allocation_limit_(0),
125 amount_of_external_allocated_memory_(0),
126 amount_of_external_allocated_memory_at_last_global_gc_(0),
127 old_gen_exhausted_(false),
128 hidden_symbol_(NULL),
129 global_gc_prologue_callback_(NULL),
130 global_gc_epilogue_callback_(NULL),
131 gc_safe_size_of_old_object_(NULL),
132 total_regexp_code_generated_(0),
134 young_survivors_after_last_gc_(0),
135 high_survival_rate_period_length_(0),
137 previous_survival_rate_trend_(Heap::STABLE),
138 survival_rate_trend_(Heap::STABLE),
140 max_alive_after_gc_(0),
141 min_in_mutator_(kMaxInt),
142 alive_after_last_gc_(0),
143 last_gc_end_timestamp_(0.0),
144 page_watermark_invalidated_mark_(1 << Page::WATERMARK_INVALIDATED),
145 number_idle_notifications_(0),
146 last_idle_notification_gc_count_(0),
147 last_idle_notification_gc_count_init_(false),
149 is_safe_to_read_maps_(true) {
150 // Allow build-time customization of the max semispace size. Building
151 // V8 with snapshots and a non-default max semispace size is much
152 // easier if you can define it as part of the build environment.
153 #if defined(V8_MAX_SEMISPACE_SIZE)
154 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
157 intptr_t max_virtual = OS::MaxVirtualMemory();
159 if (max_virtual > 0) {
160 if (code_range_size_ > 0) {
161 // Reserve no more than 1/8 of the memory for the code range.
162 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
166 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
167 global_contexts_list_ = NULL;
168 mark_compact_collector_.heap_ = this;
169 external_string_table_.heap_ = this;
173 intptr_t Heap::Capacity() {
174 if (!HasBeenSetup()) return 0;
176 return new_space_.Capacity() +
177 old_pointer_space_->Capacity() +
178 old_data_space_->Capacity() +
179 code_space_->Capacity() +
180 map_space_->Capacity() +
181 cell_space_->Capacity();
185 intptr_t Heap::CommittedMemory() {
186 if (!HasBeenSetup()) return 0;
188 return new_space_.CommittedMemory() +
189 old_pointer_space_->CommittedMemory() +
190 old_data_space_->CommittedMemory() +
191 code_space_->CommittedMemory() +
192 map_space_->CommittedMemory() +
193 cell_space_->CommittedMemory() +
197 intptr_t Heap::CommittedMemoryExecutable() {
198 if (!HasBeenSetup()) return 0;
200 return isolate()->memory_allocator()->SizeExecutable();
204 intptr_t Heap::Available() {
205 if (!HasBeenSetup()) return 0;
207 return new_space_.Available() +
208 old_pointer_space_->Available() +
209 old_data_space_->Available() +
210 code_space_->Available() +
211 map_space_->Available() +
212 cell_space_->Available();
216 bool Heap::HasBeenSetup() {
217 return old_pointer_space_ != NULL &&
218 old_data_space_ != NULL &&
219 code_space_ != NULL &&
220 map_space_ != NULL &&
221 cell_space_ != NULL &&
226 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
227 ASSERT(!HEAP->InNewSpace(object)); // Code only works for old objects.
228 ASSERT(!HEAP->mark_compact_collector()->are_map_pointers_encoded());
229 MapWord map_word = object->map_word();
230 map_word.ClearMark();
231 map_word.ClearOverflow();
232 return object->SizeFromMap(map_word.ToMap());
236 int Heap::GcSafeSizeOfOldObjectWithEncodedMap(HeapObject* object) {
237 ASSERT(!HEAP->InNewSpace(object)); // Code only works for old objects.
238 ASSERT(HEAP->mark_compact_collector()->are_map_pointers_encoded());
239 uint32_t marker = Memory::uint32_at(object->address());
240 if (marker == MarkCompactCollector::kSingleFreeEncoding) {
242 } else if (marker == MarkCompactCollector::kMultiFreeEncoding) {
243 return Memory::int_at(object->address() + kIntSize);
245 MapWord map_word = object->map_word();
246 Address map_address = map_word.DecodeMapAddress(HEAP->map_space());
247 Map* map = reinterpret_cast<Map*>(HeapObject::FromAddress(map_address));
248 return object->SizeFromMap(map);
253 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
254 // Is global GC requested?
255 if (space != NEW_SPACE || FLAG_gc_global) {
256 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
257 return MARK_COMPACTOR;
260 // Is enough data promoted to justify a global GC?
261 if (OldGenerationPromotionLimitReached()) {
262 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
263 return MARK_COMPACTOR;
266 // Have allocation in OLD and LO failed?
267 if (old_gen_exhausted_) {
268 isolate_->counters()->
269 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
270 return MARK_COMPACTOR;
273 // Is there enough space left in OLD to guarantee that a scavenge can
276 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
277 // for object promotion. It counts only the bytes that the memory
278 // allocator has not yet allocated from the OS and assigned to any space,
279 // and does not count available bytes already in the old space or code
280 // space. Undercounting is safe---we may get an unrequested full GC when
281 // a scavenge would have succeeded.
282 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
283 isolate_->counters()->
284 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
285 return MARK_COMPACTOR;
293 // TODO(1238405): Combine the infrastructure for --heap-stats and
294 // --log-gc to avoid the complicated preprocessor and flag testing.
295 void Heap::ReportStatisticsBeforeGC() {
296 // Heap::ReportHeapStatistics will also log NewSpace statistics when
297 // compiled --log-gc is set. The following logic is used to avoid
300 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
301 if (FLAG_heap_stats) {
302 ReportHeapStatistics("Before GC");
303 } else if (FLAG_log_gc) {
304 new_space_.ReportStatistics();
306 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
309 new_space_.CollectStatistics();
310 new_space_.ReportStatistics();
311 new_space_.ClearHistograms();
317 void Heap::PrintShortHeapStatistics() {
318 if (!FLAG_trace_gc_verbose) return;
319 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
320 ", available: %8" V8_PTR_PREFIX "d\n",
321 isolate_->memory_allocator()->Size(),
322 isolate_->memory_allocator()->Available());
323 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
324 ", available: %8" V8_PTR_PREFIX "d\n",
325 Heap::new_space_.Size(),
326 new_space_.Available());
327 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
328 ", available: %8" V8_PTR_PREFIX "d"
329 ", waste: %8" V8_PTR_PREFIX "d\n",
330 old_pointer_space_->Size(),
331 old_pointer_space_->Available(),
332 old_pointer_space_->Waste());
333 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
334 ", available: %8" V8_PTR_PREFIX "d"
335 ", waste: %8" V8_PTR_PREFIX "d\n",
336 old_data_space_->Size(),
337 old_data_space_->Available(),
338 old_data_space_->Waste());
339 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
340 ", available: %8" V8_PTR_PREFIX "d"
341 ", waste: %8" V8_PTR_PREFIX "d\n",
343 code_space_->Available(),
344 code_space_->Waste());
345 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
346 ", available: %8" V8_PTR_PREFIX "d"
347 ", waste: %8" V8_PTR_PREFIX "d\n",
349 map_space_->Available(),
350 map_space_->Waste());
351 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
352 ", available: %8" V8_PTR_PREFIX "d"
353 ", waste: %8" V8_PTR_PREFIX "d\n",
355 cell_space_->Available(),
356 cell_space_->Waste());
357 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
358 ", available: %8" V8_PTR_PREFIX "d\n",
360 lo_space_->Available());
364 // TODO(1238405): Combine the infrastructure for --heap-stats and
365 // --log-gc to avoid the complicated preprocessor and flag testing.
366 void Heap::ReportStatisticsAfterGC() {
367 // Similar to the before GC, we use some complicated logic to ensure that
368 // NewSpace statistics are logged exactly once when --log-gc is turned on.
370 if (FLAG_heap_stats) {
371 new_space_.CollectStatistics();
372 ReportHeapStatistics("After GC");
373 } else if (FLAG_log_gc) {
374 new_space_.ReportStatistics();
377 if (FLAG_log_gc) new_space_.ReportStatistics();
382 void Heap::GarbageCollectionPrologue() {
383 isolate_->transcendental_cache()->Clear();
384 ClearJSFunctionResultCaches();
386 unflattened_strings_length_ = 0;
388 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
389 allow_allocation(false);
391 if (FLAG_verify_heap) {
395 if (FLAG_gc_verbose) Print();
399 ReportStatisticsBeforeGC();
402 LiveObjectList::GCPrologue();
405 intptr_t Heap::SizeOfObjects() {
408 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
409 total += space->SizeOfObjects();
414 void Heap::GarbageCollectionEpilogue() {
415 LiveObjectList::GCEpilogue();
417 allow_allocation(true);
420 if (FLAG_verify_heap) {
424 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
425 if (FLAG_print_handles) PrintHandles();
426 if (FLAG_gc_verbose) Print();
427 if (FLAG_code_stats) ReportCodeStatistics("After GC");
430 isolate_->counters()->alive_after_last_gc()->Set(
431 static_cast<int>(SizeOfObjects()));
433 isolate_->counters()->symbol_table_capacity()->Set(
434 symbol_table()->Capacity());
435 isolate_->counters()->number_of_symbols()->Set(
436 symbol_table()->NumberOfElements());
438 ReportStatisticsAfterGC();
440 #ifdef ENABLE_DEBUGGER_SUPPORT
441 isolate_->debug()->AfterGarbageCollection();
442 #endif // ENABLE_DEBUGGER_SUPPORT
446 void Heap::CollectAllGarbage(bool force_compaction) {
447 // Since we are ignoring the return value, the exact choice of space does
448 // not matter, so long as we do not specify NEW_SPACE, which would not
450 mark_compact_collector_.SetForceCompaction(force_compaction);
451 CollectGarbage(OLD_POINTER_SPACE);
452 mark_compact_collector_.SetForceCompaction(false);
456 void Heap::CollectAllAvailableGarbage() {
457 // Since we are ignoring the return value, the exact choice of space does
458 // not matter, so long as we do not specify NEW_SPACE, which would not
460 mark_compact_collector()->SetForceCompaction(true);
462 // Major GC would invoke weak handle callbacks on weakly reachable
463 // handles, but won't collect weakly reachable objects until next
464 // major GC. Therefore if we collect aggressively and weak handle callback
465 // has been invoked, we rerun major GC to release objects which become
467 // Note: as weak callbacks can execute arbitrary code, we cannot
468 // hope that eventually there will be no weak callbacks invocations.
469 // Therefore stop recollecting after several attempts.
470 const int kMaxNumberOfAttempts = 7;
471 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
472 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR)) {
476 mark_compact_collector()->SetForceCompaction(false);
480 bool Heap::CollectGarbage(AllocationSpace space, GarbageCollector collector) {
481 // The VM is in the GC state until exiting this function.
482 VMState state(isolate_, GC);
485 // Reset the allocation timeout to the GC interval, but make sure to
486 // allow at least a few allocations after a collection. The reason
487 // for this is that we have a lot of allocation sequences and we
488 // assume that a garbage collection will allow the subsequent
489 // allocation attempts to go through.
490 allocation_timeout_ = Max(6, FLAG_gc_interval);
493 bool next_gc_likely_to_collect_more = false;
495 { GCTracer tracer(this);
496 GarbageCollectionPrologue();
497 // The GC count was incremented in the prologue. Tell the tracer about
499 tracer.set_gc_count(gc_count_);
501 // Tell the tracer which collector we've selected.
502 tracer.set_collector(collector);
504 HistogramTimer* rate = (collector == SCAVENGER)
505 ? isolate_->counters()->gc_scavenger()
506 : isolate_->counters()->gc_compactor();
508 next_gc_likely_to_collect_more =
509 PerformGarbageCollection(collector, &tracer);
512 GarbageCollectionEpilogue();
515 return next_gc_likely_to_collect_more;
519 void Heap::PerformScavenge() {
520 GCTracer tracer(this);
521 PerformGarbageCollection(SCAVENGER, &tracer);
526 // Helper class for verifying the symbol table.
527 class SymbolTableVerifier : public ObjectVisitor {
529 void VisitPointers(Object** start, Object** end) {
530 // Visit all HeapObject pointers in [start, end).
531 for (Object** p = start; p < end; p++) {
532 if ((*p)->IsHeapObject()) {
533 // Check that the symbol is actually a symbol.
534 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
542 static void VerifySymbolTable() {
544 SymbolTableVerifier verifier;
545 HEAP->symbol_table()->IterateElements(&verifier);
550 void Heap::ReserveSpace(
552 int pointer_space_size,
557 int large_object_size) {
558 NewSpace* new_space = Heap::new_space();
559 PagedSpace* old_pointer_space = Heap::old_pointer_space();
560 PagedSpace* old_data_space = Heap::old_data_space();
561 PagedSpace* code_space = Heap::code_space();
562 PagedSpace* map_space = Heap::map_space();
563 PagedSpace* cell_space = Heap::cell_space();
564 LargeObjectSpace* lo_space = Heap::lo_space();
565 bool gc_performed = true;
566 while (gc_performed) {
567 gc_performed = false;
568 if (!new_space->ReserveSpace(new_space_size)) {
569 Heap::CollectGarbage(NEW_SPACE);
572 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
573 Heap::CollectGarbage(OLD_POINTER_SPACE);
576 if (!(old_data_space->ReserveSpace(data_space_size))) {
577 Heap::CollectGarbage(OLD_DATA_SPACE);
580 if (!(code_space->ReserveSpace(code_space_size))) {
581 Heap::CollectGarbage(CODE_SPACE);
584 if (!(map_space->ReserveSpace(map_space_size))) {
585 Heap::CollectGarbage(MAP_SPACE);
588 if (!(cell_space->ReserveSpace(cell_space_size))) {
589 Heap::CollectGarbage(CELL_SPACE);
592 // We add a slack-factor of 2 in order to have space for a series of
593 // large-object allocations that are only just larger than the page size.
594 large_object_size *= 2;
595 // The ReserveSpace method on the large object space checks how much
596 // we can expand the old generation. This includes expansion caused by
597 // allocation in the other spaces.
598 large_object_size += cell_space_size + map_space_size + code_space_size +
599 data_space_size + pointer_space_size;
600 if (!(lo_space->ReserveSpace(large_object_size))) {
601 Heap::CollectGarbage(LO_SPACE);
608 void Heap::EnsureFromSpaceIsCommitted() {
609 if (new_space_.CommitFromSpaceIfNeeded()) return;
611 // Committing memory to from space failed.
612 // Try shrinking and try again.
614 for (PagedSpace* space = spaces.next();
616 space = spaces.next()) {
617 space->RelinkPageListInChunkOrder(true);
621 if (new_space_.CommitFromSpaceIfNeeded()) return;
623 // Committing memory to from space failed again.
624 // Memory is exhausted and we will die.
625 V8::FatalProcessOutOfMemory("Committing semi space failed.");
629 void Heap::ClearJSFunctionResultCaches() {
630 if (isolate_->bootstrapper()->IsActive()) return;
632 Object* context = global_contexts_list_;
633 while (!context->IsUndefined()) {
634 // Get the caches for this context:
636 Context::cast(context)->jsfunction_result_caches();
638 int length = caches->length();
639 for (int i = 0; i < length; i++) {
640 JSFunctionResultCache::cast(caches->get(i))->Clear();
642 // Get the next context:
643 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
649 void Heap::ClearNormalizedMapCaches() {
650 if (isolate_->bootstrapper()->IsActive()) return;
652 Object* context = global_contexts_list_;
653 while (!context->IsUndefined()) {
654 Context::cast(context)->normalized_map_cache()->Clear();
655 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
662 enum PageWatermarkValidity {
667 static void VerifyPageWatermarkValidity(PagedSpace* space,
668 PageWatermarkValidity validity) {
669 PageIterator it(space, PageIterator::PAGES_IN_USE);
670 bool expected_value = (validity == ALL_VALID);
671 while (it.has_next()) {
672 Page* page = it.next();
673 ASSERT(page->IsWatermarkValid() == expected_value);
678 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
679 double survival_rate =
680 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
681 start_new_space_size;
683 if (survival_rate > kYoungSurvivalRateThreshold) {
684 high_survival_rate_period_length_++;
686 high_survival_rate_period_length_ = 0;
689 double survival_rate_diff = survival_rate_ - survival_rate;
691 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
692 set_survival_rate_trend(DECREASING);
693 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
694 set_survival_rate_trend(INCREASING);
696 set_survival_rate_trend(STABLE);
699 survival_rate_ = survival_rate;
702 bool Heap::PerformGarbageCollection(GarbageCollector collector,
704 bool next_gc_likely_to_collect_more = false;
706 if (collector != SCAVENGER) {
707 PROFILE(isolate_, CodeMovingGCEvent());
711 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
712 ASSERT(!allocation_allowed_);
713 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
714 global_gc_prologue_callback_();
718 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
720 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
721 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
722 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
726 EnsureFromSpaceIsCommitted();
728 int start_new_space_size = Heap::new_space()->SizeAsInt();
730 if (collector == MARK_COMPACTOR) {
731 // Perform mark-sweep with optional compaction.
734 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
735 IsStableOrIncreasingSurvivalTrend();
737 UpdateSurvivalRateTrend(start_new_space_size);
739 intptr_t old_gen_size = PromotedSpaceSize();
740 old_gen_promotion_limit_ =
741 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
742 old_gen_allocation_limit_ =
743 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
745 if (high_survival_rate_during_scavenges &&
746 IsStableOrIncreasingSurvivalTrend()) {
747 // Stable high survival rates of young objects both during partial and
748 // full collection indicate that mutator is either building or modifying
749 // a structure with a long lifetime.
750 // In this case we aggressively raise old generation memory limits to
751 // postpone subsequent mark-sweep collection and thus trade memory
752 // space for the mutation speed.
753 old_gen_promotion_limit_ *= 2;
754 old_gen_allocation_limit_ *= 2;
757 old_gen_exhausted_ = false;
763 UpdateSurvivalRateTrend(start_new_space_size);
766 isolate_->counters()->objs_since_last_young()->Set(0);
768 gc_post_processing_depth_++;
769 { DisableAssertNoAllocation allow_allocation;
770 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
771 next_gc_likely_to_collect_more =
772 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
774 gc_post_processing_depth_--;
776 // Update relocatables.
777 Relocatable::PostGarbageCollectionProcessing();
779 if (collector == MARK_COMPACTOR) {
780 // Register the amount of external allocated memory.
781 amount_of_external_allocated_memory_at_last_global_gc_ =
782 amount_of_external_allocated_memory_;
785 GCCallbackFlags callback_flags = tracer->is_compacting()
786 ? kGCCallbackFlagCompacted
787 : kNoGCCallbackFlags;
788 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
789 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
790 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
794 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
795 ASSERT(!allocation_allowed_);
796 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
797 global_gc_epilogue_callback_();
801 return next_gc_likely_to_collect_more;
805 void Heap::MarkCompact(GCTracer* tracer) {
806 gc_state_ = MARK_COMPACT;
807 LOG(isolate_, ResourceEvent("markcompact", "begin"));
809 mark_compact_collector_.Prepare(tracer);
811 bool is_compacting = mark_compact_collector_.IsCompacting();
818 tracer->set_full_gc_count(mc_count_ + ms_count_);
820 MarkCompactPrologue(is_compacting);
822 is_safe_to_read_maps_ = false;
823 mark_compact_collector_.CollectGarbage();
824 is_safe_to_read_maps_ = true;
826 LOG(isolate_, ResourceEvent("markcompact", "end"));
828 gc_state_ = NOT_IN_GC;
832 isolate_->counters()->objs_since_last_full()->Set(0);
834 contexts_disposed_ = 0;
838 void Heap::MarkCompactPrologue(bool is_compacting) {
839 // At any old GC clear the keyed lookup cache to enable collection of unused
841 isolate_->keyed_lookup_cache()->Clear();
842 isolate_->context_slot_cache()->Clear();
843 isolate_->descriptor_lookup_cache()->Clear();
844 StringSplitCache::Clear(string_split_cache());
846 isolate_->compilation_cache()->MarkCompactPrologue();
848 CompletelyClearInstanceofCache();
850 if (is_compacting) FlushNumberStringCache();
851 if (FLAG_cleanup_code_caches_at_gc) {
852 polymorphic_code_cache()->set_cache(undefined_value());
855 ClearNormalizedMapCaches();
859 Object* Heap::FindCodeObject(Address a) {
860 Object* obj = NULL; // Initialization to please compiler.
861 { MaybeObject* maybe_obj = code_space_->FindObject(a);
862 if (!maybe_obj->ToObject(&obj)) {
863 obj = lo_space_->FindObject(a)->ToObjectUnchecked();
870 // Helper class for copying HeapObjects
871 class ScavengeVisitor: public ObjectVisitor {
873 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
875 void VisitPointer(Object** p) { ScavengePointer(p); }
877 void VisitPointers(Object** start, Object** end) {
878 // Copy all HeapObject pointers in [start, end)
879 for (Object** p = start; p < end; p++) ScavengePointer(p);
883 void ScavengePointer(Object** p) {
885 if (!heap_->InNewSpace(object)) return;
886 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
887 reinterpret_cast<HeapObject*>(object));
895 // Visitor class to verify pointers in code or data space do not point into
897 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
899 void VisitPointers(Object** start, Object**end) {
900 for (Object** current = start; current < end; current++) {
901 if ((*current)->IsHeapObject()) {
902 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
909 static void VerifyNonPointerSpacePointers() {
910 // Verify that there are no pointers to new space in spaces where we
911 // do not expect them.
912 VerifyNonPointerSpacePointersVisitor v;
913 HeapObjectIterator code_it(HEAP->code_space());
914 for (HeapObject* object = code_it.next();
915 object != NULL; object = code_it.next())
918 HeapObjectIterator data_it(HEAP->old_data_space());
919 for (HeapObject* object = data_it.next();
920 object != NULL; object = data_it.next())
926 void Heap::CheckNewSpaceExpansionCriteria() {
927 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
928 survived_since_last_expansion_ > new_space_.Capacity()) {
929 // Grow the size of new space if there is room to grow and enough
930 // data has survived scavenge since the last expansion.
932 survived_since_last_expansion_ = 0;
937 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
938 return heap->InNewSpace(*p) &&
939 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
943 void Heap::Scavenge() {
945 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
948 gc_state_ = SCAVENGE;
950 SwitchScavengingVisitorsTableIfProfilingWasEnabled();
952 Page::FlipMeaningOfInvalidatedWatermarkFlag(this);
954 VerifyPageWatermarkValidity(old_pointer_space_, ALL_VALID);
955 VerifyPageWatermarkValidity(map_space_, ALL_VALID);
958 // We do not update an allocation watermark of the top page during linear
959 // allocation to avoid overhead. So to maintain the watermark invariant
960 // we have to manually cache the watermark and mark the top page as having an
961 // invalid watermark. This guarantees that dirty regions iteration will use a
962 // correct watermark even if a linear allocation happens.
963 old_pointer_space_->FlushTopPageWatermark();
964 map_space_->FlushTopPageWatermark();
966 // Implements Cheney's copying algorithm
967 LOG(isolate_, ResourceEvent("scavenge", "begin"));
969 // Clear descriptor cache.
970 isolate_->descriptor_lookup_cache()->Clear();
972 // Used for updating survived_since_last_expansion_ at function end.
973 intptr_t survived_watermark = PromotedSpaceSize();
975 CheckNewSpaceExpansionCriteria();
977 // Flip the semispaces. After flipping, to space is empty, from space has
980 new_space_.ResetAllocationInfo();
982 // We need to sweep newly copied objects which can be either in the
983 // to space or promoted to the old generation. For to-space
984 // objects, we treat the bottom of the to space as a queue. Newly
985 // copied and unswept objects lie between a 'front' mark and the
986 // allocation pointer.
988 // Promoted objects can go into various old-generation spaces, and
989 // can be allocated internally in the spaces (from the free list).
990 // We treat the top of the to space as a queue of addresses of
991 // promoted objects. The addresses of newly promoted and unswept
992 // objects lie between a 'front' mark and a 'rear' mark that is
993 // updated as a side effect of promoting an object.
995 // There is guaranteed to be enough room at the top of the to space
996 // for the addresses of promoted objects: every object promoted
997 // frees up its size in bytes from the top of the new space, and
998 // objects are at least one pointer in size.
999 Address new_space_front = new_space_.ToSpaceLow();
1000 promotion_queue_.Initialize(new_space_.ToSpaceHigh());
1002 is_safe_to_read_maps_ = false;
1003 ScavengeVisitor scavenge_visitor(this);
1005 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1007 // Copy objects reachable from the old generation. By definition,
1008 // there are no intergenerational pointers in code or data spaces.
1009 IterateDirtyRegions(old_pointer_space_,
1010 &Heap::IteratePointersInDirtyRegion,
1012 WATERMARK_CAN_BE_INVALID);
1014 IterateDirtyRegions(map_space_,
1015 &IteratePointersInDirtyMapsRegion,
1017 WATERMARK_CAN_BE_INVALID);
1019 lo_space_->IterateDirtyRegions(&ScavengePointer);
1021 // Copy objects reachable from cells by scavenging cell values directly.
1022 HeapObjectIterator cell_iterator(cell_space_);
1023 for (HeapObject* cell = cell_iterator.next();
1024 cell != NULL; cell = cell_iterator.next()) {
1025 if (cell->IsJSGlobalPropertyCell()) {
1026 Address value_address =
1027 reinterpret_cast<Address>(cell) +
1028 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1029 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1033 // Scavenge object reachable from the global contexts list directly.
1034 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1036 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1037 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1038 &IsUnscavengedHeapObject);
1039 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1041 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1044 UpdateNewSpaceReferencesInExternalStringTable(
1045 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1047 LiveObjectList::UpdateReferencesForScavengeGC();
1048 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1050 ASSERT(new_space_front == new_space_.top());
1052 is_safe_to_read_maps_ = true;
1055 new_space_.set_age_mark(new_space_.top());
1057 // Update how much has survived scavenge.
1058 IncrementYoungSurvivorsCounter(static_cast<int>(
1059 (PromotedSpaceSize() - survived_watermark) + new_space_.Size()));
1061 LOG(isolate_, ResourceEvent("scavenge", "end"));
1063 gc_state_ = NOT_IN_GC;
1067 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1069 MapWord first_word = HeapObject::cast(*p)->map_word();
1071 if (!first_word.IsForwardingAddress()) {
1072 // Unreachable external string can be finalized.
1073 heap->FinalizeExternalString(String::cast(*p));
1077 // String is still reachable.
1078 return String::cast(first_word.ToForwardingAddress());
1082 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1083 ExternalStringTableUpdaterCallback updater_func) {
1084 external_string_table_.Verify();
1086 if (external_string_table_.new_space_strings_.is_empty()) return;
1088 Object** start = &external_string_table_.new_space_strings_[0];
1089 Object** end = start + external_string_table_.new_space_strings_.length();
1090 Object** last = start;
1092 for (Object** p = start; p < end; ++p) {
1093 ASSERT(InFromSpace(*p));
1094 String* target = updater_func(this, p);
1096 if (target == NULL) continue;
1098 ASSERT(target->IsExternalString());
1100 if (InNewSpace(target)) {
1101 // String is still in new space. Update the table entry.
1105 // String got promoted. Move it to the old string list.
1106 external_string_table_.AddOldString(target);
1110 ASSERT(last <= end);
1111 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1115 static Object* ProcessFunctionWeakReferences(Heap* heap,
1117 WeakObjectRetainer* retainer) {
1118 Object* head = heap->undefined_value();
1119 JSFunction* tail = NULL;
1120 Object* candidate = function;
1121 while (candidate != heap->undefined_value()) {
1122 // Check whether to keep the candidate in the list.
1123 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1124 Object* retain = retainer->RetainAs(candidate);
1125 if (retain != NULL) {
1126 if (head == heap->undefined_value()) {
1127 // First element in the list.
1128 head = candidate_function;
1130 // Subsequent elements in the list.
1131 ASSERT(tail != NULL);
1132 tail->set_next_function_link(candidate_function);
1134 // Retained function is new tail.
1135 tail = candidate_function;
1137 // Move to next element in the list.
1138 candidate = candidate_function->next_function_link();
1141 // Terminate the list if there is one or more elements.
1143 tail->set_next_function_link(heap->undefined_value());
1150 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1151 Object* head = undefined_value();
1152 Context* tail = NULL;
1153 Object* candidate = global_contexts_list_;
1154 while (candidate != undefined_value()) {
1155 // Check whether to keep the candidate in the list.
1156 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1157 Object* retain = retainer->RetainAs(candidate);
1158 if (retain != NULL) {
1159 if (head == undefined_value()) {
1160 // First element in the list.
1161 head = candidate_context;
1163 // Subsequent elements in the list.
1164 ASSERT(tail != NULL);
1165 tail->set_unchecked(this,
1166 Context::NEXT_CONTEXT_LINK,
1168 UPDATE_WRITE_BARRIER);
1170 // Retained context is new tail.
1171 tail = candidate_context;
1173 // Process the weak list of optimized functions for the context.
1174 Object* function_list_head =
1175 ProcessFunctionWeakReferences(
1177 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1179 candidate_context->set_unchecked(this,
1180 Context::OPTIMIZED_FUNCTIONS_LIST,
1182 UPDATE_WRITE_BARRIER);
1184 // Move to next element in the list.
1185 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1188 // Terminate the list if there is one or more elements.
1190 tail->set_unchecked(this,
1191 Context::NEXT_CONTEXT_LINK,
1192 Heap::undefined_value(),
1193 UPDATE_WRITE_BARRIER);
1196 // Update the head of the list of contexts.
1197 global_contexts_list_ = head;
1201 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1203 static inline void VisitPointer(Heap* heap, Object** p) {
1204 Object* object = *p;
1205 if (!heap->InNewSpace(object)) return;
1206 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1207 reinterpret_cast<HeapObject*>(object));
1212 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1213 Address new_space_front) {
1215 ASSERT(new_space_front <= new_space_.top());
1217 // The addresses new_space_front and new_space_.top() define a
1218 // queue of unprocessed copied objects. Process them until the
1220 while (new_space_front < new_space_.top()) {
1221 HeapObject* object = HeapObject::FromAddress(new_space_front);
1222 new_space_front += NewSpaceScavenger::IterateBody(object->map(), object);
1225 // Promote and process all the to-be-promoted objects.
1226 while (!promotion_queue_.is_empty()) {
1229 promotion_queue_.remove(&target, &size);
1231 // Promoted object might be already partially visited
1232 // during dirty regions iteration. Thus we search specificly
1233 // for pointers to from semispace instead of looking for pointers
1235 ASSERT(!target->IsMap());
1236 IterateAndMarkPointersToFromSpace(target->address(),
1237 target->address() + size,
1241 // Take another spin if there are now unswept objects in new space
1242 // (there are currently no more unswept promoted objects).
1243 } while (new_space_front < new_space_.top());
1245 return new_space_front;
1249 enum LoggingAndProfiling {
1250 LOGGING_AND_PROFILING_ENABLED,
1251 LOGGING_AND_PROFILING_DISABLED
1255 typedef void (*ScavengingCallback)(Map* map,
1257 HeapObject* object);
1260 static Atomic32 scavenging_visitors_table_mode_;
1261 static VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
1264 INLINE(static void DoScavengeObject(Map* map,
1269 void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1270 scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1274 template<LoggingAndProfiling logging_and_profiling_mode>
1275 class ScavengingVisitor : public StaticVisitorBase {
1277 static void Initialize() {
1278 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1279 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1280 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1281 table_.Register(kVisitByteArray, &EvacuateByteArray);
1282 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1283 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1285 table_.Register(kVisitGlobalContext,
1286 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1287 template VisitSpecialized<Context::kSize>);
1289 table_.Register(kVisitConsString,
1290 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1291 template VisitSpecialized<ConsString::kSize>);
1293 table_.Register(kVisitSlicedString,
1294 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1295 template VisitSpecialized<SlicedString::kSize>);
1297 table_.Register(kVisitSharedFunctionInfo,
1298 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1299 template VisitSpecialized<SharedFunctionInfo::kSize>);
1301 table_.Register(kVisitJSWeakMap,
1302 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1305 table_.Register(kVisitJSRegExp,
1306 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1309 table_.Register(kVisitJSFunction,
1310 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1311 template VisitSpecialized<JSFunction::kSize>);
1313 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1315 kVisitDataObjectGeneric>();
1317 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1319 kVisitJSObjectGeneric>();
1321 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1323 kVisitStructGeneric>();
1326 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1331 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1332 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1334 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1335 bool should_record = false;
1337 should_record = FLAG_heap_stats;
1339 should_record = should_record || FLAG_log_gc;
1340 if (should_record) {
1341 if (heap->new_space()->Contains(obj)) {
1342 heap->new_space()->RecordAllocation(obj);
1344 heap->new_space()->RecordPromotion(obj);
1349 // Helper function used by CopyObject to copy a source object to an
1350 // allocated target object and update the forwarding pointer in the source
1351 // object. Returns the target object.
1352 INLINE(static HeapObject* MigrateObject(Heap* heap,
1356 // Copy the content of source to target.
1357 heap->CopyBlock(target->address(), source->address(), size);
1359 // Set the forwarding address.
1360 source->set_map_word(MapWord::FromForwardingAddress(target));
1362 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1363 // Update NewSpace stats if necessary.
1364 RecordCopiedObject(heap, target);
1365 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1366 Isolate* isolate = heap->isolate();
1367 if (isolate->logger()->is_logging() ||
1368 CpuProfiler::is_profiling(isolate)) {
1369 if (target->IsSharedFunctionInfo()) {
1370 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1371 source->address(), target->address()));
1380 template<ObjectContents object_contents, SizeRestriction size_restriction>
1381 static inline void EvacuateObject(Map* map,
1385 ASSERT((size_restriction != SMALL) ||
1386 (object_size <= Page::kMaxHeapObjectSize));
1387 ASSERT(object->Size() == object_size);
1389 Heap* heap = map->heap();
1390 if (heap->ShouldBePromoted(object->address(), object_size)) {
1391 MaybeObject* maybe_result;
1393 if ((size_restriction != SMALL) &&
1394 (object_size > Page::kMaxHeapObjectSize)) {
1395 maybe_result = heap->lo_space()->AllocateRawFixedArray(object_size);
1397 if (object_contents == DATA_OBJECT) {
1398 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
1400 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
1404 Object* result = NULL; // Initialization to please compiler.
1405 if (maybe_result->ToObject(&result)) {
1406 HeapObject* target = HeapObject::cast(result);
1407 *slot = MigrateObject(heap, object , target, object_size);
1409 if (object_contents == POINTER_OBJECT) {
1410 heap->promotion_queue()->insert(target, object_size);
1413 heap->tracer()->increment_promoted_objects_size(object_size);
1418 heap->new_space()->AllocateRaw(object_size)->ToObjectUnchecked();
1419 *slot = MigrateObject(heap, object, HeapObject::cast(result), object_size);
1424 static inline void EvacuateFixedArray(Map* map,
1426 HeapObject* object) {
1427 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1428 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1435 static inline void EvacuateFixedDoubleArray(Map* map,
1437 HeapObject* object) {
1438 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1439 int object_size = FixedDoubleArray::SizeFor(length);
1440 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1447 static inline void EvacuateByteArray(Map* map,
1449 HeapObject* object) {
1450 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1451 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1455 static inline void EvacuateSeqAsciiString(Map* map,
1457 HeapObject* object) {
1458 int object_size = SeqAsciiString::cast(object)->
1459 SeqAsciiStringSize(map->instance_type());
1460 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1464 static inline void EvacuateSeqTwoByteString(Map* map,
1466 HeapObject* object) {
1467 int object_size = SeqTwoByteString::cast(object)->
1468 SeqTwoByteStringSize(map->instance_type());
1469 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1473 static inline bool IsShortcutCandidate(int type) {
1474 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1477 static inline void EvacuateShortcutCandidate(Map* map,
1479 HeapObject* object) {
1480 ASSERT(IsShortcutCandidate(map->instance_type()));
1482 if (ConsString::cast(object)->unchecked_second() ==
1483 map->heap()->empty_string()) {
1485 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1489 if (!map->heap()->InNewSpace(first)) {
1490 object->set_map_word(MapWord::FromForwardingAddress(first));
1494 MapWord first_word = first->map_word();
1495 if (first_word.IsForwardingAddress()) {
1496 HeapObject* target = first_word.ToForwardingAddress();
1499 object->set_map_word(MapWord::FromForwardingAddress(target));
1503 DoScavengeObject(first->map(), slot, first);
1504 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1508 int object_size = ConsString::kSize;
1509 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
1512 template<ObjectContents object_contents>
1513 class ObjectEvacuationStrategy {
1515 template<int object_size>
1516 static inline void VisitSpecialized(Map* map,
1518 HeapObject* object) {
1519 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1522 static inline void Visit(Map* map,
1524 HeapObject* object) {
1525 int object_size = map->instance_size();
1526 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1530 static VisitorDispatchTable<ScavengingCallback> table_;
1534 template<LoggingAndProfiling logging_and_profiling_mode>
1535 VisitorDispatchTable<ScavengingCallback>
1536 ScavengingVisitor<logging_and_profiling_mode>::table_;
1539 static void InitializeScavengingVisitorsTables() {
1540 ScavengingVisitor<LOGGING_AND_PROFILING_DISABLED>::Initialize();
1541 ScavengingVisitor<LOGGING_AND_PROFILING_ENABLED>::Initialize();
1542 scavenging_visitors_table_.CopyFrom(
1543 ScavengingVisitor<LOGGING_AND_PROFILING_DISABLED>::GetTable());
1544 scavenging_visitors_table_mode_ = LOGGING_AND_PROFILING_DISABLED;
1548 void Heap::SwitchScavengingVisitorsTableIfProfilingWasEnabled() {
1549 if (scavenging_visitors_table_mode_ == LOGGING_AND_PROFILING_ENABLED) {
1550 // Table was already updated by some isolate.
1554 if (isolate()->logger()->is_logging() |
1555 CpuProfiler::is_profiling(isolate()) ||
1556 (isolate()->heap_profiler() != NULL &&
1557 isolate()->heap_profiler()->is_profiling())) {
1558 // If one of the isolates is doing scavenge at this moment of time
1559 // it might see this table in an inconsitent state when
1560 // some of the callbacks point to
1561 // ScavengingVisitor<LOGGING_AND_PROFILING_ENABLED> and others
1562 // to ScavengingVisitor<LOGGING_AND_PROFILING_DISABLED>.
1563 // However this does not lead to any bugs as such isolate does not have
1564 // profiling enabled and any isolate with enabled profiling is guaranteed
1565 // to see the table in the consistent state.
1566 scavenging_visitors_table_.CopyFrom(
1567 ScavengingVisitor<LOGGING_AND_PROFILING_ENABLED>::GetTable());
1569 // We use Release_Store to prevent reordering of this write before writes
1571 Release_Store(&scavenging_visitors_table_mode_,
1572 LOGGING_AND_PROFILING_ENABLED);
1577 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1578 ASSERT(HEAP->InFromSpace(object));
1579 MapWord first_word = object->map_word();
1580 ASSERT(!first_word.IsForwardingAddress());
1581 Map* map = first_word.ToMap();
1582 DoScavengeObject(map, p, object);
1586 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1587 int instance_size) {
1589 { MaybeObject* maybe_result = AllocateRawMap();
1590 if (!maybe_result->ToObject(&result)) return maybe_result;
1593 // Map::cast cannot be used due to uninitialized map field.
1594 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1595 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1596 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1597 reinterpret_cast<Map*>(result)->set_visitor_id(
1598 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1599 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
1600 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
1601 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1602 reinterpret_cast<Map*>(result)->set_bit_field(0);
1603 reinterpret_cast<Map*>(result)->set_bit_field2(0);
1608 MaybeObject* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
1610 { MaybeObject* maybe_result = AllocateRawMap();
1611 if (!maybe_result->ToObject(&result)) return maybe_result;
1614 Map* map = reinterpret_cast<Map*>(result);
1615 map->set_map(meta_map());
1616 map->set_instance_type(instance_type);
1617 map->set_visitor_id(
1618 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1619 map->set_prototype(null_value());
1620 map->set_constructor(null_value());
1621 map->set_instance_size(instance_size);
1622 map->set_inobject_properties(0);
1623 map->set_pre_allocated_property_fields(0);
1624 map->init_instance_descriptors();
1625 map->set_code_cache(empty_fixed_array());
1626 map->set_prototype_transitions(empty_fixed_array());
1627 map->set_unused_property_fields(0);
1628 map->set_bit_field(0);
1629 map->set_bit_field2(1 << Map::kIsExtensible);
1630 map->set_elements_kind(FAST_ELEMENTS);
1632 // If the map object is aligned fill the padding area with Smi 0 objects.
1633 if (Map::kPadStart < Map::kSize) {
1634 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1636 Map::kSize - Map::kPadStart);
1642 MaybeObject* Heap::AllocateCodeCache() {
1644 { MaybeObject* maybe_result = AllocateStruct(CODE_CACHE_TYPE);
1645 if (!maybe_result->ToObject(&result)) return maybe_result;
1647 CodeCache* code_cache = CodeCache::cast(result);
1648 code_cache->set_default_cache(empty_fixed_array());
1649 code_cache->set_normal_type_cache(undefined_value());
1654 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1655 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1659 const Heap::StringTypeTable Heap::string_type_table[] = {
1660 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1661 {type, size, k##camel_name##MapRootIndex},
1662 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1663 #undef STRING_TYPE_ELEMENT
1667 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1668 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1669 {contents, k##name##RootIndex},
1670 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1671 #undef CONSTANT_SYMBOL_ELEMENT
1675 const Heap::StructTable Heap::struct_table[] = {
1676 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1677 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1678 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1679 #undef STRUCT_TABLE_ELEMENT
1683 bool Heap::CreateInitialMaps() {
1685 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1686 if (!maybe_obj->ToObject(&obj)) return false;
1688 // Map::cast cannot be used due to uninitialized map field.
1689 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1690 set_meta_map(new_meta_map);
1691 new_meta_map->set_map(new_meta_map);
1693 { MaybeObject* maybe_obj =
1694 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1695 if (!maybe_obj->ToObject(&obj)) return false;
1697 set_fixed_array_map(Map::cast(obj));
1699 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1700 if (!maybe_obj->ToObject(&obj)) return false;
1702 set_oddball_map(Map::cast(obj));
1704 // Allocate the empty array.
1705 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1706 if (!maybe_obj->ToObject(&obj)) return false;
1708 set_empty_fixed_array(FixedArray::cast(obj));
1710 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1711 if (!maybe_obj->ToObject(&obj)) return false;
1713 set_null_value(obj);
1714 Oddball::cast(obj)->set_kind(Oddball::kNull);
1716 // Allocate the empty descriptor array.
1717 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1718 if (!maybe_obj->ToObject(&obj)) return false;
1720 set_empty_descriptor_array(DescriptorArray::cast(obj));
1722 // Fix the instance_descriptors for the existing maps.
1723 meta_map()->init_instance_descriptors();
1724 meta_map()->set_code_cache(empty_fixed_array());
1725 meta_map()->set_prototype_transitions(empty_fixed_array());
1727 fixed_array_map()->init_instance_descriptors();
1728 fixed_array_map()->set_code_cache(empty_fixed_array());
1729 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
1731 oddball_map()->init_instance_descriptors();
1732 oddball_map()->set_code_cache(empty_fixed_array());
1733 oddball_map()->set_prototype_transitions(empty_fixed_array());
1735 // Fix prototype object for existing maps.
1736 meta_map()->set_prototype(null_value());
1737 meta_map()->set_constructor(null_value());
1739 fixed_array_map()->set_prototype(null_value());
1740 fixed_array_map()->set_constructor(null_value());
1742 oddball_map()->set_prototype(null_value());
1743 oddball_map()->set_constructor(null_value());
1745 { MaybeObject* maybe_obj =
1746 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1747 if (!maybe_obj->ToObject(&obj)) return false;
1749 set_fixed_cow_array_map(Map::cast(obj));
1750 ASSERT(fixed_array_map() != fixed_cow_array_map());
1752 { MaybeObject* maybe_obj =
1753 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1754 if (!maybe_obj->ToObject(&obj)) return false;
1756 set_serialized_scope_info_map(Map::cast(obj));
1758 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1759 if (!maybe_obj->ToObject(&obj)) return false;
1761 set_heap_number_map(Map::cast(obj));
1763 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
1764 if (!maybe_obj->ToObject(&obj)) return false;
1766 set_foreign_map(Map::cast(obj));
1768 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1769 const StringTypeTable& entry = string_type_table[i];
1770 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
1771 if (!maybe_obj->ToObject(&obj)) return false;
1773 roots_[entry.index] = Map::cast(obj);
1776 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
1777 if (!maybe_obj->ToObject(&obj)) return false;
1779 set_undetectable_string_map(Map::cast(obj));
1780 Map::cast(obj)->set_is_undetectable();
1782 { MaybeObject* maybe_obj =
1783 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
1784 if (!maybe_obj->ToObject(&obj)) return false;
1786 set_undetectable_ascii_string_map(Map::cast(obj));
1787 Map::cast(obj)->set_is_undetectable();
1789 { MaybeObject* maybe_obj =
1790 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
1791 if (!maybe_obj->ToObject(&obj)) return false;
1793 set_fixed_double_array_map(Map::cast(obj));
1795 { MaybeObject* maybe_obj =
1796 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
1797 if (!maybe_obj->ToObject(&obj)) return false;
1799 set_byte_array_map(Map::cast(obj));
1801 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
1802 if (!maybe_obj->ToObject(&obj)) return false;
1804 set_empty_byte_array(ByteArray::cast(obj));
1806 { MaybeObject* maybe_obj =
1807 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
1808 if (!maybe_obj->ToObject(&obj)) return false;
1810 set_external_pixel_array_map(Map::cast(obj));
1812 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1813 ExternalArray::kAlignedSize);
1814 if (!maybe_obj->ToObject(&obj)) return false;
1816 set_external_byte_array_map(Map::cast(obj));
1818 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1819 ExternalArray::kAlignedSize);
1820 if (!maybe_obj->ToObject(&obj)) return false;
1822 set_external_unsigned_byte_array_map(Map::cast(obj));
1824 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1825 ExternalArray::kAlignedSize);
1826 if (!maybe_obj->ToObject(&obj)) return false;
1828 set_external_short_array_map(Map::cast(obj));
1830 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1831 ExternalArray::kAlignedSize);
1832 if (!maybe_obj->ToObject(&obj)) return false;
1834 set_external_unsigned_short_array_map(Map::cast(obj));
1836 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1837 ExternalArray::kAlignedSize);
1838 if (!maybe_obj->ToObject(&obj)) return false;
1840 set_external_int_array_map(Map::cast(obj));
1842 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1843 ExternalArray::kAlignedSize);
1844 if (!maybe_obj->ToObject(&obj)) return false;
1846 set_external_unsigned_int_array_map(Map::cast(obj));
1848 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1849 ExternalArray::kAlignedSize);
1850 if (!maybe_obj->ToObject(&obj)) return false;
1852 set_external_float_array_map(Map::cast(obj));
1854 { MaybeObject* maybe_obj =
1855 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1856 if (!maybe_obj->ToObject(&obj)) return false;
1858 set_non_strict_arguments_elements_map(Map::cast(obj));
1860 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
1861 ExternalArray::kAlignedSize);
1862 if (!maybe_obj->ToObject(&obj)) return false;
1864 set_external_double_array_map(Map::cast(obj));
1866 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
1867 if (!maybe_obj->ToObject(&obj)) return false;
1869 set_code_map(Map::cast(obj));
1871 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1872 JSGlobalPropertyCell::kSize);
1873 if (!maybe_obj->ToObject(&obj)) return false;
1875 set_global_property_cell_map(Map::cast(obj));
1877 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
1878 if (!maybe_obj->ToObject(&obj)) return false;
1880 set_one_pointer_filler_map(Map::cast(obj));
1882 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1883 if (!maybe_obj->ToObject(&obj)) return false;
1885 set_two_pointer_filler_map(Map::cast(obj));
1887 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1888 const StructTable& entry = struct_table[i];
1889 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
1890 if (!maybe_obj->ToObject(&obj)) return false;
1892 roots_[entry.index] = Map::cast(obj);
1895 { MaybeObject* maybe_obj =
1896 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1897 if (!maybe_obj->ToObject(&obj)) return false;
1899 set_hash_table_map(Map::cast(obj));
1901 { MaybeObject* maybe_obj =
1902 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1903 if (!maybe_obj->ToObject(&obj)) return false;
1905 set_function_context_map(Map::cast(obj));
1907 { MaybeObject* maybe_obj =
1908 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1909 if (!maybe_obj->ToObject(&obj)) return false;
1911 set_catch_context_map(Map::cast(obj));
1913 { MaybeObject* maybe_obj =
1914 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1915 if (!maybe_obj->ToObject(&obj)) return false;
1917 set_with_context_map(Map::cast(obj));
1919 { MaybeObject* maybe_obj =
1920 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1921 if (!maybe_obj->ToObject(&obj)) return false;
1923 set_block_context_map(Map::cast(obj));
1925 { MaybeObject* maybe_obj =
1926 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1927 if (!maybe_obj->ToObject(&obj)) return false;
1929 Map* global_context_map = Map::cast(obj);
1930 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
1931 set_global_context_map(global_context_map);
1933 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
1934 SharedFunctionInfo::kAlignedSize);
1935 if (!maybe_obj->ToObject(&obj)) return false;
1937 set_shared_function_info_map(Map::cast(obj));
1939 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
1940 JSMessageObject::kSize);
1941 if (!maybe_obj->ToObject(&obj)) return false;
1943 set_message_object_map(Map::cast(obj));
1945 ASSERT(!InNewSpace(empty_fixed_array()));
1950 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1951 // Statically ensure that it is safe to allocate heap numbers in paged
1953 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1954 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1957 { MaybeObject* maybe_result =
1958 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
1959 if (!maybe_result->ToObject(&result)) return maybe_result;
1962 HeapObject::cast(result)->set_map(heap_number_map());
1963 HeapNumber::cast(result)->set_value(value);
1968 MaybeObject* Heap::AllocateHeapNumber(double value) {
1969 // Use general version, if we're forced to always allocate.
1970 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1972 // This version of AllocateHeapNumber is optimized for
1973 // allocation in new space.
1974 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1975 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1977 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
1978 if (!maybe_result->ToObject(&result)) return maybe_result;
1980 HeapObject::cast(result)->set_map(heap_number_map());
1981 HeapNumber::cast(result)->set_value(value);
1986 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
1988 { MaybeObject* maybe_result = AllocateRawCell();
1989 if (!maybe_result->ToObject(&result)) return maybe_result;
1991 HeapObject::cast(result)->set_map(global_property_cell_map());
1992 JSGlobalPropertyCell::cast(result)->set_value(value);
1997 MaybeObject* Heap::CreateOddball(const char* to_string,
2001 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_DATA_SPACE);
2002 if (!maybe_result->ToObject(&result)) return maybe_result;
2004 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2008 bool Heap::CreateApiObjects() {
2011 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2012 if (!maybe_obj->ToObject(&obj)) return false;
2014 set_neander_map(Map::cast(obj));
2016 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2017 if (!maybe_obj->ToObject(&obj)) return false;
2020 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2021 if (!maybe_elements->ToObject(&elements)) return false;
2023 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2024 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2025 set_message_listeners(JSObject::cast(obj));
2031 void Heap::CreateJSEntryStub() {
2033 set_js_entry_code(*stub.GetCode());
2037 void Heap::CreateJSConstructEntryStub() {
2038 JSConstructEntryStub stub;
2039 set_js_construct_entry_code(*stub.GetCode());
2043 void Heap::CreateFixedStubs() {
2044 // Here we create roots for fixed stubs. They are needed at GC
2045 // for cooking and uncooking (check out frames.cc).
2046 // The eliminates the need for doing dictionary lookup in the
2047 // stub cache for these stubs.
2049 // gcc-4.4 has problem generating correct code of following snippet:
2050 // { JSEntryStub stub;
2051 // js_entry_code_ = *stub.GetCode();
2053 // { JSConstructEntryStub stub;
2054 // js_construct_entry_code_ = *stub.GetCode();
2056 // To workaround the problem, make separate functions without inlining.
2057 Heap::CreateJSEntryStub();
2058 Heap::CreateJSConstructEntryStub();
2062 bool Heap::CreateInitialObjects() {
2065 // The -0 value must be set before NumberFromDouble works.
2066 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2067 if (!maybe_obj->ToObject(&obj)) return false;
2069 set_minus_zero_value(obj);
2070 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2072 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2073 if (!maybe_obj->ToObject(&obj)) return false;
2077 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_DATA_SPACE);
2078 if (!maybe_obj->ToObject(&obj)) return false;
2080 set_undefined_value(obj);
2081 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2082 ASSERT(!InNewSpace(undefined_value()));
2084 // Allocate initial symbol table.
2085 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2086 if (!maybe_obj->ToObject(&obj)) return false;
2088 // Don't use set_symbol_table() due to asserts.
2089 roots_[kSymbolTableRootIndex] = obj;
2091 // Assign the print strings for oddballs after creating symboltable.
2093 { MaybeObject* maybe_symbol = LookupAsciiSymbol("undefined");
2094 if (!maybe_symbol->ToObject(&symbol)) return false;
2096 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
2097 Oddball::cast(undefined_value())->set_to_number(nan_value());
2099 // Allocate the null_value
2100 { MaybeObject* maybe_obj =
2101 Oddball::cast(null_value())->Initialize("null",
2104 if (!maybe_obj->ToObject(&obj)) return false;
2107 { MaybeObject* maybe_obj = CreateOddball("true",
2110 if (!maybe_obj->ToObject(&obj)) return false;
2112 set_true_value(obj);
2114 { MaybeObject* maybe_obj = CreateOddball("false",
2117 if (!maybe_obj->ToObject(&obj)) return false;
2119 set_false_value(obj);
2121 { MaybeObject* maybe_obj = CreateOddball("hole",
2124 if (!maybe_obj->ToObject(&obj)) return false;
2126 set_the_hole_value(obj);
2128 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2130 Oddball::kArgumentMarker);
2131 if (!maybe_obj->ToObject(&obj)) return false;
2133 set_arguments_marker(obj);
2135 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2138 if (!maybe_obj->ToObject(&obj)) return false;
2140 set_no_interceptor_result_sentinel(obj);
2142 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2145 if (!maybe_obj->ToObject(&obj)) return false;
2147 set_termination_exception(obj);
2149 // Allocate the empty string.
2150 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2151 if (!maybe_obj->ToObject(&obj)) return false;
2153 set_empty_string(String::cast(obj));
2155 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2156 { MaybeObject* maybe_obj =
2157 LookupAsciiSymbol(constant_symbol_table[i].contents);
2158 if (!maybe_obj->ToObject(&obj)) return false;
2160 roots_[constant_symbol_table[i].index] = String::cast(obj);
2163 // Allocate the hidden symbol which is used to identify the hidden properties
2164 // in JSObjects. The hash code has a special value so that it will not match
2165 // the empty string when searching for the property. It cannot be part of the
2166 // loop above because it needs to be allocated manually with the special
2167 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2168 // that it will always be at the first entry in property descriptors.
2169 { MaybeObject* maybe_obj =
2170 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2171 if (!maybe_obj->ToObject(&obj)) return false;
2173 hidden_symbol_ = String::cast(obj);
2175 // Allocate the foreign for __proto__.
2176 { MaybeObject* maybe_obj =
2177 AllocateForeign((Address) &Accessors::ObjectPrototype);
2178 if (!maybe_obj->ToObject(&obj)) return false;
2180 set_prototype_accessors(Foreign::cast(obj));
2182 // Allocate the code_stubs dictionary. The initial size is set to avoid
2183 // expanding the dictionary during bootstrapping.
2184 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2185 if (!maybe_obj->ToObject(&obj)) return false;
2187 set_code_stubs(UnseededNumberDictionary::cast(obj));
2189 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2190 // is set to avoid expanding the dictionary during bootstrapping.
2191 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2192 if (!maybe_obj->ToObject(&obj)) return false;
2194 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2196 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2197 if (!maybe_obj->ToObject(&obj)) return false;
2199 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2201 set_instanceof_cache_function(Smi::FromInt(0));
2202 set_instanceof_cache_map(Smi::FromInt(0));
2203 set_instanceof_cache_answer(Smi::FromInt(0));
2207 // Allocate the dictionary of intrinsic function names.
2208 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2209 if (!maybe_obj->ToObject(&obj)) return false;
2211 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2213 if (!maybe_obj->ToObject(&obj)) return false;
2215 set_intrinsic_function_names(StringDictionary::cast(obj));
2217 if (InitializeNumberStringCache()->IsFailure()) return false;
2219 // Allocate cache for single character ASCII strings.
2220 { MaybeObject* maybe_obj =
2221 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2222 if (!maybe_obj->ToObject(&obj)) return false;
2224 set_single_character_string_cache(FixedArray::cast(obj));
2226 // Allocate cache for string split.
2227 { MaybeObject* maybe_obj =
2228 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2229 if (!maybe_obj->ToObject(&obj)) return false;
2231 set_string_split_cache(FixedArray::cast(obj));
2233 // Allocate cache for external strings pointing to native source code.
2234 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2235 if (!maybe_obj->ToObject(&obj)) return false;
2237 set_natives_source_cache(FixedArray::cast(obj));
2239 // Handling of script id generation is in FACTORY->NewScript.
2240 set_last_script_id(undefined_value());
2242 // Initialize keyed lookup cache.
2243 isolate_->keyed_lookup_cache()->Clear();
2245 // Initialize context slot cache.
2246 isolate_->context_slot_cache()->Clear();
2248 // Initialize descriptor cache.
2249 isolate_->descriptor_lookup_cache()->Clear();
2251 // Initialize compilation cache.
2252 isolate_->compilation_cache()->Clear();
2258 Object* StringSplitCache::Lookup(
2259 FixedArray* cache, String* string, String* pattern) {
2260 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2261 uint32_t hash = string->Hash();
2262 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2263 ~(kArrayEntriesPerCacheEntry - 1));
2264 if (cache->get(index + kStringOffset) == string &&
2265 cache->get(index + kPatternOffset) == pattern) {
2266 return cache->get(index + kArrayOffset);
2268 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2269 if (cache->get(index + kStringOffset) == string &&
2270 cache->get(index + kPatternOffset) == pattern) {
2271 return cache->get(index + kArrayOffset);
2273 return Smi::FromInt(0);
2277 void StringSplitCache::Enter(Heap* heap,
2281 FixedArray* array) {
2282 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2283 uint32_t hash = string->Hash();
2284 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2285 ~(kArrayEntriesPerCacheEntry - 1));
2286 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2287 cache->set(index + kStringOffset, string);
2288 cache->set(index + kPatternOffset, pattern);
2289 cache->set(index + kArrayOffset, array);
2292 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2293 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2294 cache->set(index2 + kStringOffset, string);
2295 cache->set(index2 + kPatternOffset, pattern);
2296 cache->set(index2 + kArrayOffset, array);
2298 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2299 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2300 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2301 cache->set(index + kStringOffset, string);
2302 cache->set(index + kPatternOffset, pattern);
2303 cache->set(index + kArrayOffset, array);
2306 if (array->length() < 100) { // Limit how many new symbols we want to make.
2307 for (int i = 0; i < array->length(); i++) {
2308 String* str = String::cast(array->get(i));
2310 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2311 if (maybe_symbol->ToObject(&symbol)) {
2312 array->set(i, symbol);
2316 array->set_map(heap->fixed_cow_array_map());
2320 void StringSplitCache::Clear(FixedArray* cache) {
2321 for (int i = 0; i < kStringSplitCacheSize; i++) {
2322 cache->set(i, Smi::FromInt(0));
2327 MaybeObject* Heap::InitializeNumberStringCache() {
2328 // Compute the size of the number string cache based on the max heap size.
2329 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
2330 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
2331 int number_string_cache_size = max_semispace_size_ / 512;
2332 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
2334 MaybeObject* maybe_obj =
2335 AllocateFixedArray(number_string_cache_size * 2, TENURED);
2336 if (maybe_obj->ToObject(&obj)) set_number_string_cache(FixedArray::cast(obj));
2341 void Heap::FlushNumberStringCache() {
2342 // Flush the number to string cache.
2343 int len = number_string_cache()->length();
2344 for (int i = 0; i < len; i++) {
2345 number_string_cache()->set_undefined(this, i);
2350 static inline int double_get_hash(double d) {
2351 DoubleRepresentation rep(d);
2352 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2356 static inline int smi_get_hash(Smi* smi) {
2357 return smi->value();
2361 Object* Heap::GetNumberStringCache(Object* number) {
2363 int mask = (number_string_cache()->length() >> 1) - 1;
2364 if (number->IsSmi()) {
2365 hash = smi_get_hash(Smi::cast(number)) & mask;
2367 hash = double_get_hash(number->Number()) & mask;
2369 Object* key = number_string_cache()->get(hash * 2);
2370 if (key == number) {
2371 return String::cast(number_string_cache()->get(hash * 2 + 1));
2372 } else if (key->IsHeapNumber() &&
2373 number->IsHeapNumber() &&
2374 key->Number() == number->Number()) {
2375 return String::cast(number_string_cache()->get(hash * 2 + 1));
2377 return undefined_value();
2381 void Heap::SetNumberStringCache(Object* number, String* string) {
2383 int mask = (number_string_cache()->length() >> 1) - 1;
2384 if (number->IsSmi()) {
2385 hash = smi_get_hash(Smi::cast(number)) & mask;
2386 number_string_cache()->set(hash * 2, Smi::cast(number));
2388 hash = double_get_hash(number->Number()) & mask;
2389 number_string_cache()->set(hash * 2, number);
2391 number_string_cache()->set(hash * 2 + 1, string);
2395 MaybeObject* Heap::NumberToString(Object* number,
2396 bool check_number_string_cache) {
2397 isolate_->counters()->number_to_string_runtime()->Increment();
2398 if (check_number_string_cache) {
2399 Object* cached = GetNumberStringCache(number);
2400 if (cached != undefined_value()) {
2406 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2408 if (number->IsSmi()) {
2409 int num = Smi::cast(number)->value();
2410 str = IntToCString(num, buffer);
2412 double num = HeapNumber::cast(number)->value();
2413 str = DoubleToCString(num, buffer);
2417 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2418 if (maybe_js_string->ToObject(&js_string)) {
2419 SetNumberStringCache(number, String::cast(js_string));
2421 return maybe_js_string;
2425 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2426 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2430 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2431 ExternalArrayType array_type) {
2432 switch (array_type) {
2433 case kExternalByteArray:
2434 return kExternalByteArrayMapRootIndex;
2435 case kExternalUnsignedByteArray:
2436 return kExternalUnsignedByteArrayMapRootIndex;
2437 case kExternalShortArray:
2438 return kExternalShortArrayMapRootIndex;
2439 case kExternalUnsignedShortArray:
2440 return kExternalUnsignedShortArrayMapRootIndex;
2441 case kExternalIntArray:
2442 return kExternalIntArrayMapRootIndex;
2443 case kExternalUnsignedIntArray:
2444 return kExternalUnsignedIntArrayMapRootIndex;
2445 case kExternalFloatArray:
2446 return kExternalFloatArrayMapRootIndex;
2447 case kExternalDoubleArray:
2448 return kExternalDoubleArrayMapRootIndex;
2449 case kExternalPixelArray:
2450 return kExternalPixelArrayMapRootIndex;
2453 return kUndefinedValueRootIndex;
2458 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2459 // We need to distinguish the minus zero value and this cannot be
2460 // done after conversion to int. Doing this by comparing bit
2461 // patterns is faster than using fpclassify() et al.
2462 static const DoubleRepresentation minus_zero(-0.0);
2464 DoubleRepresentation rep(value);
2465 if (rep.bits == minus_zero.bits) {
2466 return AllocateHeapNumber(-0.0, pretenure);
2469 int int_value = FastD2I(value);
2470 if (value == int_value && Smi::IsValid(int_value)) {
2471 return Smi::FromInt(int_value);
2474 // Materialize the value in the heap.
2475 return AllocateHeapNumber(value, pretenure);
2479 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2480 // Statically ensure that it is safe to allocate foreigns in paged spaces.
2481 STATIC_ASSERT(Foreign::kSize <= Page::kMaxHeapObjectSize);
2482 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2484 { MaybeObject* maybe_result = Allocate(foreign_map(), space);
2485 if (!maybe_result->ToObject(&result)) return maybe_result;
2488 Foreign::cast(result)->set_address(address);
2493 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
2494 SharedFunctionInfo* share;
2495 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2496 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
2498 // Set pointer fields.
2499 share->set_name(name);
2500 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
2501 share->set_code(illegal);
2502 share->set_scope_info(SerializedScopeInfo::Empty());
2503 Code* construct_stub =
2504 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2505 share->set_construct_stub(construct_stub);
2506 share->set_instance_class_name(Object_symbol());
2507 share->set_function_data(undefined_value());
2508 share->set_script(undefined_value());
2509 share->set_debug_info(undefined_value());
2510 share->set_inferred_name(empty_string());
2511 share->set_initial_map(undefined_value());
2512 share->set_this_property_assignments(undefined_value());
2513 share->set_deopt_counter(Smi::FromInt(FLAG_deopt_every_n_times));
2515 // Set integer fields (smi or int, depending on the architecture).
2516 share->set_length(0);
2517 share->set_formal_parameter_count(0);
2518 share->set_expected_nof_properties(0);
2519 share->set_num_literals(0);
2520 share->set_start_position_and_type(0);
2521 share->set_end_position(0);
2522 share->set_function_token_position(0);
2523 // All compiler hints default to false or 0.
2524 share->set_compiler_hints(0);
2525 share->set_this_property_assignments_count(0);
2526 share->set_opt_count(0);
2532 MaybeObject* Heap::AllocateJSMessageObject(String* type,
2537 Object* stack_trace,
2538 Object* stack_frames) {
2540 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2541 if (!maybe_result->ToObject(&result)) return maybe_result;
2543 JSMessageObject* message = JSMessageObject::cast(result);
2544 message->set_properties(Heap::empty_fixed_array());
2545 message->set_elements(Heap::empty_fixed_array());
2546 message->set_type(type);
2547 message->set_arguments(arguments);
2548 message->set_start_position(start_position);
2549 message->set_end_position(end_position);
2550 message->set_script(script);
2551 message->set_stack_trace(stack_trace);
2552 message->set_stack_frames(stack_frames);
2558 // Returns true for a character in a range. Both limits are inclusive.
2559 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2560 // This makes uses of the the unsigned wraparound.
2561 return character - from <= to - from;
2565 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
2570 // Numeric strings have a different hash algorithm not known by
2571 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2572 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
2573 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
2575 // Now we know the length is 2, we might as well make use of that fact
2576 // when building the new string.
2577 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2578 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
2580 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
2581 if (!maybe_result->ToObject(&result)) return maybe_result;
2583 char* dest = SeqAsciiString::cast(result)->GetChars();
2589 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
2590 if (!maybe_result->ToObject(&result)) return maybe_result;
2592 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2600 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
2601 int first_length = first->length();
2602 if (first_length == 0) {
2606 int second_length = second->length();
2607 if (second_length == 0) {
2611 int length = first_length + second_length;
2613 // Optimization for 2-byte strings often used as keys in a decompression
2614 // dictionary. Check whether we already have the string in the symbol
2615 // table to prevent creation of many unneccesary strings.
2617 unsigned c1 = first->Get(0);
2618 unsigned c2 = second->Get(0);
2619 return MakeOrFindTwoCharacterString(this, c1, c2);
2622 bool first_is_ascii = first->IsAsciiRepresentation();
2623 bool second_is_ascii = second->IsAsciiRepresentation();
2624 bool is_ascii = first_is_ascii && second_is_ascii;
2626 // Make sure that an out of memory exception is thrown if the length
2627 // of the new cons string is too large.
2628 if (length > String::kMaxLength || length < 0) {
2629 isolate()->context()->mark_out_of_memory();
2630 return Failure::OutOfMemoryException();
2633 bool is_ascii_data_in_two_byte_string = false;
2635 // At least one of the strings uses two-byte representation so we
2636 // can't use the fast case code for short ascii strings below, but
2637 // we can try to save memory if all chars actually fit in ascii.
2638 is_ascii_data_in_two_byte_string =
2639 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
2640 if (is_ascii_data_in_two_byte_string) {
2641 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
2645 // If the resulting string is small make a flat string.
2646 if (length < String::kMinNonFlatLength) {
2647 // Note that neither of the two inputs can be a slice because:
2648 STATIC_ASSERT(String::kMinNonFlatLength <= SlicedString::kMinLength);
2649 ASSERT(first->IsFlat());
2650 ASSERT(second->IsFlat());
2653 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2654 if (!maybe_result->ToObject(&result)) return maybe_result;
2656 // Copy the characters into the new object.
2657 char* dest = SeqAsciiString::cast(result)->GetChars();
2660 if (first->IsExternalString()) {
2661 src = ExternalAsciiString::cast(first)->resource()->data();
2663 src = SeqAsciiString::cast(first)->GetChars();
2665 for (int i = 0; i < first_length; i++) *dest++ = src[i];
2666 // Copy second part.
2667 if (second->IsExternalString()) {
2668 src = ExternalAsciiString::cast(second)->resource()->data();
2670 src = SeqAsciiString::cast(second)->GetChars();
2672 for (int i = 0; i < second_length; i++) *dest++ = src[i];
2675 if (is_ascii_data_in_two_byte_string) {
2677 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2678 if (!maybe_result->ToObject(&result)) return maybe_result;
2680 // Copy the characters into the new object.
2681 char* dest = SeqAsciiString::cast(result)->GetChars();
2682 String::WriteToFlat(first, dest, 0, first_length);
2683 String::WriteToFlat(second, dest + first_length, 0, second_length);
2684 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
2689 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
2690 if (!maybe_result->ToObject(&result)) return maybe_result;
2692 // Copy the characters into the new object.
2693 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2694 String::WriteToFlat(first, dest, 0, first_length);
2695 String::WriteToFlat(second, dest + first_length, 0, second_length);
2700 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
2701 cons_ascii_string_map() : cons_string_map();
2704 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2705 if (!maybe_result->ToObject(&result)) return maybe_result;
2708 AssertNoAllocation no_gc;
2709 ConsString* cons_string = ConsString::cast(result);
2710 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
2711 cons_string->set_length(length);
2712 cons_string->set_hash_field(String::kEmptyHashField);
2713 cons_string->set_first(first, mode);
2714 cons_string->set_second(second, mode);
2719 MaybeObject* Heap::AllocateSubString(String* buffer,
2722 PretenureFlag pretenure) {
2723 int length = end - start;
2725 return empty_string();
2726 } else if (length == 1) {
2727 return LookupSingleCharacterStringFromCode(buffer->Get(start));
2728 } else if (length == 2) {
2729 // Optimization for 2-byte strings often used as keys in a decompression
2730 // dictionary. Check whether we already have the string in the symbol
2731 // table to prevent creation of many unneccesary strings.
2732 unsigned c1 = buffer->Get(start);
2733 unsigned c2 = buffer->Get(start + 1);
2734 return MakeOrFindTwoCharacterString(this, c1, c2);
2737 // Make an attempt to flatten the buffer to reduce access time.
2738 buffer = buffer->TryFlattenGetString();
2740 // TODO(1626): For now slicing external strings is not supported. However,
2741 // a flat cons string can have an external string as first part in some cases.
2742 // Therefore we have to single out this case as well.
2743 if (!FLAG_string_slices ||
2744 (buffer->IsConsString() &&
2745 (!buffer->IsFlat() ||
2746 !ConsString::cast(buffer)->first()->IsSeqString())) ||
2747 buffer->IsExternalString() ||
2748 length < SlicedString::kMinLength ||
2749 pretenure == TENURED) {
2751 { MaybeObject* maybe_result = buffer->IsAsciiRepresentation()
2752 ? AllocateRawAsciiString(length, pretenure)
2753 : AllocateRawTwoByteString(length, pretenure);
2754 if (!maybe_result->ToObject(&result)) return maybe_result;
2756 String* string_result = String::cast(result);
2757 // Copy the characters into the new object.
2758 if (buffer->IsAsciiRepresentation()) {
2759 ASSERT(string_result->IsAsciiRepresentation());
2760 char* dest = SeqAsciiString::cast(string_result)->GetChars();
2761 String::WriteToFlat(buffer, dest, start, end);
2763 ASSERT(string_result->IsTwoByteRepresentation());
2764 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
2765 String::WriteToFlat(buffer, dest, start, end);
2770 ASSERT(buffer->IsFlat());
2771 ASSERT(!buffer->IsExternalString());
2773 buffer->StringVerify();
2777 { Map* map = buffer->IsAsciiRepresentation()
2778 ? sliced_ascii_string_map()
2779 : sliced_string_map();
2780 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2781 if (!maybe_result->ToObject(&result)) return maybe_result;
2784 AssertNoAllocation no_gc;
2785 SlicedString* sliced_string = SlicedString::cast(result);
2786 sliced_string->set_length(length);
2787 sliced_string->set_hash_field(String::kEmptyHashField);
2788 if (buffer->IsConsString()) {
2789 ConsString* cons = ConsString::cast(buffer);
2790 ASSERT(cons->second()->length() == 0);
2791 sliced_string->set_parent(cons->first());
2792 sliced_string->set_offset(start);
2793 } else if (buffer->IsSlicedString()) {
2794 // Prevent nesting sliced strings.
2795 SlicedString* parent_slice = SlicedString::cast(buffer);
2796 sliced_string->set_parent(parent_slice->parent());
2797 sliced_string->set_offset(start + parent_slice->offset());
2799 sliced_string->set_parent(buffer);
2800 sliced_string->set_offset(start);
2802 ASSERT(sliced_string->parent()->IsSeqString());
2807 MaybeObject* Heap::AllocateExternalStringFromAscii(
2808 ExternalAsciiString::Resource* resource) {
2809 size_t length = resource->length();
2810 if (length > static_cast<size_t>(String::kMaxLength)) {
2811 isolate()->context()->mark_out_of_memory();
2812 return Failure::OutOfMemoryException();
2815 Map* map = external_ascii_string_map();
2817 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2818 if (!maybe_result->ToObject(&result)) return maybe_result;
2821 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
2822 external_string->set_length(static_cast<int>(length));
2823 external_string->set_hash_field(String::kEmptyHashField);
2824 external_string->set_resource(resource);
2830 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
2831 ExternalTwoByteString::Resource* resource) {
2832 size_t length = resource->length();
2833 if (length > static_cast<size_t>(String::kMaxLength)) {
2834 isolate()->context()->mark_out_of_memory();
2835 return Failure::OutOfMemoryException();
2838 // For small strings we check whether the resource contains only
2839 // ASCII characters. If yes, we use a different string map.
2840 static const size_t kAsciiCheckLengthLimit = 32;
2841 bool is_ascii = length <= kAsciiCheckLengthLimit &&
2842 String::IsAscii(resource->data(), static_cast<int>(length));
2843 Map* map = is_ascii ?
2844 external_string_with_ascii_data_map() : external_string_map();
2846 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2847 if (!maybe_result->ToObject(&result)) return maybe_result;
2850 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
2851 external_string->set_length(static_cast<int>(length));
2852 external_string->set_hash_field(String::kEmptyHashField);
2853 external_string->set_resource(resource);
2859 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
2860 if (code <= String::kMaxAsciiCharCode) {
2861 Object* value = single_character_string_cache()->get(code);
2862 if (value != undefined_value()) return value;
2865 buffer[0] = static_cast<char>(code);
2867 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
2869 if (!maybe_result->ToObject(&result)) return maybe_result;
2870 single_character_string_cache()->set(code, result);
2875 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
2876 if (!maybe_result->ToObject(&result)) return maybe_result;
2878 String* answer = String::cast(result);
2879 answer->Set(0, code);
2884 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
2885 if (length < 0 || length > ByteArray::kMaxLength) {
2886 return Failure::OutOfMemoryException();
2888 if (pretenure == NOT_TENURED) {
2889 return AllocateByteArray(length);
2891 int size = ByteArray::SizeFor(length);
2893 { MaybeObject* maybe_result = (size <= MaxObjectSizeInPagedSpace())
2894 ? old_data_space_->AllocateRaw(size)
2895 : lo_space_->AllocateRaw(size);
2896 if (!maybe_result->ToObject(&result)) return maybe_result;
2899 reinterpret_cast<ByteArray*>(result)->set_map(byte_array_map());
2900 reinterpret_cast<ByteArray*>(result)->set_length(length);
2905 MaybeObject* Heap::AllocateByteArray(int length) {
2906 if (length < 0 || length > ByteArray::kMaxLength) {
2907 return Failure::OutOfMemoryException();
2909 int size = ByteArray::SizeFor(length);
2910 AllocationSpace space =
2911 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : NEW_SPACE;
2913 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
2914 if (!maybe_result->ToObject(&result)) return maybe_result;
2917 reinterpret_cast<ByteArray*>(result)->set_map(byte_array_map());
2918 reinterpret_cast<ByteArray*>(result)->set_length(length);
2923 void Heap::CreateFillerObjectAt(Address addr, int size) {
2924 if (size == 0) return;
2925 HeapObject* filler = HeapObject::FromAddress(addr);
2926 if (size == kPointerSize) {
2927 filler->set_map(one_pointer_filler_map());
2928 } else if (size == 2 * kPointerSize) {
2929 filler->set_map(two_pointer_filler_map());
2931 filler->set_map(byte_array_map());
2932 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2937 MaybeObject* Heap::AllocateExternalArray(int length,
2938 ExternalArrayType array_type,
2939 void* external_pointer,
2940 PretenureFlag pretenure) {
2941 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2943 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
2946 if (!maybe_result->ToObject(&result)) return maybe_result;
2949 reinterpret_cast<ExternalArray*>(result)->set_map(
2950 MapForExternalArrayType(array_type));
2951 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2952 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2959 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
2961 Handle<Object> self_reference,
2963 // Allocate ByteArray before the Code object, so that we do not risk
2964 // leaving uninitialized Code object (and breaking the heap).
2966 { MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
2967 if (!maybe_reloc_info->ToObject(&reloc_info)) return maybe_reloc_info;
2971 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
2972 int obj_size = Code::SizeFor(body_size);
2973 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
2974 MaybeObject* maybe_result;
2975 // Large code objects and code objects which should stay at a fixed address
2976 // are allocated in large object space.
2977 if (obj_size > MaxObjectSizeInPagedSpace() || immovable) {
2978 maybe_result = lo_space_->AllocateRawCode(obj_size);
2980 maybe_result = code_space_->AllocateRaw(obj_size);
2984 if (!maybe_result->ToObject(&result)) return maybe_result;
2986 // Initialize the object
2987 HeapObject::cast(result)->set_map(code_map());
2988 Code* code = Code::cast(result);
2989 ASSERT(!isolate_->code_range()->exists() ||
2990 isolate_->code_range()->contains(code->address()));
2991 code->set_instruction_size(desc.instr_size);
2992 code->set_relocation_info(ByteArray::cast(reloc_info));
2993 code->set_flags(flags);
2994 if (code->is_call_stub() || code->is_keyed_call_stub()) {
2995 code->set_check_type(RECEIVER_MAP_CHECK);
2997 code->set_deoptimization_data(empty_fixed_array());
2998 code->set_next_code_flushing_candidate(undefined_value());
2999 // Allow self references to created code object by patching the handle to
3000 // point to the newly allocated Code object.
3001 if (!self_reference.is_null()) {
3002 *(self_reference.location()) = code;
3004 // Migrate generated code.
3005 // The generated code can contain Object** values (typically from handles)
3006 // that are dereferenced during the copy to point directly to the actual heap
3007 // objects. These pointers can include references to the code object itself,
3008 // through the self_reference parameter.
3009 code->CopyFrom(desc);
3018 MaybeObject* Heap::CopyCode(Code* code) {
3019 // Allocate an object the same size as the code object.
3020 int obj_size = code->Size();
3021 MaybeObject* maybe_result;
3022 if (obj_size > MaxObjectSizeInPagedSpace()) {
3023 maybe_result = lo_space_->AllocateRawCode(obj_size);
3025 maybe_result = code_space_->AllocateRaw(obj_size);
3029 if (!maybe_result->ToObject(&result)) return maybe_result;
3031 // Copy code object.
3032 Address old_addr = code->address();
3033 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3034 CopyBlock(new_addr, old_addr, obj_size);
3035 // Relocate the copy.
3036 Code* new_code = Code::cast(result);
3037 ASSERT(!isolate_->code_range()->exists() ||
3038 isolate_->code_range()->contains(code->address()));
3039 new_code->Relocate(new_addr - old_addr);
3044 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3045 // Allocate ByteArray before the Code object, so that we do not risk
3046 // leaving uninitialized Code object (and breaking the heap).
3047 Object* reloc_info_array;
3048 { MaybeObject* maybe_reloc_info_array =
3049 AllocateByteArray(reloc_info.length(), TENURED);
3050 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3051 return maybe_reloc_info_array;
3055 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3057 int new_obj_size = Code::SizeFor(new_body_size);
3059 Address old_addr = code->address();
3061 size_t relocation_offset =
3062 static_cast<size_t>(code->instruction_end() - old_addr);
3064 MaybeObject* maybe_result;
3065 if (new_obj_size > MaxObjectSizeInPagedSpace()) {
3066 maybe_result = lo_space_->AllocateRawCode(new_obj_size);
3068 maybe_result = code_space_->AllocateRaw(new_obj_size);
3072 if (!maybe_result->ToObject(&result)) return maybe_result;
3074 // Copy code object.
3075 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3077 // Copy header and instructions.
3078 memcpy(new_addr, old_addr, relocation_offset);
3080 Code* new_code = Code::cast(result);
3081 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3083 // Copy patched rinfo.
3084 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3086 // Relocate the copy.
3087 ASSERT(!isolate_->code_range()->exists() ||
3088 isolate_->code_range()->contains(code->address()));
3089 new_code->Relocate(new_addr - old_addr);
3098 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3099 ASSERT(gc_state_ == NOT_IN_GC);
3100 ASSERT(map->instance_type() != MAP_TYPE);
3101 // If allocation failures are disallowed, we may allocate in a different
3102 // space when new space is full and the object is not a large object.
3103 AllocationSpace retry_space =
3104 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3106 { MaybeObject* maybe_result =
3107 AllocateRaw(map->instance_size(), space, retry_space);
3108 if (!maybe_result->ToObject(&result)) return maybe_result;
3110 HeapObject::cast(result)->set_map(map);
3115 MaybeObject* Heap::InitializeFunction(JSFunction* function,
3116 SharedFunctionInfo* shared,
3117 Object* prototype) {
3118 ASSERT(!prototype->IsMap());
3119 function->initialize_properties();
3120 function->initialize_elements();
3121 function->set_shared(shared);
3122 function->set_code(shared->code());
3123 function->set_prototype_or_initial_map(prototype);
3124 function->set_context(undefined_value());
3125 function->set_literals(empty_fixed_array());
3126 function->set_next_function_link(undefined_value());
3131 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3132 // Allocate the prototype. Make sure to use the object function
3133 // from the function's context, since the function can be from a
3134 // different context.
3135 JSFunction* object_function =
3136 function->context()->global_context()->object_function();
3138 { MaybeObject* maybe_prototype = AllocateJSObject(object_function);
3139 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3141 // When creating the prototype for the function we must set its
3142 // constructor to the function.
3144 { MaybeObject* maybe_result =
3145 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3146 constructor_symbol(), function, DONT_ENUM);
3147 if (!maybe_result->ToObject(&result)) return maybe_result;
3153 MaybeObject* Heap::AllocateFunction(Map* function_map,
3154 SharedFunctionInfo* shared,
3156 PretenureFlag pretenure) {
3157 AllocationSpace space =
3158 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3160 { MaybeObject* maybe_result = Allocate(function_map, space);
3161 if (!maybe_result->ToObject(&result)) return maybe_result;
3163 return InitializeFunction(JSFunction::cast(result), shared, prototype);
3167 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3168 // To get fast allocation and map sharing for arguments objects we
3169 // allocate them based on an arguments boilerplate.
3171 JSObject* boilerplate;
3172 int arguments_object_size;
3173 bool strict_mode_callee = callee->IsJSFunction() &&
3174 JSFunction::cast(callee)->shared()->strict_mode();
3175 if (strict_mode_callee) {
3177 isolate()->context()->global_context()->
3178 strict_mode_arguments_boilerplate();
3179 arguments_object_size = kArgumentsObjectSizeStrict;
3182 isolate()->context()->global_context()->arguments_boilerplate();
3183 arguments_object_size = kArgumentsObjectSize;
3186 // This calls Copy directly rather than using Heap::AllocateRaw so we
3187 // duplicate the check here.
3188 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3190 // Check that the size of the boilerplate matches our
3191 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3192 // on the size being a known constant.
3193 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3195 // Do the allocation.
3197 { MaybeObject* maybe_result =
3198 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3199 if (!maybe_result->ToObject(&result)) return maybe_result;
3202 // Copy the content. The arguments boilerplate doesn't have any
3203 // fields that point to new space so it's safe to skip the write
3205 CopyBlock(HeapObject::cast(result)->address(),
3206 boilerplate->address(),
3207 JSObject::kHeaderSize);
3209 // Set the length property.
3210 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3211 Smi::FromInt(length),
3212 SKIP_WRITE_BARRIER);
3213 // Set the callee property for non-strict mode arguments object only.
3214 if (!strict_mode_callee) {
3215 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3219 // Check the state of the object
3220 ASSERT(JSObject::cast(result)->HasFastProperties());
3221 ASSERT(JSObject::cast(result)->HasFastElements());
3227 static bool HasDuplicates(DescriptorArray* descriptors) {
3228 int count = descriptors->number_of_descriptors();
3230 String* prev_key = descriptors->GetKey(0);
3231 for (int i = 1; i != count; i++) {
3232 String* current_key = descriptors->GetKey(i);
3233 if (prev_key == current_key) return true;
3234 prev_key = current_key;
3241 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3242 ASSERT(!fun->has_initial_map());
3244 // First create a new map with the size and number of in-object properties
3245 // suggested by the function.
3246 int instance_size = fun->shared()->CalculateInstanceSize();
3247 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3249 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3250 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3253 // Fetch or allocate prototype.
3255 if (fun->has_instance_prototype()) {
3256 prototype = fun->instance_prototype();
3258 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3259 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3262 Map* map = Map::cast(map_obj);
3263 map->set_inobject_properties(in_object_properties);
3264 map->set_unused_property_fields(in_object_properties);
3265 map->set_prototype(prototype);
3266 ASSERT(map->has_fast_elements());
3268 // If the function has only simple this property assignments add
3269 // field descriptors for these to the initial map as the object
3270 // cannot be constructed without having these properties. Guard by
3271 // the inline_new flag so we only change the map if we generate a
3272 // specialized construct stub.
3273 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3274 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3275 int count = fun->shared()->this_property_assignments_count();
3276 if (count > in_object_properties) {
3277 // Inline constructor can only handle inobject properties.
3278 fun->shared()->ForbidInlineConstructor();
3280 Object* descriptors_obj;
3281 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
3282 if (!maybe_descriptors_obj->ToObject(&descriptors_obj)) {
3283 return maybe_descriptors_obj;
3286 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
3287 for (int i = 0; i < count; i++) {
3288 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3289 ASSERT(name->IsSymbol());
3290 FieldDescriptor field(name, i, NONE);
3291 field.SetEnumerationIndex(i);
3292 descriptors->Set(i, &field);
3294 descriptors->SetNextEnumerationIndex(count);
3295 descriptors->SortUnchecked();
3297 // The descriptors may contain duplicates because the compiler does not
3298 // guarantee the uniqueness of property names (it would have required
3299 // quadratic time). Once the descriptors are sorted we can check for
3300 // duplicates in linear time.
3301 if (HasDuplicates(descriptors)) {
3302 fun->shared()->ForbidInlineConstructor();
3304 map->set_instance_descriptors(descriptors);
3305 map->set_pre_allocated_property_fields(count);
3306 map->set_unused_property_fields(in_object_properties - count);
3311 fun->shared()->StartInobjectSlackTracking(map);
3317 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3318 FixedArray* properties,
3320 obj->set_properties(properties);
3321 obj->initialize_elements();
3322 // TODO(1240798): Initialize the object's body using valid initial values
3323 // according to the object's initial map. For example, if the map's
3324 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3325 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
3326 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
3327 // verification code has to cope with (temporarily) invalid objects. See
3328 // for example, JSArray::JSArrayVerify).
3330 // We cannot always fill with one_pointer_filler_map because objects
3331 // created from API functions expect their internal fields to be initialized
3332 // with undefined_value.
3333 if (map->constructor()->IsJSFunction() &&
3334 JSFunction::cast(map->constructor())->shared()->
3335 IsInobjectSlackTrackingInProgress()) {
3336 // We might want to shrink the object later.
3337 ASSERT(obj->GetInternalFieldCount() == 0);
3338 filler = Heap::one_pointer_filler_map();
3340 filler = Heap::undefined_value();
3342 obj->InitializeBody(map->instance_size(), filler);
3346 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3347 // JSFunctions should be allocated using AllocateFunction to be
3348 // properly initialized.
3349 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3351 // Both types of global objects should be allocated using
3352 // AllocateGlobalObject to be properly initialized.
3353 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3354 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3356 // Allocate the backing storage for the properties.
3358 map->pre_allocated_property_fields() +
3359 map->unused_property_fields() -
3360 map->inobject_properties();
3361 ASSERT(prop_size >= 0);
3363 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3364 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3367 // Allocate the JSObject.
3368 AllocationSpace space =
3369 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3370 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
3372 { MaybeObject* maybe_obj = Allocate(map, space);
3373 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3376 // Initialize the JSObject.
3377 InitializeJSObjectFromMap(JSObject::cast(obj),
3378 FixedArray::cast(properties),
3380 ASSERT(JSObject::cast(obj)->HasFastElements());
3385 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3386 PretenureFlag pretenure) {
3387 // Allocate the initial map if absent.
3388 if (!constructor->has_initial_map()) {
3389 Object* initial_map;
3390 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3391 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3393 constructor->set_initial_map(Map::cast(initial_map));
3394 Map::cast(initial_map)->set_constructor(constructor);
3396 // Allocate the object based on the constructors initial map.
3397 MaybeObject* result =
3398 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
3400 // Make sure result is NOT a global object if valid.
3401 Object* non_failure;
3402 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3408 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3410 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3411 // maps. Will probably depend on the identity of the handler object, too.
3413 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3414 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3415 map->set_prototype(prototype);
3417 // Allocate the proxy object.
3419 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3420 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3421 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3422 result->set_handler(handler);
3427 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3429 Object* construct_trap,
3430 Object* prototype) {
3432 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3433 // maps. Will probably depend on the identity of the handler object, too.
3435 MaybeObject* maybe_map_obj =
3436 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3437 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3438 map->set_prototype(prototype);
3440 // Allocate the proxy object.
3441 JSFunctionProxy* result;
3442 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3443 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3444 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3445 result->set_handler(handler);
3446 result->set_call_trap(call_trap);
3447 result->set_construct_trap(construct_trap);
3452 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
3453 ASSERT(constructor->has_initial_map());
3454 Map* map = constructor->initial_map();
3456 // Make sure no field properties are described in the initial map.
3457 // This guarantees us that normalizing the properties does not
3458 // require us to change property values to JSGlobalPropertyCells.
3459 ASSERT(map->NextFreePropertyIndex() == 0);
3461 // Make sure we don't have a ton of pre-allocated slots in the
3462 // global objects. They will be unused once we normalize the object.
3463 ASSERT(map->unused_property_fields() == 0);
3464 ASSERT(map->inobject_properties() == 0);
3466 // Initial size of the backing store to avoid resize of the storage during
3467 // bootstrapping. The size differs between the JS global object ad the
3469 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3471 // Allocate a dictionary object for backing storage.
3473 { MaybeObject* maybe_obj =
3474 StringDictionary::Allocate(
3475 map->NumberOfDescribedProperties() * 2 + initial_size);
3476 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3478 StringDictionary* dictionary = StringDictionary::cast(obj);
3480 // The global object might be created from an object template with accessors.
3481 // Fill these accessors into the dictionary.
3482 DescriptorArray* descs = map->instance_descriptors();
3483 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3484 PropertyDetails details(descs->GetDetails(i));
3485 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3487 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3488 Object* value = descs->GetCallbacksObject(i);
3489 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
3490 if (!maybe_value->ToObject(&value)) return maybe_value;
3494 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3495 if (!maybe_result->ToObject(&result)) return maybe_result;
3497 dictionary = StringDictionary::cast(result);
3500 // Allocate the global object and initialize it with the backing store.
3501 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3502 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3504 JSObject* global = JSObject::cast(obj);
3505 InitializeJSObjectFromMap(global, dictionary, map);
3507 // Create a new map for the global object.
3508 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3509 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3511 Map* new_map = Map::cast(obj);
3513 // Setup the global object as a normalized object.
3514 global->set_map(new_map);
3515 global->map()->clear_instance_descriptors();
3516 global->set_properties(dictionary);
3518 // Make sure result is a global object with properties in dictionary.
3519 ASSERT(global->IsGlobalObject());
3520 ASSERT(!global->HasFastProperties());
3525 MaybeObject* Heap::CopyJSObject(JSObject* source) {
3526 // Never used to copy functions. If functions need to be copied we
3527 // have to be careful to clear the literals array.
3528 ASSERT(!source->IsJSFunction());
3531 Map* map = source->map();
3532 int object_size = map->instance_size();
3535 // If we're forced to always allocate, we use the general allocation
3536 // functions which may leave us with an object in old space.
3537 if (always_allocate()) {
3538 { MaybeObject* maybe_clone =
3539 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
3540 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3542 Address clone_address = HeapObject::cast(clone)->address();
3543 CopyBlock(clone_address,
3546 // Update write barrier for all fields that lie beyond the header.
3547 RecordWrites(clone_address,
3548 JSObject::kHeaderSize,
3549 (object_size - JSObject::kHeaderSize) / kPointerSize);
3551 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
3552 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3554 ASSERT(InNewSpace(clone));
3555 // Since we know the clone is allocated in new space, we can copy
3556 // the contents without worrying about updating the write barrier.
3557 CopyBlock(HeapObject::cast(clone)->address(),
3562 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
3563 FixedArray* properties = FixedArray::cast(source->properties());
3564 // Update elements if necessary.
3565 if (elements->length() > 0) {
3567 { MaybeObject* maybe_elem;
3568 if (elements->map() == fixed_cow_array_map()) {
3569 maybe_elem = FixedArray::cast(elements);
3570 } else if (source->HasFastDoubleElements()) {
3571 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
3573 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
3575 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
3577 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem));
3579 // Update properties if necessary.
3580 if (properties->length() > 0) {
3582 { MaybeObject* maybe_prop = CopyFixedArray(properties);
3583 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
3585 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
3587 // Return the new clone.
3592 MaybeObject* Heap::ReinitializeJSReceiver(
3593 JSReceiver* object, InstanceType type, int size) {
3594 ASSERT(type >= FIRST_JS_RECEIVER_TYPE);
3596 // Allocate fresh map.
3597 // TODO(rossberg): Once we optimize proxies, cache these maps.
3599 MaybeObject* maybe_map_obj = AllocateMap(type, size);
3600 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3602 // Check that the receiver has at least the size of the fresh object.
3603 int size_difference = object->map()->instance_size() - map->instance_size();
3604 ASSERT(size_difference >= 0);
3606 map->set_prototype(object->map()->prototype());
3608 // Allocate the backing storage for the properties.
3609 int prop_size = map->unused_property_fields() - map->inobject_properties();
3611 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
3612 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3615 // Reset the map for the object.
3616 object->set_map(map);
3618 // Reinitialize the object from the constructor map.
3619 InitializeJSObjectFromMap(JSObject::cast(object),
3620 FixedArray::cast(properties), map);
3622 // Functions require some minimal initialization.
3623 if (type == JS_FUNCTION_TYPE) {
3625 MaybeObject* maybe_name = LookupAsciiSymbol("<freezing call trap>");
3626 if (!maybe_name->To<String>(&name)) return maybe_name;
3627 SharedFunctionInfo* shared;
3628 MaybeObject* maybe_shared = AllocateSharedFunctionInfo(name);
3629 if (!maybe_shared->To<SharedFunctionInfo>(&shared)) return maybe_shared;
3631 MaybeObject* maybe_func =
3632 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
3633 if (!maybe_func->To<JSFunction>(&func)) return maybe_func;
3634 func->set_context(isolate()->context()->global_context());
3637 // Put in filler if the new object is smaller than the old.
3638 if (size_difference > 0) {
3639 CreateFillerObjectAt(
3640 object->address() + map->instance_size(), size_difference);
3647 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
3648 JSGlobalProxy* object) {
3649 ASSERT(constructor->has_initial_map());
3650 Map* map = constructor->initial_map();
3652 // Check that the already allocated object has the same size and type as
3653 // objects allocated using the constructor.
3654 ASSERT(map->instance_size() == object->map()->instance_size());
3655 ASSERT(map->instance_type() == object->map()->instance_type());
3657 // Allocate the backing storage for the properties.
3658 int prop_size = map->unused_property_fields() - map->inobject_properties();
3660 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
3661 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3664 // Reset the map for the object.
3665 object->set_map(constructor->initial_map());
3667 // Reinitialize the object from the constructor map.
3668 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
3673 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
3674 PretenureFlag pretenure) {
3675 if (string.length() == 1) {
3676 return Heap::LookupSingleCharacterStringFromCode(string[0]);
3679 { MaybeObject* maybe_result =
3680 AllocateRawAsciiString(string.length(), pretenure);
3681 if (!maybe_result->ToObject(&result)) return maybe_result;
3684 // Copy the characters into the new object.
3685 SeqAsciiString* string_result = SeqAsciiString::cast(result);
3686 for (int i = 0; i < string.length(); i++) {
3687 string_result->SeqAsciiStringSet(i, string[i]);
3693 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
3694 PretenureFlag pretenure) {
3695 // V8 only supports characters in the Basic Multilingual Plane.
3696 const uc32 kMaxSupportedChar = 0xFFFF;
3697 // Count the number of characters in the UTF-8 string and check if
3698 // it is an ASCII string.
3699 Access<UnicodeCache::Utf8Decoder>
3700 decoder(isolate_->unicode_cache()->utf8_decoder());
3701 decoder->Reset(string.start(), string.length());
3703 while (decoder->has_more()) {
3709 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
3710 if (!maybe_result->ToObject(&result)) return maybe_result;
3713 // Convert and copy the characters into the new object.
3714 String* string_result = String::cast(result);
3715 decoder->Reset(string.start(), string.length());
3716 for (int i = 0; i < chars; i++) {
3717 uc32 r = decoder->GetNext();
3718 if (r > kMaxSupportedChar) { r = unibrow::Utf8::kBadChar; }
3719 string_result->Set(i, r);
3725 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
3726 PretenureFlag pretenure) {
3727 // Check if the string is an ASCII string.
3728 MaybeObject* maybe_result;
3729 if (String::IsAscii(string.start(), string.length())) {
3730 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
3731 } else { // It's not an ASCII string.
3732 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
3735 if (!maybe_result->ToObject(&result)) return maybe_result;
3737 // Copy the characters into the new object, which may be either ASCII or
3739 String* string_result = String::cast(result);
3740 for (int i = 0; i < string.length(); i++) {
3741 string_result->Set(i, string[i]);
3747 Map* Heap::SymbolMapForString(String* string) {
3748 // If the string is in new space it cannot be used as a symbol.
3749 if (InNewSpace(string)) return NULL;
3751 // Find the corresponding symbol map for strings.
3752 Map* map = string->map();
3753 if (map == ascii_string_map()) {
3754 return ascii_symbol_map();
3756 if (map == string_map()) {
3757 return symbol_map();
3759 if (map == cons_string_map()) {
3760 return cons_symbol_map();
3762 if (map == cons_ascii_string_map()) {
3763 return cons_ascii_symbol_map();
3765 if (map == external_string_map()) {
3766 return external_symbol_map();
3768 if (map == external_ascii_string_map()) {
3769 return external_ascii_symbol_map();
3771 if (map == external_string_with_ascii_data_map()) {
3772 return external_symbol_with_ascii_data_map();
3780 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
3782 uint32_t hash_field) {
3784 // Ensure the chars matches the number of characters in the buffer.
3785 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
3786 // Determine whether the string is ascii.
3787 bool is_ascii = true;
3788 while (buffer->has_more()) {
3789 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
3796 // Compute map and object size.
3801 if (chars > SeqAsciiString::kMaxLength) {
3802 return Failure::OutOfMemoryException();
3804 map = ascii_symbol_map();
3805 size = SeqAsciiString::SizeFor(chars);
3807 if (chars > SeqTwoByteString::kMaxLength) {
3808 return Failure::OutOfMemoryException();
3811 size = SeqTwoByteString::SizeFor(chars);
3816 { MaybeObject* maybe_result = (size > MaxObjectSizeInPagedSpace())
3817 ? lo_space_->AllocateRaw(size)
3818 : old_data_space_->AllocateRaw(size);
3819 if (!maybe_result->ToObject(&result)) return maybe_result;
3822 reinterpret_cast<HeapObject*>(result)->set_map(map);
3823 // Set length and hash fields of the allocated string.
3824 String* answer = String::cast(result);
3825 answer->set_length(chars);
3826 answer->set_hash_field(hash_field);
3828 ASSERT_EQ(size, answer->Size());
3830 // Fill in the characters.
3831 for (int i = 0; i < chars; i++) {
3832 answer->Set(i, buffer->GetNext());
3838 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
3839 if (length < 0 || length > SeqAsciiString::kMaxLength) {
3840 return Failure::OutOfMemoryException();
3843 int size = SeqAsciiString::SizeFor(length);
3844 ASSERT(size <= SeqAsciiString::kMaxSize);
3846 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3847 AllocationSpace retry_space = OLD_DATA_SPACE;
3849 if (space == NEW_SPACE) {
3850 if (size > kMaxObjectSizeInNewSpace) {
3851 // Allocate in large object space, retry space will be ignored.
3853 } else if (size > MaxObjectSizeInPagedSpace()) {
3854 // Allocate in new space, retry in large object space.
3855 retry_space = LO_SPACE;
3857 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
3861 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
3862 if (!maybe_result->ToObject(&result)) return maybe_result;
3865 // Partially initialize the object.
3866 HeapObject::cast(result)->set_map(ascii_string_map());
3867 String::cast(result)->set_length(length);
3868 String::cast(result)->set_hash_field(String::kEmptyHashField);
3869 ASSERT_EQ(size, HeapObject::cast(result)->Size());
3874 MaybeObject* Heap::AllocateRawTwoByteString(int length,
3875 PretenureFlag pretenure) {
3876 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
3877 return Failure::OutOfMemoryException();
3879 int size = SeqTwoByteString::SizeFor(length);
3880 ASSERT(size <= SeqTwoByteString::kMaxSize);
3881 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3882 AllocationSpace retry_space = OLD_DATA_SPACE;
3884 if (space == NEW_SPACE) {
3885 if (size > kMaxObjectSizeInNewSpace) {
3886 // Allocate in large object space, retry space will be ignored.
3888 } else if (size > MaxObjectSizeInPagedSpace()) {
3889 // Allocate in new space, retry in large object space.
3890 retry_space = LO_SPACE;
3892 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
3896 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
3897 if (!maybe_result->ToObject(&result)) return maybe_result;
3900 // Partially initialize the object.
3901 HeapObject::cast(result)->set_map(string_map());
3902 String::cast(result)->set_length(length);
3903 String::cast(result)->set_hash_field(String::kEmptyHashField);
3904 ASSERT_EQ(size, HeapObject::cast(result)->Size());
3909 MaybeObject* Heap::AllocateEmptyFixedArray() {
3910 int size = FixedArray::SizeFor(0);
3912 { MaybeObject* maybe_result =
3913 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
3914 if (!maybe_result->ToObject(&result)) return maybe_result;
3916 // Initialize the object.
3917 reinterpret_cast<FixedArray*>(result)->set_map(fixed_array_map());
3918 reinterpret_cast<FixedArray*>(result)->set_length(0);
3923 MaybeObject* Heap::AllocateRawFixedArray(int length) {
3924 if (length < 0 || length > FixedArray::kMaxLength) {
3925 return Failure::OutOfMemoryException();
3928 // Use the general function if we're forced to always allocate.
3929 if (always_allocate()) return AllocateFixedArray(length, TENURED);
3930 // Allocate the raw data for a fixed array.
3931 int size = FixedArray::SizeFor(length);
3932 return size <= kMaxObjectSizeInNewSpace
3933 ? new_space_.AllocateRaw(size)
3934 : lo_space_->AllocateRawFixedArray(size);
3938 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
3939 int len = src->length();
3941 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
3942 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3944 if (InNewSpace(obj)) {
3945 HeapObject* dst = HeapObject::cast(obj);
3947 CopyBlock(dst->address() + kPointerSize,
3948 src->address() + kPointerSize,
3949 FixedArray::SizeFor(len) - kPointerSize);
3952 HeapObject::cast(obj)->set_map(map);
3953 FixedArray* result = FixedArray::cast(obj);
3954 result->set_length(len);
3957 AssertNoAllocation no_gc;
3958 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
3959 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
3964 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
3966 int len = src->length();
3968 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
3969 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3971 HeapObject* dst = HeapObject::cast(obj);
3974 dst->address() + FixedDoubleArray::kLengthOffset,
3975 src->address() + FixedDoubleArray::kLengthOffset,
3976 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
3981 MaybeObject* Heap::AllocateFixedArray(int length) {
3982 ASSERT(length >= 0);
3983 if (length == 0) return empty_fixed_array();
3985 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
3986 if (!maybe_result->ToObject(&result)) return maybe_result;
3988 // Initialize header.
3989 FixedArray* array = reinterpret_cast<FixedArray*>(result);
3990 array->set_map(fixed_array_map());
3991 array->set_length(length);
3993 ASSERT(!InNewSpace(undefined_value()));
3994 MemsetPointer(array->data_start(), undefined_value(), length);
3999 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4000 if (length < 0 || length > FixedArray::kMaxLength) {
4001 return Failure::OutOfMemoryException();
4004 AllocationSpace space =
4005 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4006 int size = FixedArray::SizeFor(length);
4007 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4008 // Too big for new space.
4010 } else if (space == OLD_POINTER_SPACE &&
4011 size > MaxObjectSizeInPagedSpace()) {
4012 // Too big for old pointer space.
4016 AllocationSpace retry_space =
4017 (size <= MaxObjectSizeInPagedSpace()) ? OLD_POINTER_SPACE : LO_SPACE;
4019 return AllocateRaw(size, space, retry_space);
4023 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4026 PretenureFlag pretenure,
4028 ASSERT(length >= 0);
4029 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4030 if (length == 0) return heap->empty_fixed_array();
4032 ASSERT(!heap->InNewSpace(filler));
4034 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4035 if (!maybe_result->ToObject(&result)) return maybe_result;
4038 HeapObject::cast(result)->set_map(heap->fixed_array_map());
4039 FixedArray* array = FixedArray::cast(result);
4040 array->set_length(length);
4041 MemsetPointer(array->data_start(), filler, length);
4046 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4047 return AllocateFixedArrayWithFiller(this,
4054 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4055 PretenureFlag pretenure) {
4056 return AllocateFixedArrayWithFiller(this,
4063 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4064 if (length == 0) return empty_fixed_array();
4067 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4068 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4071 reinterpret_cast<FixedArray*>(obj)->set_map(fixed_array_map());
4072 FixedArray::cast(obj)->set_length(length);
4077 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4078 int size = FixedDoubleArray::SizeFor(0);
4080 { MaybeObject* maybe_result =
4081 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4082 if (!maybe_result->ToObject(&result)) return maybe_result;
4084 // Initialize the object.
4085 reinterpret_cast<FixedDoubleArray*>(result)->set_map(
4086 fixed_double_array_map());
4087 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4092 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4094 PretenureFlag pretenure) {
4095 if (length == 0) return empty_fixed_double_array();
4098 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4099 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4102 reinterpret_cast<FixedDoubleArray*>(obj)->set_map(fixed_double_array_map());
4103 FixedDoubleArray::cast(obj)->set_length(length);
4108 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4109 PretenureFlag pretenure) {
4110 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4111 return Failure::OutOfMemoryException();
4114 AllocationSpace space =
4115 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4116 int size = FixedDoubleArray::SizeFor(length);
4117 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4118 // Too big for new space.
4120 } else if (space == OLD_DATA_SPACE &&
4121 size > MaxObjectSizeInPagedSpace()) {
4122 // Too big for old data space.
4126 AllocationSpace retry_space =
4127 (size <= MaxObjectSizeInPagedSpace()) ? OLD_DATA_SPACE : LO_SPACE;
4129 return AllocateRaw(size, space, retry_space);
4133 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4135 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4136 if (!maybe_result->ToObject(&result)) return maybe_result;
4138 reinterpret_cast<HeapObject*>(result)->set_map(hash_table_map());
4139 ASSERT(result->IsHashTable());
4144 MaybeObject* Heap::AllocateGlobalContext() {
4146 { MaybeObject* maybe_result =
4147 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4148 if (!maybe_result->ToObject(&result)) return maybe_result;
4150 Context* context = reinterpret_cast<Context*>(result);
4151 context->set_map(global_context_map());
4152 ASSERT(context->IsGlobalContext());
4153 ASSERT(result->IsContext());
4158 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4159 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4161 { MaybeObject* maybe_result = AllocateFixedArray(length);
4162 if (!maybe_result->ToObject(&result)) return maybe_result;
4164 Context* context = reinterpret_cast<Context*>(result);
4165 context->set_map(function_context_map());
4166 context->set_closure(function);
4167 context->set_previous(function->context());
4168 context->set_extension(NULL);
4169 context->set_global(function->context()->global());
4174 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4177 Object* thrown_object) {
4178 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4180 { MaybeObject* maybe_result =
4181 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4182 if (!maybe_result->ToObject(&result)) return maybe_result;
4184 Context* context = reinterpret_cast<Context*>(result);
4185 context->set_map(catch_context_map());
4186 context->set_closure(function);
4187 context->set_previous(previous);
4188 context->set_extension(name);
4189 context->set_global(previous->global());
4190 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4195 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4197 JSObject* extension) {
4199 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4200 if (!maybe_result->ToObject(&result)) return maybe_result;
4202 Context* context = reinterpret_cast<Context*>(result);
4203 context->set_map(with_context_map());
4204 context->set_closure(function);
4205 context->set_previous(previous);
4206 context->set_extension(extension);
4207 context->set_global(previous->global());
4212 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4214 SerializedScopeInfo* scope_info) {
4216 { MaybeObject* maybe_result =
4217 AllocateFixedArrayWithHoles(scope_info->NumberOfContextSlots());
4218 if (!maybe_result->ToObject(&result)) return maybe_result;
4220 Context* context = reinterpret_cast<Context*>(result);
4221 context->set_map(block_context_map());
4222 context->set_closure(function);
4223 context->set_previous(previous);
4224 context->set_extension(scope_info);
4225 context->set_global(previous->global());
4230 MaybeObject* Heap::AllocateSerializedScopeInfo(int length) {
4232 { MaybeObject* maybe_result = AllocateFixedArray(length, TENURED);
4233 if (!maybe_result->ToObject(&result)) return maybe_result;
4235 SerializedScopeInfo* scope_info =
4236 reinterpret_cast<SerializedScopeInfo*>(result);
4237 scope_info->set_map(serialized_scope_info_map());
4242 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4245 #define MAKE_CASE(NAME, Name, name) \
4246 case NAME##_TYPE: map = name##_map(); break;
4247 STRUCT_LIST(MAKE_CASE)
4251 return Failure::InternalError();
4253 int size = map->instance_size();
4254 AllocationSpace space =
4255 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
4257 { MaybeObject* maybe_result = Allocate(map, space);
4258 if (!maybe_result->ToObject(&result)) return maybe_result;
4260 Struct::cast(result)->InitializeBody(size);
4265 bool Heap::IdleNotification() {
4266 static const int kIdlesBeforeScavenge = 4;
4267 static const int kIdlesBeforeMarkSweep = 7;
4268 static const int kIdlesBeforeMarkCompact = 8;
4269 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
4270 static const unsigned int kGCsBetweenCleanup = 4;
4272 if (!last_idle_notification_gc_count_init_) {
4273 last_idle_notification_gc_count_ = gc_count_;
4274 last_idle_notification_gc_count_init_ = true;
4277 bool uncommit = true;
4278 bool finished = false;
4280 // Reset the number of idle notifications received when a number of
4281 // GCs have taken place. This allows another round of cleanup based
4282 // on idle notifications if enough work has been carried out to
4283 // provoke a number of garbage collections.
4284 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4285 number_idle_notifications_ =
4286 Min(number_idle_notifications_ + 1, kMaxIdleCount);
4288 number_idle_notifications_ = 0;
4289 last_idle_notification_gc_count_ = gc_count_;
4292 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
4293 if (contexts_disposed_ > 0) {
4294 HistogramTimerScope scope(isolate_->counters()->gc_context());
4295 CollectAllGarbage(false);
4297 CollectGarbage(NEW_SPACE);
4299 new_space_.Shrink();
4300 last_idle_notification_gc_count_ = gc_count_;
4301 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
4302 // Before doing the mark-sweep collections we clear the
4303 // compilation cache to avoid hanging on to source code and
4304 // generated code for cached functions.
4305 isolate_->compilation_cache()->Clear();
4307 CollectAllGarbage(false);
4308 new_space_.Shrink();
4309 last_idle_notification_gc_count_ = gc_count_;
4311 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
4312 CollectAllGarbage(true);
4313 new_space_.Shrink();
4314 last_idle_notification_gc_count_ = gc_count_;
4315 number_idle_notifications_ = 0;
4317 } else if (contexts_disposed_ > 0) {
4318 if (FLAG_expose_gc) {
4319 contexts_disposed_ = 0;
4321 HistogramTimerScope scope(isolate_->counters()->gc_context());
4322 CollectAllGarbage(false);
4323 last_idle_notification_gc_count_ = gc_count_;
4325 // If this is the first idle notification, we reset the
4326 // notification count to avoid letting idle notifications for
4327 // context disposal garbage collections start a potentially too
4328 // aggressive idle GC cycle.
4329 if (number_idle_notifications_ <= 1) {
4330 number_idle_notifications_ = 0;
4333 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
4334 // If we have received more than kIdlesBeforeMarkCompact idle
4335 // notifications we do not perform any cleanup because we don't
4336 // expect to gain much by doing so.
4340 // Make sure that we have no pending context disposals and
4341 // conditionally uncommit from space.
4342 ASSERT(contexts_disposed_ == 0);
4343 if (uncommit) UncommitFromSpace();
4350 void Heap::Print() {
4351 if (!HasBeenSetup()) return;
4352 isolate()->PrintStack();
4354 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4359 void Heap::ReportCodeStatistics(const char* title) {
4360 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4361 PagedSpace::ResetCodeStatistics();
4362 // We do not look for code in new space, map space, or old space. If code
4363 // somehow ends up in those spaces, we would miss it here.
4364 code_space_->CollectCodeStatistics();
4365 lo_space_->CollectCodeStatistics();
4366 PagedSpace::ReportCodeStatistics();
4370 // This function expects that NewSpace's allocated objects histogram is
4371 // populated (via a call to CollectStatistics or else as a side effect of a
4372 // just-completed scavenge collection).
4373 void Heap::ReportHeapStatistics(const char* title) {
4375 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
4377 PrintF("mark-compact GC : %d\n", mc_count_);
4378 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
4379 old_gen_promotion_limit_);
4380 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
4381 old_gen_allocation_limit_);
4384 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
4385 isolate_->global_handles()->PrintStats();
4388 PrintF("Heap statistics : ");
4389 isolate_->memory_allocator()->ReportStatistics();
4390 PrintF("To space : ");
4391 new_space_.ReportStatistics();
4392 PrintF("Old pointer space : ");
4393 old_pointer_space_->ReportStatistics();
4394 PrintF("Old data space : ");
4395 old_data_space_->ReportStatistics();
4396 PrintF("Code space : ");
4397 code_space_->ReportStatistics();
4398 PrintF("Map space : ");
4399 map_space_->ReportStatistics();
4400 PrintF("Cell space : ");
4401 cell_space_->ReportStatistics();
4402 PrintF("Large object space : ");
4403 lo_space_->ReportStatistics();
4404 PrintF(">>>>>> ========================================= >>>>>>\n");
4409 bool Heap::Contains(HeapObject* value) {
4410 return Contains(value->address());
4414 bool Heap::Contains(Address addr) {
4415 if (OS::IsOutsideAllocatedSpace(addr)) return false;
4416 return HasBeenSetup() &&
4417 (new_space_.ToSpaceContains(addr) ||
4418 old_pointer_space_->Contains(addr) ||
4419 old_data_space_->Contains(addr) ||
4420 code_space_->Contains(addr) ||
4421 map_space_->Contains(addr) ||
4422 cell_space_->Contains(addr) ||
4423 lo_space_->SlowContains(addr));
4427 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
4428 return InSpace(value->address(), space);
4432 bool Heap::InSpace(Address addr, AllocationSpace space) {
4433 if (OS::IsOutsideAllocatedSpace(addr)) return false;
4434 if (!HasBeenSetup()) return false;
4438 return new_space_.ToSpaceContains(addr);
4439 case OLD_POINTER_SPACE:
4440 return old_pointer_space_->Contains(addr);
4441 case OLD_DATA_SPACE:
4442 return old_data_space_->Contains(addr);
4444 return code_space_->Contains(addr);
4446 return map_space_->Contains(addr);
4448 return cell_space_->Contains(addr);
4450 return lo_space_->SlowContains(addr);
4458 static void DummyScavengePointer(HeapObject** p) {
4462 static void VerifyPointersUnderWatermark(
4464 DirtyRegionCallback visit_dirty_region) {
4465 PageIterator it(space, PageIterator::PAGES_IN_USE);
4467 while (it.has_next()) {
4468 Page* page = it.next();
4469 Address start = page->ObjectAreaStart();
4470 Address end = page->AllocationWatermark();
4472 HEAP->IterateDirtyRegions(Page::kAllRegionsDirtyMarks,
4476 &DummyScavengePointer);
4481 static void VerifyPointersUnderWatermark(LargeObjectSpace* space) {
4482 LargeObjectIterator it(space);
4483 for (HeapObject* object = it.next(); object != NULL; object = it.next()) {
4484 if (object->IsFixedArray()) {
4485 Address slot_address = object->address();
4486 Address end = object->address() + object->Size();
4488 while (slot_address < end) {
4489 HeapObject** slot = reinterpret_cast<HeapObject**>(slot_address);
4490 // When we are not in GC the Heap::InNewSpace() predicate
4491 // checks that pointers which satisfy predicate point into
4492 // the active semispace.
4493 HEAP->InNewSpace(*slot);
4494 slot_address += kPointerSize;
4501 void Heap::Verify() {
4502 ASSERT(HasBeenSetup());
4504 VerifyPointersVisitor visitor;
4505 IterateRoots(&visitor, VISIT_ONLY_STRONG);
4507 new_space_.Verify();
4509 VerifyPointersAndDirtyRegionsVisitor dirty_regions_visitor;
4510 old_pointer_space_->Verify(&dirty_regions_visitor);
4511 map_space_->Verify(&dirty_regions_visitor);
4513 VerifyPointersUnderWatermark(old_pointer_space_,
4514 &IteratePointersInDirtyRegion);
4515 VerifyPointersUnderWatermark(map_space_,
4516 &IteratePointersInDirtyMapsRegion);
4517 VerifyPointersUnderWatermark(lo_space_);
4519 VerifyPageWatermarkValidity(old_pointer_space_, ALL_INVALID);
4520 VerifyPageWatermarkValidity(map_space_, ALL_INVALID);
4522 VerifyPointersVisitor no_dirty_regions_visitor;
4523 old_data_space_->Verify(&no_dirty_regions_visitor);
4524 code_space_->Verify(&no_dirty_regions_visitor);
4525 cell_space_->Verify(&no_dirty_regions_visitor);
4527 lo_space_->Verify();
4532 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
4533 Object* symbol = NULL;
4535 { MaybeObject* maybe_new_table =
4536 symbol_table()->LookupSymbol(string, &symbol);
4537 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4539 // Can't use set_symbol_table because SymbolTable::cast knows that
4540 // SymbolTable is a singleton and checks for identity.
4541 roots_[kSymbolTableRootIndex] = new_table;
4542 ASSERT(symbol != NULL);
4547 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
4548 Object* symbol = NULL;
4550 { MaybeObject* maybe_new_table =
4551 symbol_table()->LookupAsciiSymbol(string, &symbol);
4552 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4554 // Can't use set_symbol_table because SymbolTable::cast knows that
4555 // SymbolTable is a singleton and checks for identity.
4556 roots_[kSymbolTableRootIndex] = new_table;
4557 ASSERT(symbol != NULL);
4562 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
4565 Object* symbol = NULL;
4567 { MaybeObject* maybe_new_table =
4568 symbol_table()->LookupSubStringAsciiSymbol(string,
4572 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4574 // Can't use set_symbol_table because SymbolTable::cast knows that
4575 // SymbolTable is a singleton and checks for identity.
4576 roots_[kSymbolTableRootIndex] = new_table;
4577 ASSERT(symbol != NULL);
4582 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
4583 Object* symbol = NULL;
4585 { MaybeObject* maybe_new_table =
4586 symbol_table()->LookupTwoByteSymbol(string, &symbol);
4587 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4589 // Can't use set_symbol_table because SymbolTable::cast knows that
4590 // SymbolTable is a singleton and checks for identity.
4591 roots_[kSymbolTableRootIndex] = new_table;
4592 ASSERT(symbol != NULL);
4597 MaybeObject* Heap::LookupSymbol(String* string) {
4598 if (string->IsSymbol()) return string;
4599 Object* symbol = NULL;
4601 { MaybeObject* maybe_new_table =
4602 symbol_table()->LookupString(string, &symbol);
4603 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4605 // Can't use set_symbol_table because SymbolTable::cast knows that
4606 // SymbolTable is a singleton and checks for identity.
4607 roots_[kSymbolTableRootIndex] = new_table;
4608 ASSERT(symbol != NULL);
4613 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
4614 if (string->IsSymbol()) {
4618 return symbol_table()->LookupSymbolIfExists(string, symbol);
4623 void Heap::ZapFromSpace() {
4624 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsFailure());
4625 for (Address a = new_space_.FromSpaceLow();
4626 a < new_space_.FromSpaceHigh();
4627 a += kPointerSize) {
4628 Memory::Address_at(a) = kFromSpaceZapValue;
4634 bool Heap::IteratePointersInDirtyRegion(Heap* heap,
4637 ObjectSlotCallback copy_object_func) {
4638 Address slot_address = start;
4639 bool pointers_to_new_space_found = false;
4641 while (slot_address < end) {
4642 Object** slot = reinterpret_cast<Object**>(slot_address);
4643 if (heap->InNewSpace(*slot)) {
4644 ASSERT((*slot)->IsHeapObject());
4645 copy_object_func(reinterpret_cast<HeapObject**>(slot));
4646 if (heap->InNewSpace(*slot)) {
4647 ASSERT((*slot)->IsHeapObject());
4648 pointers_to_new_space_found = true;
4651 slot_address += kPointerSize;
4653 return pointers_to_new_space_found;
4657 // Compute start address of the first map following given addr.
4658 static inline Address MapStartAlign(Address addr) {
4659 Address page = Page::FromAddress(addr)->ObjectAreaStart();
4660 return page + (((addr - page) + (Map::kSize - 1)) / Map::kSize * Map::kSize);
4664 // Compute end address of the first map preceding given addr.
4665 static inline Address MapEndAlign(Address addr) {
4666 Address page = Page::FromAllocationTop(addr)->ObjectAreaStart();
4667 return page + ((addr - page) / Map::kSize * Map::kSize);
4671 static bool IteratePointersInDirtyMaps(Address start,
4673 ObjectSlotCallback copy_object_func) {
4674 ASSERT(MapStartAlign(start) == start);
4675 ASSERT(MapEndAlign(end) == end);
4677 Address map_address = start;
4678 bool pointers_to_new_space_found = false;
4681 while (map_address < end) {
4682 ASSERT(!heap->InNewSpace(Memory::Object_at(map_address)));
4683 ASSERT(Memory::Object_at(map_address)->IsMap());
4685 Address pointer_fields_start = map_address + Map::kPointerFieldsBeginOffset;
4686 Address pointer_fields_end = map_address + Map::kPointerFieldsEndOffset;
4688 if (Heap::IteratePointersInDirtyRegion(heap,
4689 pointer_fields_start,
4691 copy_object_func)) {
4692 pointers_to_new_space_found = true;
4695 map_address += Map::kSize;
4698 return pointers_to_new_space_found;
4702 bool Heap::IteratePointersInDirtyMapsRegion(
4706 ObjectSlotCallback copy_object_func) {
4707 Address map_aligned_start = MapStartAlign(start);
4708 Address map_aligned_end = MapEndAlign(end);
4710 bool contains_pointers_to_new_space = false;
4712 if (map_aligned_start != start) {
4713 Address prev_map = map_aligned_start - Map::kSize;
4714 ASSERT(Memory::Object_at(prev_map)->IsMap());
4716 Address pointer_fields_start =
4717 Max(start, prev_map + Map::kPointerFieldsBeginOffset);
4719 Address pointer_fields_end =
4720 Min(prev_map + Map::kPointerFieldsEndOffset, end);
4722 contains_pointers_to_new_space =
4723 IteratePointersInDirtyRegion(heap,
4724 pointer_fields_start,
4727 || contains_pointers_to_new_space;
4730 contains_pointers_to_new_space =
4731 IteratePointersInDirtyMaps(map_aligned_start,
4734 || contains_pointers_to_new_space;
4736 if (map_aligned_end != end) {
4737 ASSERT(Memory::Object_at(map_aligned_end)->IsMap());
4739 Address pointer_fields_start =
4740 map_aligned_end + Map::kPointerFieldsBeginOffset;
4742 Address pointer_fields_end =
4743 Min(end, map_aligned_end + Map::kPointerFieldsEndOffset);
4745 contains_pointers_to_new_space =
4746 IteratePointersInDirtyRegion(heap,
4747 pointer_fields_start,
4750 || contains_pointers_to_new_space;
4753 return contains_pointers_to_new_space;
4757 void Heap::IterateAndMarkPointersToFromSpace(Address start,
4759 ObjectSlotCallback callback) {
4760 Address slot_address = start;
4761 Page* page = Page::FromAddress(start);
4763 uint32_t marks = page->GetRegionMarks();
4765 while (slot_address < end) {
4766 Object** slot = reinterpret_cast<Object**>(slot_address);
4767 if (InFromSpace(*slot)) {
4768 ASSERT((*slot)->IsHeapObject());
4769 callback(reinterpret_cast<HeapObject**>(slot));
4770 if (InNewSpace(*slot)) {
4771 ASSERT((*slot)->IsHeapObject());
4772 marks |= page->GetRegionMaskForAddress(slot_address);
4775 slot_address += kPointerSize;
4778 page->SetRegionMarks(marks);
4782 uint32_t Heap::IterateDirtyRegions(
4786 DirtyRegionCallback visit_dirty_region,
4787 ObjectSlotCallback copy_object_func) {
4788 uint32_t newmarks = 0;
4791 if (area_start >= area_end) {
4795 Address region_start = area_start;
4797 // area_start does not necessarily coincide with start of the first region.
4798 // Thus to calculate the beginning of the next region we have to align
4799 // area_start by Page::kRegionSize.
4800 Address second_region =
4801 reinterpret_cast<Address>(
4802 reinterpret_cast<intptr_t>(area_start + Page::kRegionSize) &
4803 ~Page::kRegionAlignmentMask);
4805 // Next region might be beyond area_end.
4806 Address region_end = Min(second_region, area_end);
4809 if (visit_dirty_region(this, region_start, region_end, copy_object_func)) {
4815 // Iterate subsequent regions which fully lay inside [area_start, area_end[.
4816 region_start = region_end;
4817 region_end = region_start + Page::kRegionSize;
4819 while (region_end <= area_end) {
4821 if (visit_dirty_region(this,
4824 copy_object_func)) {
4829 region_start = region_end;
4830 region_end = region_start + Page::kRegionSize;
4835 if (region_start != area_end) {
4836 // A small piece of area left uniterated because area_end does not coincide
4837 // with region end. Check whether region covering last part of area is
4840 if (visit_dirty_region(this, region_start, area_end, copy_object_func)) {
4851 void Heap::IterateDirtyRegions(
4853 DirtyRegionCallback visit_dirty_region,
4854 ObjectSlotCallback copy_object_func,
4855 ExpectedPageWatermarkState expected_page_watermark_state) {
4857 PageIterator it(space, PageIterator::PAGES_IN_USE);
4859 while (it.has_next()) {
4860 Page* page = it.next();
4861 uint32_t marks = page->GetRegionMarks();
4863 if (marks != Page::kAllRegionsCleanMarks) {
4864 Address start = page->ObjectAreaStart();
4866 // Do not try to visit pointers beyond page allocation watermark.
4867 // Page can contain garbage pointers there.
4870 if ((expected_page_watermark_state == WATERMARK_SHOULD_BE_VALID) ||
4871 page->IsWatermarkValid()) {
4872 end = page->AllocationWatermark();
4874 end = page->CachedAllocationWatermark();
4877 ASSERT(space == old_pointer_space_ ||
4878 (space == map_space_ &&
4879 ((page->ObjectAreaStart() - end) % Map::kSize == 0)));
4881 page->SetRegionMarks(IterateDirtyRegions(marks,
4888 // Mark page watermark as invalid to maintain watermark validity invariant.
4889 // See Page::FlipMeaningOfInvalidatedWatermarkFlag() for details.
4890 page->InvalidateWatermark(true);
4895 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
4896 IterateStrongRoots(v, mode);
4897 IterateWeakRoots(v, mode);
4901 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
4902 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
4903 v->Synchronize("symbol_table");
4904 if (mode != VISIT_ALL_IN_SCAVENGE &&
4905 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
4906 // Scavenge collections have special processing for this.
4907 external_string_table_.Iterate(v);
4909 v->Synchronize("external_string_table");
4913 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
4914 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
4915 v->Synchronize("strong_root_list");
4917 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
4918 v->Synchronize("symbol");
4920 isolate_->bootstrapper()->Iterate(v);
4921 v->Synchronize("bootstrapper");
4922 isolate_->Iterate(v);
4923 v->Synchronize("top");
4924 Relocatable::Iterate(v);
4925 v->Synchronize("relocatable");
4927 #ifdef ENABLE_DEBUGGER_SUPPORT
4928 isolate_->debug()->Iterate(v);
4929 if (isolate_->deoptimizer_data() != NULL) {
4930 isolate_->deoptimizer_data()->Iterate(v);
4933 v->Synchronize("debug");
4934 isolate_->compilation_cache()->Iterate(v);
4935 v->Synchronize("compilationcache");
4937 // Iterate over local handles in handle scopes.
4938 isolate_->handle_scope_implementer()->Iterate(v);
4939 v->Synchronize("handlescope");
4941 // Iterate over the builtin code objects and code stubs in the
4942 // heap. Note that it is not necessary to iterate over code objects
4943 // on scavenge collections.
4944 if (mode != VISIT_ALL_IN_SCAVENGE &&
4945 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
4946 isolate_->builtins()->IterateBuiltins(v);
4948 v->Synchronize("builtins");
4950 // Iterate over global handles.
4952 case VISIT_ONLY_STRONG:
4953 isolate_->global_handles()->IterateStrongRoots(v);
4955 case VISIT_ALL_IN_SCAVENGE:
4956 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
4958 case VISIT_ALL_IN_SWEEP_NEWSPACE:
4960 isolate_->global_handles()->IterateAllRoots(v);
4963 v->Synchronize("globalhandles");
4965 // Iterate over pointers being held by inactive threads.
4966 isolate_->thread_manager()->Iterate(v);
4967 v->Synchronize("threadmanager");
4969 // Iterate over the pointers the Serialization/Deserialization code is
4971 // During garbage collection this keeps the partial snapshot cache alive.
4972 // During deserialization of the startup snapshot this creates the partial
4973 // snapshot cache and deserializes the objects it refers to. During
4974 // serialization this does nothing, since the partial snapshot cache is
4975 // empty. However the next thing we do is create the partial snapshot,
4976 // filling up the partial snapshot cache with objects it needs as we go.
4977 SerializerDeserializer::Iterate(v);
4978 // We don't do a v->Synchronize call here, because in debug mode that will
4979 // output a flag to the snapshot. However at this point the serializer and
4980 // deserializer are deliberately a little unsynchronized (see above) so the
4981 // checking of the sync flag in the snapshot would fail.
4985 // TODO(1236194): Since the heap size is configurable on the command line
4986 // and through the API, we should gracefully handle the case that the heap
4987 // size is not big enough to fit all the initial objects.
4988 bool Heap::ConfigureHeap(int max_semispace_size,
4989 int max_old_gen_size,
4990 int max_executable_size) {
4991 if (HasBeenSetup()) return false;
4993 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
4995 if (Snapshot::IsEnabled()) {
4996 // If we are using a snapshot we always reserve the default amount
4997 // of memory for each semispace because code in the snapshot has
4998 // write-barrier code that relies on the size and alignment of new
4999 // space. We therefore cannot use a larger max semispace size
5000 // than the default reserved semispace size.
5001 if (max_semispace_size_ > reserved_semispace_size_) {
5002 max_semispace_size_ = reserved_semispace_size_;
5005 // If we are not using snapshots we reserve space for the actual
5006 // max semispace size.
5007 reserved_semispace_size_ = max_semispace_size_;
5010 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5011 if (max_executable_size > 0) {
5012 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5015 // The max executable size must be less than or equal to the max old
5017 if (max_executable_size_ > max_old_generation_size_) {
5018 max_executable_size_ = max_old_generation_size_;
5021 // The new space size must be a power of two to support single-bit testing
5023 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5024 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5025 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5026 external_allocation_limit_ = 10 * max_semispace_size_;
5028 // The old generation is paged.
5029 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
5036 bool Heap::ConfigureHeapDefault() {
5037 return ConfigureHeap(FLAG_max_new_space_size / 2 * KB,
5038 FLAG_max_old_space_size * MB,
5039 FLAG_max_executable_size * MB);
5043 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5044 *stats->start_marker = HeapStats::kStartMarker;
5045 *stats->end_marker = HeapStats::kEndMarker;
5046 *stats->new_space_size = new_space_.SizeAsInt();
5047 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5048 *stats->old_pointer_space_size = old_pointer_space_->Size();
5049 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5050 *stats->old_data_space_size = old_data_space_->Size();
5051 *stats->old_data_space_capacity = old_data_space_->Capacity();
5052 *stats->code_space_size = code_space_->Size();
5053 *stats->code_space_capacity = code_space_->Capacity();
5054 *stats->map_space_size = map_space_->Size();
5055 *stats->map_space_capacity = map_space_->Capacity();
5056 *stats->cell_space_size = cell_space_->Size();
5057 *stats->cell_space_capacity = cell_space_->Capacity();
5058 *stats->lo_space_size = lo_space_->Size();
5059 isolate_->global_handles()->RecordStats(stats);
5060 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5061 *stats->memory_allocator_capacity =
5062 isolate()->memory_allocator()->Size() +
5063 isolate()->memory_allocator()->Available();
5064 *stats->os_error = OS::GetLastError();
5065 isolate()->memory_allocator()->Available();
5066 if (take_snapshot) {
5067 HeapIterator iterator(HeapIterator::kFilterFreeListNodes);
5068 for (HeapObject* obj = iterator.next();
5070 obj = iterator.next()) {
5071 InstanceType type = obj->map()->instance_type();
5072 ASSERT(0 <= type && type <= LAST_TYPE);
5073 stats->objects_per_type[type]++;
5074 stats->size_per_type[type] += obj->Size();
5080 intptr_t Heap::PromotedSpaceSize() {
5081 return old_pointer_space_->Size()
5082 + old_data_space_->Size()
5083 + code_space_->Size()
5084 + map_space_->Size()
5085 + cell_space_->Size()
5086 + lo_space_->Size();
5090 int Heap::PromotedExternalMemorySize() {
5091 if (amount_of_external_allocated_memory_
5092 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5093 return amount_of_external_allocated_memory_
5094 - amount_of_external_allocated_memory_at_last_global_gc_;
5099 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5100 static const int kMarkTag = 2;
5103 class HeapDebugUtils {
5105 explicit HeapDebugUtils(Heap* heap)
5106 : search_for_any_global_(false),
5107 search_target_(NULL),
5108 found_target_(false),
5113 class MarkObjectVisitor : public ObjectVisitor {
5115 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5117 void VisitPointers(Object** start, Object** end) {
5118 // Copy all HeapObject pointers in [start, end)
5119 for (Object** p = start; p < end; p++) {
5120 if ((*p)->IsHeapObject())
5121 utils_->MarkObjectRecursively(p);
5125 HeapDebugUtils* utils_;
5128 void MarkObjectRecursively(Object** p) {
5129 if (!(*p)->IsHeapObject()) return;
5131 HeapObject* obj = HeapObject::cast(*p);
5133 Object* map = obj->map();
5135 if (!map->IsHeapObject()) return; // visited before
5137 if (found_target_) return; // stop if target found
5138 object_stack_.Add(obj);
5139 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5140 (!search_for_any_global_ && (obj == search_target_))) {
5141 found_target_ = true;
5146 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5148 Address map_addr = map_p->address();
5150 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
5152 MarkObjectRecursively(&map);
5154 MarkObjectVisitor mark_visitor(this);
5156 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5159 if (!found_target_) // don't pop if found the target
5160 object_stack_.RemoveLast();
5164 class UnmarkObjectVisitor : public ObjectVisitor {
5166 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5168 void VisitPointers(Object** start, Object** end) {
5169 // Copy all HeapObject pointers in [start, end)
5170 for (Object** p = start; p < end; p++) {
5171 if ((*p)->IsHeapObject())
5172 utils_->UnmarkObjectRecursively(p);
5176 HeapDebugUtils* utils_;
5180 void UnmarkObjectRecursively(Object** p) {
5181 if (!(*p)->IsHeapObject()) return;
5183 HeapObject* obj = HeapObject::cast(*p);
5185 Object* map = obj->map();
5187 if (map->IsHeapObject()) return; // unmarked already
5189 Address map_addr = reinterpret_cast<Address>(map);
5191 map_addr -= kMarkTag;
5193 ASSERT_TAG_ALIGNED(map_addr);
5195 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5197 obj->set_map(reinterpret_cast<Map*>(map_p));
5199 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5201 UnmarkObjectVisitor unmark_visitor(this);
5203 obj->IterateBody(Map::cast(map_p)->instance_type(),
5204 obj->SizeFromMap(Map::cast(map_p)),
5209 void MarkRootObjectRecursively(Object** root) {
5210 if (search_for_any_global_) {
5211 ASSERT(search_target_ == NULL);
5213 ASSERT(search_target_->IsHeapObject());
5215 found_target_ = false;
5216 object_stack_.Clear();
5218 MarkObjectRecursively(root);
5219 UnmarkObjectRecursively(root);
5221 if (found_target_) {
5222 PrintF("=====================================\n");
5223 PrintF("==== Path to object ====\n");
5224 PrintF("=====================================\n\n");
5226 ASSERT(!object_stack_.is_empty());
5227 for (int i = 0; i < object_stack_.length(); i++) {
5228 if (i > 0) PrintF("\n |\n |\n V\n\n");
5229 Object* obj = object_stack_[i];
5232 PrintF("=====================================\n");
5236 // Helper class for visiting HeapObjects recursively.
5237 class MarkRootVisitor: public ObjectVisitor {
5239 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5241 void VisitPointers(Object** start, Object** end) {
5242 // Visit all HeapObject pointers in [start, end)
5243 for (Object** p = start; p < end; p++) {
5244 if ((*p)->IsHeapObject())
5245 utils_->MarkRootObjectRecursively(p);
5249 HeapDebugUtils* utils_;
5252 bool search_for_any_global_;
5253 Object* search_target_;
5255 List<Object*> object_stack_;
5263 bool Heap::Setup(bool create_heap_objects) {
5265 debug_utils_ = new HeapDebugUtils(this);
5268 // Initialize heap spaces and initial maps and objects. Whenever something
5269 // goes wrong, just return false. The caller should check the results and
5270 // call Heap::TearDown() to release allocated memory.
5272 // If the heap is not yet configured (eg, through the API), configure it.
5273 // Configuration is based on the flags new-space-size (really the semispace
5274 // size) and old-space-size if set or the initial values of semispace_size_
5275 // and old_generation_size_ otherwise.
5277 if (!ConfigureHeapDefault()) return false;
5280 gc_initializer_mutex->Lock();
5281 static bool initialized_gc = false;
5282 if (!initialized_gc) {
5283 initialized_gc = true;
5284 InitializeScavengingVisitorsTables();
5285 NewSpaceScavenger::Initialize();
5286 MarkCompactCollector::Initialize();
5288 gc_initializer_mutex->Unlock();
5290 MarkMapPointersAsEncoded(false);
5292 // Setup memory allocator and reserve a chunk of memory for new
5293 // space. The chunk is double the size of the requested reserved
5294 // new space size to ensure that we can find a pair of semispaces that
5295 // are contiguous and aligned to their size.
5296 if (!isolate_->memory_allocator()->Setup(MaxReserved(), MaxExecutableSize()))
5299 isolate_->memory_allocator()->ReserveInitialChunk(
5300 4 * reserved_semispace_size_);
5301 if (chunk == NULL) return false;
5303 // Align the pair of semispaces to their size, which must be a power
5305 Address new_space_start =
5306 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
5307 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
5311 // Initialize old pointer space.
5312 old_pointer_space_ =
5314 max_old_generation_size_,
5317 if (old_pointer_space_ == NULL) return false;
5318 if (!old_pointer_space_->Setup(NULL, 0)) return false;
5320 // Initialize old data space.
5323 max_old_generation_size_,
5326 if (old_data_space_ == NULL) return false;
5327 if (!old_data_space_->Setup(NULL, 0)) return false;
5329 // Initialize the code space, set its maximum capacity to the old
5330 // generation size. It needs executable memory.
5331 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5332 // virtual address space, so that they can call each other with near calls.
5333 if (code_range_size_ > 0) {
5334 if (!isolate_->code_range()->Setup(code_range_size_)) {
5340 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
5341 if (code_space_ == NULL) return false;
5342 if (!code_space_->Setup(NULL, 0)) return false;
5344 // Initialize map space.
5345 map_space_ = new MapSpace(this, FLAG_use_big_map_space
5346 ? max_old_generation_size_
5347 : MapSpace::kMaxMapPageIndex * Page::kPageSize,
5348 FLAG_max_map_space_pages,
5350 if (map_space_ == NULL) return false;
5351 if (!map_space_->Setup(NULL, 0)) return false;
5353 // Initialize global property cell space.
5354 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
5355 if (cell_space_ == NULL) return false;
5356 if (!cell_space_->Setup(NULL, 0)) return false;
5358 // The large object code space may contain code or data. We set the memory
5359 // to be non-executable here for safety, but this means we need to enable it
5360 // explicitly when allocating large code objects.
5361 lo_space_ = new LargeObjectSpace(this, LO_SPACE);
5362 if (lo_space_ == NULL) return false;
5363 if (!lo_space_->Setup()) return false;
5365 // Setup the seed that is used to randomize the string hash function.
5366 ASSERT(hash_seed() == 0);
5367 if (FLAG_randomize_hashes) {
5368 if (FLAG_hash_seed == 0) {
5370 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
5372 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5376 if (create_heap_objects) {
5377 // Create initial maps.
5378 if (!CreateInitialMaps()) return false;
5379 if (!CreateApiObjects()) return false;
5381 // Create initial objects
5382 if (!CreateInitialObjects()) return false;
5384 global_contexts_list_ = undefined_value();
5387 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5388 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
5394 void Heap::SetStackLimits() {
5395 ASSERT(isolate_ != NULL);
5396 ASSERT(isolate_ == isolate());
5397 // On 64 bit machines, pointers are generally out of range of Smis. We write
5398 // something that looks like an out of range Smi to the GC.
5400 // Set up the special root array entries containing the stack limits.
5401 // These are actually addresses, but the tag makes the GC ignore it.
5402 roots_[kStackLimitRootIndex] =
5403 reinterpret_cast<Object*>(
5404 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
5405 roots_[kRealStackLimitRootIndex] =
5406 reinterpret_cast<Object*>(
5407 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
5411 void Heap::TearDown() {
5412 if (FLAG_print_cumulative_gc_stat) {
5414 PrintF("gc_count=%d ", gc_count_);
5415 PrintF("mark_sweep_count=%d ", ms_count_);
5416 PrintF("mark_compact_count=%d ", mc_count_);
5417 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5418 PrintF("min_in_mutator=%d ", get_min_in_mutator());
5419 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
5420 get_max_alive_after_gc());
5424 isolate_->global_handles()->TearDown();
5426 external_string_table_.TearDown();
5428 new_space_.TearDown();
5430 if (old_pointer_space_ != NULL) {
5431 old_pointer_space_->TearDown();
5432 delete old_pointer_space_;
5433 old_pointer_space_ = NULL;
5436 if (old_data_space_ != NULL) {
5437 old_data_space_->TearDown();
5438 delete old_data_space_;
5439 old_data_space_ = NULL;
5442 if (code_space_ != NULL) {
5443 code_space_->TearDown();
5448 if (map_space_ != NULL) {
5449 map_space_->TearDown();
5454 if (cell_space_ != NULL) {
5455 cell_space_->TearDown();
5460 if (lo_space_ != NULL) {
5461 lo_space_->TearDown();
5466 isolate_->memory_allocator()->TearDown();
5469 delete debug_utils_;
5470 debug_utils_ = NULL;
5475 void Heap::Shrink() {
5476 // Try to shrink all paged spaces.
5478 for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next())
5483 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5484 ASSERT(callback != NULL);
5485 GCPrologueCallbackPair pair(callback, gc_type);
5486 ASSERT(!gc_prologue_callbacks_.Contains(pair));
5487 return gc_prologue_callbacks_.Add(pair);
5491 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5492 ASSERT(callback != NULL);
5493 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
5494 if (gc_prologue_callbacks_[i].callback == callback) {
5495 gc_prologue_callbacks_.Remove(i);
5503 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5504 ASSERT(callback != NULL);
5505 GCEpilogueCallbackPair pair(callback, gc_type);
5506 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
5507 return gc_epilogue_callbacks_.Add(pair);
5511 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5512 ASSERT(callback != NULL);
5513 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
5514 if (gc_epilogue_callbacks_[i].callback == callback) {
5515 gc_epilogue_callbacks_.Remove(i);
5525 class PrintHandleVisitor: public ObjectVisitor {
5527 void VisitPointers(Object** start, Object** end) {
5528 for (Object** p = start; p < end; p++)
5529 PrintF(" handle %p to %p\n",
5530 reinterpret_cast<void*>(p),
5531 reinterpret_cast<void*>(*p));
5535 void Heap::PrintHandles() {
5536 PrintF("Handles:\n");
5537 PrintHandleVisitor v;
5538 isolate_->handle_scope_implementer()->Iterate(&v);
5544 Space* AllSpaces::next() {
5545 switch (counter_++) {
5547 return HEAP->new_space();
5548 case OLD_POINTER_SPACE:
5549 return HEAP->old_pointer_space();
5550 case OLD_DATA_SPACE:
5551 return HEAP->old_data_space();
5553 return HEAP->code_space();
5555 return HEAP->map_space();
5557 return HEAP->cell_space();
5559 return HEAP->lo_space();
5566 PagedSpace* PagedSpaces::next() {
5567 switch (counter_++) {
5568 case OLD_POINTER_SPACE:
5569 return HEAP->old_pointer_space();
5570 case OLD_DATA_SPACE:
5571 return HEAP->old_data_space();
5573 return HEAP->code_space();
5575 return HEAP->map_space();
5577 return HEAP->cell_space();
5585 OldSpace* OldSpaces::next() {
5586 switch (counter_++) {
5587 case OLD_POINTER_SPACE:
5588 return HEAP->old_pointer_space();
5589 case OLD_DATA_SPACE:
5590 return HEAP->old_data_space();
5592 return HEAP->code_space();
5599 SpaceIterator::SpaceIterator()
5600 : current_space_(FIRST_SPACE),
5606 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
5607 : current_space_(FIRST_SPACE),
5609 size_func_(size_func) {
5613 SpaceIterator::~SpaceIterator() {
5614 // Delete active iterator if any.
5619 bool SpaceIterator::has_next() {
5620 // Iterate until no more spaces.
5621 return current_space_ != LAST_SPACE;
5625 ObjectIterator* SpaceIterator::next() {
5626 if (iterator_ != NULL) {
5629 // Move to the next space
5631 if (current_space_ > LAST_SPACE) {
5636 // Return iterator for the new current space.
5637 return CreateIterator();
5641 // Create an iterator for the space to iterate.
5642 ObjectIterator* SpaceIterator::CreateIterator() {
5643 ASSERT(iterator_ == NULL);
5645 switch (current_space_) {
5647 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
5649 case OLD_POINTER_SPACE:
5650 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
5652 case OLD_DATA_SPACE:
5653 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
5656 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
5659 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
5662 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
5665 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
5669 // Return the newly allocated iterator;
5670 ASSERT(iterator_ != NULL);
5675 class HeapObjectsFilter {
5677 virtual ~HeapObjectsFilter() {}
5678 virtual bool SkipObject(HeapObject* object) = 0;
5682 class FreeListNodesFilter : public HeapObjectsFilter {
5684 FreeListNodesFilter() {
5685 MarkFreeListNodes();
5688 bool SkipObject(HeapObject* object) {
5689 if (object->IsMarked()) {
5690 object->ClearMark();
5698 void MarkFreeListNodes() {
5700 heap->old_pointer_space()->MarkFreeListNodes();
5701 heap->old_data_space()->MarkFreeListNodes();
5702 MarkCodeSpaceFreeListNodes(heap);
5703 heap->map_space()->MarkFreeListNodes();
5704 heap->cell_space()->MarkFreeListNodes();
5707 void MarkCodeSpaceFreeListNodes(Heap* heap) {
5708 // For code space, using FreeListNode::IsFreeListNode is OK.
5709 HeapObjectIterator iter(heap->code_space());
5710 for (HeapObject* obj = iter.next_object();
5712 obj = iter.next_object()) {
5713 if (FreeListNode::IsFreeListNode(obj)) obj->SetMark();
5717 AssertNoAllocation no_alloc;
5721 class UnreachableObjectsFilter : public HeapObjectsFilter {
5723 UnreachableObjectsFilter() {
5724 MarkUnreachableObjects();
5727 bool SkipObject(HeapObject* object) {
5728 if (object->IsMarked()) {
5729 object->ClearMark();
5737 class UnmarkingVisitor : public ObjectVisitor {
5739 UnmarkingVisitor() : list_(10) {}
5741 void VisitPointers(Object** start, Object** end) {
5742 for (Object** p = start; p < end; p++) {
5743 if (!(*p)->IsHeapObject()) continue;
5744 HeapObject* obj = HeapObject::cast(*p);
5745 if (obj->IsMarked()) {
5752 bool can_process() { return !list_.is_empty(); }
5754 void ProcessNext() {
5755 HeapObject* obj = list_.RemoveLast();
5760 List<HeapObject*> list_;
5763 void MarkUnreachableObjects() {
5764 HeapIterator iterator;
5765 for (HeapObject* obj = iterator.next();
5767 obj = iterator.next()) {
5770 UnmarkingVisitor visitor;
5771 HEAP->IterateRoots(&visitor, VISIT_ALL);
5772 while (visitor.can_process())
5773 visitor.ProcessNext();
5776 AssertNoAllocation no_alloc;
5780 HeapIterator::HeapIterator()
5781 : filtering_(HeapIterator::kNoFiltering),
5787 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
5788 : filtering_(filtering),
5794 HeapIterator::~HeapIterator() {
5799 void HeapIterator::Init() {
5800 // Start the iteration.
5801 space_iterator_ = filtering_ == kNoFiltering ? new SpaceIterator :
5802 new SpaceIterator(MarkCompactCollector::SizeOfMarkedObject);
5803 switch (filtering_) {
5804 case kFilterFreeListNodes:
5805 filter_ = new FreeListNodesFilter;
5807 case kFilterUnreachable:
5808 filter_ = new UnreachableObjectsFilter;
5813 object_iterator_ = space_iterator_->next();
5817 void HeapIterator::Shutdown() {
5819 // Assert that in filtering mode we have iterated through all
5820 // objects. Otherwise, heap will be left in an inconsistent state.
5821 if (filtering_ != kNoFiltering) {
5822 ASSERT(object_iterator_ == NULL);
5825 // Make sure the last iterator is deallocated.
5826 delete space_iterator_;
5827 space_iterator_ = NULL;
5828 object_iterator_ = NULL;
5834 HeapObject* HeapIterator::next() {
5835 if (filter_ == NULL) return NextObject();
5837 HeapObject* obj = NextObject();
5838 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
5843 HeapObject* HeapIterator::NextObject() {
5844 // No iterator means we are done.
5845 if (object_iterator_ == NULL) return NULL;
5847 if (HeapObject* obj = object_iterator_->next_object()) {
5848 // If the current iterator has more objects we are fine.
5851 // Go though the spaces looking for one that has objects.
5852 while (space_iterator_->has_next()) {
5853 object_iterator_ = space_iterator_->next();
5854 if (HeapObject* obj = object_iterator_->next_object()) {
5859 // Done with the last space.
5860 object_iterator_ = NULL;
5865 void HeapIterator::reset() {
5866 // Restart the iterator.
5872 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
5874 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
5876 class PathTracer::MarkVisitor: public ObjectVisitor {
5878 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
5879 void VisitPointers(Object** start, Object** end) {
5880 // Scan all HeapObject pointers in [start, end)
5881 for (Object** p = start; !tracer_->found() && (p < end); p++) {
5882 if ((*p)->IsHeapObject())
5883 tracer_->MarkRecursively(p, this);
5888 PathTracer* tracer_;
5892 class PathTracer::UnmarkVisitor: public ObjectVisitor {
5894 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
5895 void VisitPointers(Object** start, Object** end) {
5896 // Scan all HeapObject pointers in [start, end)
5897 for (Object** p = start; p < end; p++) {
5898 if ((*p)->IsHeapObject())
5899 tracer_->UnmarkRecursively(p, this);
5904 PathTracer* tracer_;
5908 void PathTracer::VisitPointers(Object** start, Object** end) {
5909 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
5910 // Visit all HeapObject pointers in [start, end)
5911 for (Object** p = start; !done && (p < end); p++) {
5912 if ((*p)->IsHeapObject()) {
5914 done = ((what_to_find_ == FIND_FIRST) && found_target_);
5920 void PathTracer::Reset() {
5921 found_target_ = false;
5922 object_stack_.Clear();
5926 void PathTracer::TracePathFrom(Object** root) {
5927 ASSERT((search_target_ == kAnyGlobalObject) ||
5928 search_target_->IsHeapObject());
5929 found_target_in_trace_ = false;
5930 object_stack_.Clear();
5932 MarkVisitor mark_visitor(this);
5933 MarkRecursively(root, &mark_visitor);
5935 UnmarkVisitor unmark_visitor(this);
5936 UnmarkRecursively(root, &unmark_visitor);
5942 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
5943 if (!(*p)->IsHeapObject()) return;
5945 HeapObject* obj = HeapObject::cast(*p);
5947 Object* map = obj->map();
5949 if (!map->IsHeapObject()) return; // visited before
5951 if (found_target_in_trace_) return; // stop if target found
5952 object_stack_.Add(obj);
5953 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
5954 (obj == search_target_)) {
5955 found_target_in_trace_ = true;
5956 found_target_ = true;
5960 bool is_global_context = obj->IsGlobalContext();
5963 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5965 Address map_addr = map_p->address();
5967 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
5969 // Scan the object body.
5970 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
5971 // This is specialized to scan Context's properly.
5972 Object** start = reinterpret_cast<Object**>(obj->address() +
5973 Context::kHeaderSize);
5974 Object** end = reinterpret_cast<Object**>(obj->address() +
5975 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
5976 mark_visitor->VisitPointers(start, end);
5978 obj->IterateBody(map_p->instance_type(),
5979 obj->SizeFromMap(map_p),
5983 // Scan the map after the body because the body is a lot more interesting
5984 // when doing leak detection.
5985 MarkRecursively(&map, mark_visitor);
5987 if (!found_target_in_trace_) // don't pop if found the target
5988 object_stack_.RemoveLast();
5992 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
5993 if (!(*p)->IsHeapObject()) return;
5995 HeapObject* obj = HeapObject::cast(*p);
5997 Object* map = obj->map();
5999 if (map->IsHeapObject()) return; // unmarked already
6001 Address map_addr = reinterpret_cast<Address>(map);
6003 map_addr -= kMarkTag;
6005 ASSERT_TAG_ALIGNED(map_addr);
6007 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6009 obj->set_map(reinterpret_cast<Map*>(map_p));
6011 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6013 obj->IterateBody(Map::cast(map_p)->instance_type(),
6014 obj->SizeFromMap(Map::cast(map_p)),
6019 void PathTracer::ProcessResults() {
6020 if (found_target_) {
6021 PrintF("=====================================\n");
6022 PrintF("==== Path to object ====\n");
6023 PrintF("=====================================\n\n");
6025 ASSERT(!object_stack_.is_empty());
6026 for (int i = 0; i < object_stack_.length(); i++) {
6027 if (i > 0) PrintF("\n |\n |\n V\n\n");
6028 Object* obj = object_stack_[i];
6035 PrintF("=====================================\n");
6038 #endif // DEBUG || LIVE_OBJECT_LIST
6042 // Triggers a depth-first traversal of reachable objects from roots
6043 // and finds a path to a specific heap object and prints it.
6044 void Heap::TracePathToObject(Object* target) {
6045 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6046 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6050 // Triggers a depth-first traversal of reachable objects from roots
6051 // and finds a path to any global object and prints it. Useful for
6052 // determining the source for leaks of global objects.
6053 void Heap::TracePathToGlobal() {
6054 PathTracer tracer(PathTracer::kAnyGlobalObject,
6055 PathTracer::FIND_ALL,
6057 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6062 static intptr_t CountTotalHolesSize() {
6063 intptr_t holes_size = 0;
6065 for (OldSpace* space = spaces.next();
6067 space = spaces.next()) {
6068 holes_size += space->Waste() + space->AvailableFree();
6074 GCTracer::GCTracer(Heap* heap)
6079 is_compacting_(false),
6081 allocated_since_last_gc_(0),
6082 spent_in_mutator_(0),
6083 promoted_objects_size_(0),
6085 // These two fields reflect the state of the previous full collection.
6086 // Set them before they are changed by the collector.
6087 previous_has_compacted_ = heap_->mark_compact_collector_.HasCompacted();
6088 previous_marked_count_ =
6089 heap_->mark_compact_collector_.previous_marked_count();
6090 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6091 start_time_ = OS::TimeCurrentMillis();
6092 start_size_ = heap_->SizeOfObjects();
6094 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6098 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6100 allocated_since_last_gc_ =
6101 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6103 if (heap_->last_gc_end_timestamp_ > 0) {
6104 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6109 GCTracer::~GCTracer() {
6110 // Printf ONE line iff flag is set.
6111 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6113 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6115 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6116 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6118 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6120 // Update cumulative GC statistics if required.
6121 if (FLAG_print_cumulative_gc_stat) {
6122 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6123 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6124 heap_->alive_after_last_gc_);
6126 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6127 static_cast<int>(spent_in_mutator_));
6131 if (!FLAG_trace_gc_nvp) {
6132 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6134 PrintF("%s %.1f -> %.1f MB, ",
6136 static_cast<double>(start_size_) / MB,
6137 SizeOfHeapObjects());
6139 if (external_time > 0) PrintF("%d / ", external_time);
6140 PrintF("%d ms.\n", time);
6142 PrintF("pause=%d ", time);
6143 PrintF("mutator=%d ",
6144 static_cast<int>(spent_in_mutator_));
6147 switch (collector_) {
6151 case MARK_COMPACTOR:
6153 heap_->mark_compact_collector_.HasCompacted() ? "mc" : "ms");
6160 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6161 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6162 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6163 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6164 PrintF("compact=%d ", static_cast<int>(scopes_[Scope::MC_COMPACT]));
6166 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_size_);
6167 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6168 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6169 in_free_list_or_wasted_before_gc_);
6170 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6172 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6173 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6178 heap_->PrintShortHeapStatistics();
6182 const char* GCTracer::CollectorString() {
6183 switch (collector_) {
6186 case MARK_COMPACTOR:
6187 return heap_->mark_compact_collector_.HasCompacted() ? "Mark-compact"
6190 return "Unknown GC";
6194 int KeyedLookupCache::Hash(Map* map, String* name) {
6195 // Uses only lower 32 bits if pointers are larger.
6196 uintptr_t addr_hash =
6197 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6198 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6202 int KeyedLookupCache::Lookup(Map* map, String* name) {
6203 int index = Hash(map, name);
6204 Key& key = keys_[index];
6205 if ((key.map == map) && key.name->Equals(name)) {
6206 return field_offsets_[index];
6212 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6214 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
6215 int index = Hash(map, symbol);
6216 Key& key = keys_[index];
6219 field_offsets_[index] = field_offset;
6224 void KeyedLookupCache::Clear() {
6225 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6229 void DescriptorLookupCache::Clear() {
6230 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6235 void Heap::GarbageCollectionGreedyCheck() {
6236 ASSERT(FLAG_gc_greedy);
6237 if (isolate_->bootstrapper()->IsActive()) return;
6238 if (disallow_allocation_failure()) return;
6239 CollectGarbage(NEW_SPACE);
6244 TranscendentalCache::SubCache::SubCache(Type t)
6246 isolate_(Isolate::Current()) {
6247 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6248 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6249 for (int i = 0; i < kCacheSize; i++) {
6250 elements_[i].in[0] = in0;
6251 elements_[i].in[1] = in1;
6252 elements_[i].output = NULL;
6257 void TranscendentalCache::Clear() {
6258 for (int i = 0; i < kNumberOfCaches; i++) {
6259 if (caches_[i] != NULL) {
6267 void ExternalStringTable::CleanUp() {
6269 for (int i = 0; i < new_space_strings_.length(); ++i) {
6270 if (new_space_strings_[i] == heap_->raw_unchecked_null_value()) continue;
6271 if (heap_->InNewSpace(new_space_strings_[i])) {
6272 new_space_strings_[last++] = new_space_strings_[i];
6274 old_space_strings_.Add(new_space_strings_[i]);
6277 new_space_strings_.Rewind(last);
6279 for (int i = 0; i < old_space_strings_.length(); ++i) {
6280 if (old_space_strings_[i] == heap_->raw_unchecked_null_value()) continue;
6281 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
6282 old_space_strings_[last++] = old_space_strings_[i];
6284 old_space_strings_.Rewind(last);
6289 void ExternalStringTable::TearDown() {
6290 new_space_strings_.Free();
6291 old_space_strings_.Free();
6295 } } // namespace v8::internal