blob: ba26c1d7fc15fae0abfa0312506bc580dfc55c99 [file] [log] [blame]
Ben Murdochc7cc0282012-03-05 14:35:55 +00001// Copyright 2012 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
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.
15//
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.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
Ben Murdoch8b112d22011-06-08 16:22:53 +010033#include "codegen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000034#include "compilation-cache.h"
35#include "debug.h"
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000036#include "deoptimizer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000037#include "global-handles.h"
Ben Murdoch257744e2011-11-30 15:57:28 +000038#include "heap-profiler.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000039#include "incremental-marking.h"
Steve Block1e0659c2011-05-24 12:43:12 +010040#include "liveobjectlist-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000041#include "mark-compact.h"
42#include "natives.h"
Iain Merrick75681382010-08-19 15:07:18 +010043#include "objects-visiting.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000044#include "objects-visiting-inl.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010045#include "runtime-profiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000046#include "scopeinfo.h"
Steve Block3ce2e202009-11-05 08:53:23 +000047#include "snapshot.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000048#include "store-buffer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000049#include "v8threads.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010050#include "vm-state-inl.h"
Steve Block6ded16b2010-05-10 14:33:55 +010051#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000052#include "regexp-macro-assembler.h"
Steve Blockd0582a62009-12-15 09:54:21 +000053#include "arm/regexp-macro-assembler-arm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000054#endif
Steve Block44f0eee2011-05-26 01:26:41 +010055#if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
56#include "regexp-macro-assembler.h"
57#include "mips/regexp-macro-assembler-mips.h"
58#endif
Steve Block6ded16b2010-05-10 14:33:55 +010059
Steve Blocka7e24c12009-10-30 11:49:00 +000060namespace v8 {
61namespace internal {
62
63
Steve Block44f0eee2011-05-26 01:26:41 +010064static Mutex* gc_initializer_mutex = OS::CreateMutex();
Steve Blocka7e24c12009-10-30 11:49:00 +000065
Steve Blocka7e24c12009-10-30 11:49:00 +000066
Steve Block44f0eee2011-05-26 01:26:41 +010067Heap::Heap()
68 : isolate_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +000069// semispace_size_ should be a power of 2 and old_generation_size_ should be
70// a multiple of Page::kPageSize.
Ben Murdoch589d6972011-11-30 16:04:58 +000071#if defined(ANDROID)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000072#define LUMP_OF_MEMORY (128 * KB)
Steve Block44f0eee2011-05-26 01:26:41 +010073 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000074#elif defined(V8_TARGET_ARCH_X64)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000075#define LUMP_OF_MEMORY (2 * MB)
Steve Block44f0eee2011-05-26 01:26:41 +010076 code_range_size_(512*MB),
Steve Blocka7e24c12009-10-30 11:49:00 +000077#else
Ben Murdoch592a9fc2012-03-05 11:04:45 +000078#define LUMP_OF_MEMORY MB
Steve Block44f0eee2011-05-26 01:26:41 +010079 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000080#endif
Ben Murdoch592a9fc2012-03-05 11:04:45 +000081 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
82 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
Ben Murdochc7cc0282012-03-05 14:35:55 +000083 initial_semispace_size_(Page::kPageSize),
Ben Murdoch592a9fc2012-03-05 11:04:45 +000084 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
85 max_executable_size_(128l * LUMP_OF_MEMORY),
86
Steve Blocka7e24c12009-10-30 11:49:00 +000087// Variables set based on semispace_size_ and old_generation_size_ in
Steve Block44f0eee2011-05-26 01:26:41 +010088// ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
Steve Block3ce2e202009-11-05 08:53:23 +000089// Will be 4 * reserved_semispace_size_ to ensure that young
90// generation can be aligned to its size.
Steve Block44f0eee2011-05-26 01:26:41 +010091 survived_since_last_expansion_(0),
Ben Murdoch257744e2011-11-30 15:57:28 +000092 sweep_generation_(0),
Steve Block44f0eee2011-05-26 01:26:41 +010093 always_allocate_scope_depth_(0),
94 linear_allocation_scope_depth_(0),
95 contexts_disposed_(0),
Ben Murdoch592a9fc2012-03-05 11:04:45 +000096 scan_on_scavenge_pages_(0),
Steve Block44f0eee2011-05-26 01:26:41 +010097 new_space_(this),
98 old_pointer_space_(NULL),
99 old_data_space_(NULL),
100 code_space_(NULL),
101 map_space_(NULL),
102 cell_space_(NULL),
103 lo_space_(NULL),
104 gc_state_(NOT_IN_GC),
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000105 gc_post_processing_depth_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100106 ms_count_(0),
107 gc_count_(0),
108 unflattened_strings_length_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000109#ifdef DEBUG
Steve Block44f0eee2011-05-26 01:26:41 +0100110 allocation_allowed_(true),
111 allocation_timeout_(0),
112 disallow_allocation_failure_(false),
113 debug_utils_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +0000114#endif // DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000115 new_space_high_promotion_mode_active_(false),
Steve Block44f0eee2011-05-26 01:26:41 +0100116 old_gen_promotion_limit_(kMinimumPromotionLimit),
117 old_gen_allocation_limit_(kMinimumAllocationLimit),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000118 old_gen_limit_factor_(1),
119 size_of_old_gen_at_last_old_space_gc_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100120 external_allocation_limit_(0),
121 amount_of_external_allocated_memory_(0),
122 amount_of_external_allocated_memory_at_last_global_gc_(0),
123 old_gen_exhausted_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000124 store_buffer_rebuilder_(store_buffer()),
Steve Block44f0eee2011-05-26 01:26:41 +0100125 hidden_symbol_(NULL),
126 global_gc_prologue_callback_(NULL),
127 global_gc_epilogue_callback_(NULL),
128 gc_safe_size_of_old_object_(NULL),
Steve Block053d10c2011-06-13 19:13:29 +0100129 total_regexp_code_generated_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100130 tracer_(NULL),
131 young_survivors_after_last_gc_(0),
132 high_survival_rate_period_length_(0),
133 survival_rate_(0),
134 previous_survival_rate_trend_(Heap::STABLE),
135 survival_rate_trend_(Heap::STABLE),
136 max_gc_pause_(0),
137 max_alive_after_gc_(0),
138 min_in_mutator_(kMaxInt),
139 alive_after_last_gc_(0),
140 last_gc_end_timestamp_(0.0),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000141 store_buffer_(this),
142 marking_(this),
143 incremental_marking_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100144 number_idle_notifications_(0),
145 last_idle_notification_gc_count_(0),
146 last_idle_notification_gc_count_init_(false),
Ben Murdochc7cc0282012-03-05 14:35:55 +0000147 idle_notification_will_schedule_next_gc_(false),
148 mark_sweeps_since_idle_round_started_(0),
149 ms_count_at_last_idle_notification_(0),
150 gc_count_at_last_idle_gc_(0),
151 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000152 promotion_queue_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100153 configured_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000154 chunks_queued_for_free_(NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +0100155 // Allow build-time customization of the max semispace size. Building
156 // V8 with snapshots and a non-default max semispace size is much
157 // easier if you can define it as part of the build environment.
158#if defined(V8_MAX_SEMISPACE_SIZE)
159 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
160#endif
Steve Blocka7e24c12009-10-30 11:49:00 +0000161
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000162 intptr_t max_virtual = OS::MaxVirtualMemory();
163
164 if (max_virtual > 0) {
165 if (code_range_size_ > 0) {
166 // Reserve no more than 1/8 of the memory for the code range.
167 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
168 }
169 }
170
Steve Block44f0eee2011-05-26 01:26:41 +0100171 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
172 global_contexts_list_ = NULL;
173 mark_compact_collector_.heap_ = this;
174 external_string_table_.heap_ = this;
175}
176
Steve Blocka7e24c12009-10-30 11:49:00 +0000177
Ben Murdochf87a2032010-10-22 12:50:53 +0100178intptr_t Heap::Capacity() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000179 if (!HasBeenSetUp()) return 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000180
181 return new_space_.Capacity() +
182 old_pointer_space_->Capacity() +
183 old_data_space_->Capacity() +
184 code_space_->Capacity() +
185 map_space_->Capacity() +
186 cell_space_->Capacity();
187}
188
189
Ben Murdochf87a2032010-10-22 12:50:53 +0100190intptr_t Heap::CommittedMemory() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000191 if (!HasBeenSetUp()) return 0;
Steve Block3ce2e202009-11-05 08:53:23 +0000192
193 return new_space_.CommittedMemory() +
194 old_pointer_space_->CommittedMemory() +
195 old_data_space_->CommittedMemory() +
196 code_space_->CommittedMemory() +
197 map_space_->CommittedMemory() +
198 cell_space_->CommittedMemory() +
199 lo_space_->Size();
200}
201
Russell Brenner90bac252010-11-18 13:33:46 -0800202intptr_t Heap::CommittedMemoryExecutable() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000203 if (!HasBeenSetUp()) return 0;
Russell Brenner90bac252010-11-18 13:33:46 -0800204
Steve Block44f0eee2011-05-26 01:26:41 +0100205 return isolate()->memory_allocator()->SizeExecutable();
Russell Brenner90bac252010-11-18 13:33:46 -0800206}
207
Steve Block3ce2e202009-11-05 08:53:23 +0000208
Ben Murdochf87a2032010-10-22 12:50:53 +0100209intptr_t Heap::Available() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000210 if (!HasBeenSetUp()) return 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000211
212 return new_space_.Available() +
213 old_pointer_space_->Available() +
214 old_data_space_->Available() +
215 code_space_->Available() +
216 map_space_->Available() +
217 cell_space_->Available();
218}
219
220
Ben Murdochc7cc0282012-03-05 14:35:55 +0000221bool Heap::HasBeenSetUp() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000222 return old_pointer_space_ != NULL &&
223 old_data_space_ != NULL &&
224 code_space_ != NULL &&
225 map_space_ != NULL &&
226 cell_space_ != NULL &&
227 lo_space_ != NULL;
228}
229
230
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100231int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000232 if (IntrusiveMarking::IsMarked(object)) {
233 return IntrusiveMarking::SizeOfMarkedObject(object);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100234 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000235 return object->SizeFromMap(object->map());
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100236}
237
238
Steve Blocka7e24c12009-10-30 11:49:00 +0000239GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
240 // Is global GC requested?
241 if (space != NEW_SPACE || FLAG_gc_global) {
Steve Block44f0eee2011-05-26 01:26:41 +0100242 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000243 return MARK_COMPACTOR;
244 }
245
246 // Is enough data promoted to justify a global GC?
247 if (OldGenerationPromotionLimitReached()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100248 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000249 return MARK_COMPACTOR;
250 }
251
252 // Have allocation in OLD and LO failed?
253 if (old_gen_exhausted_) {
Steve Block44f0eee2011-05-26 01:26:41 +0100254 isolate_->counters()->
255 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000256 return MARK_COMPACTOR;
257 }
258
259 // Is there enough space left in OLD to guarantee that a scavenge can
260 // succeed?
261 //
262 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
263 // for object promotion. It counts only the bytes that the memory
264 // allocator has not yet allocated from the OS and assigned to any space,
265 // and does not count available bytes already in the old space or code
266 // space. Undercounting is safe---we may get an unrequested full GC when
267 // a scavenge would have succeeded.
Steve Block44f0eee2011-05-26 01:26:41 +0100268 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
269 isolate_->counters()->
270 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000271 return MARK_COMPACTOR;
272 }
273
274 // Default
275 return SCAVENGER;
276}
277
278
279// TODO(1238405): Combine the infrastructure for --heap-stats and
280// --log-gc to avoid the complicated preprocessor and flag testing.
Steve Blocka7e24c12009-10-30 11:49:00 +0000281void Heap::ReportStatisticsBeforeGC() {
282 // Heap::ReportHeapStatistics will also log NewSpace statistics when
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000283 // compiled --log-gc is set. The following logic is used to avoid
284 // double logging.
285#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
287 if (FLAG_heap_stats) {
288 ReportHeapStatistics("Before GC");
289 } else if (FLAG_log_gc) {
290 new_space_.ReportStatistics();
291 }
292 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000293#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000294 if (FLAG_log_gc) {
295 new_space_.CollectStatistics();
296 new_space_.ReportStatistics();
297 new_space_.ClearHistograms();
298 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000299#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000300}
301
302
Steve Blocka7e24c12009-10-30 11:49:00 +0000303void Heap::PrintShortHeapStatistics() {
304 if (!FLAG_trace_gc_verbose) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100305 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
306 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block44f0eee2011-05-26 01:26:41 +0100307 isolate_->memory_allocator()->Size(),
308 isolate_->memory_allocator()->Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100309 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
310 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000311 Heap::new_space_.Size(),
312 new_space_.Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100313 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
314 ", available: %8" V8_PTR_PREFIX "d"
315 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000316 old_pointer_space_->Size(),
317 old_pointer_space_->Available(),
318 old_pointer_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100319 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
320 ", available: %8" V8_PTR_PREFIX "d"
321 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000322 old_data_space_->Size(),
323 old_data_space_->Available(),
324 old_data_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100325 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
326 ", available: %8" V8_PTR_PREFIX "d"
327 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000328 code_space_->Size(),
329 code_space_->Available(),
330 code_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100331 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
332 ", available: %8" V8_PTR_PREFIX "d"
333 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000334 map_space_->Size(),
335 map_space_->Available(),
336 map_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100337 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
338 ", available: %8" V8_PTR_PREFIX "d"
339 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000340 cell_space_->Size(),
341 cell_space_->Available(),
342 cell_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100343 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
344 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000345 lo_space_->Size(),
346 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000347}
Steve Blocka7e24c12009-10-30 11:49:00 +0000348
349
350// TODO(1238405): Combine the infrastructure for --heap-stats and
351// --log-gc to avoid the complicated preprocessor and flag testing.
352void Heap::ReportStatisticsAfterGC() {
353 // Similar to the before GC, we use some complicated logic to ensure that
354 // NewSpace statistics are logged exactly once when --log-gc is turned on.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000355#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 if (FLAG_heap_stats) {
357 new_space_.CollectStatistics();
358 ReportHeapStatistics("After GC");
359 } else if (FLAG_log_gc) {
360 new_space_.ReportStatistics();
361 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000362#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000363 if (FLAG_log_gc) new_space_.ReportStatistics();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000364#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000365}
Steve Blocka7e24c12009-10-30 11:49:00 +0000366
367
368void Heap::GarbageCollectionPrologue() {
Steve Block44f0eee2011-05-26 01:26:41 +0100369 isolate_->transcendental_cache()->Clear();
Steve Block6ded16b2010-05-10 14:33:55 +0100370 ClearJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000371 gc_count_++;
Steve Block6ded16b2010-05-10 14:33:55 +0100372 unflattened_strings_length_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000373#ifdef DEBUG
374 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
375 allow_allocation(false);
376
377 if (FLAG_verify_heap) {
378 Verify();
379 }
380
381 if (FLAG_gc_verbose) Print();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000382#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000383
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000384#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000385 ReportStatisticsBeforeGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000386#endif // DEBUG
Steve Block1e0659c2011-05-24 12:43:12 +0100387
388 LiveObjectList::GCPrologue();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000389 store_buffer()->GCPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000390}
391
Ben Murdochf87a2032010-10-22 12:50:53 +0100392intptr_t Heap::SizeOfObjects() {
393 intptr_t total = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000394 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +0000395 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800396 total += space->SizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +0000397 }
398 return total;
399}
400
401void Heap::GarbageCollectionEpilogue() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000402 store_buffer()->GCEpilogue();
Steve Block1e0659c2011-05-24 12:43:12 +0100403 LiveObjectList::GCEpilogue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000404#ifdef DEBUG
405 allow_allocation(true);
406 ZapFromSpace();
407
408 if (FLAG_verify_heap) {
409 Verify();
410 }
411
Steve Block44f0eee2011-05-26 01:26:41 +0100412 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +0000413 if (FLAG_print_handles) PrintHandles();
414 if (FLAG_gc_verbose) Print();
415 if (FLAG_code_stats) ReportCodeStatistics("After GC");
416#endif
417
Steve Block44f0eee2011-05-26 01:26:41 +0100418 isolate_->counters()->alive_after_last_gc()->Set(
419 static_cast<int>(SizeOfObjects()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000420
Steve Block44f0eee2011-05-26 01:26:41 +0100421 isolate_->counters()->symbol_table_capacity()->Set(
422 symbol_table()->Capacity());
423 isolate_->counters()->number_of_symbols()->Set(
424 symbol_table()->NumberOfElements());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000425#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000426 ReportStatisticsAfterGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000427#endif // DEBUG
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000428#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +0100429 isolate_->debug()->AfterGarbageCollection();
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000430#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +0000431}
432
433
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000434void Heap::CollectAllGarbage(int flags) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000435 // Since we are ignoring the return value, the exact choice of space does
436 // not matter, so long as we do not specify NEW_SPACE, which would not
437 // cause a full GC.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000438 mark_compact_collector_.SetFlags(flags);
John Reck59135872010-11-02 12:39:01 -0700439 CollectGarbage(OLD_POINTER_SPACE);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000440 mark_compact_collector_.SetFlags(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000441}
442
443
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800444void Heap::CollectAllAvailableGarbage() {
445 // Since we are ignoring the return value, the exact choice of space does
446 // not matter, so long as we do not specify NEW_SPACE, which would not
447 // cause a full GC.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800448 // Major GC would invoke weak handle callbacks on weakly reachable
449 // handles, but won't collect weakly reachable objects until next
450 // major GC. Therefore if we collect aggressively and weak handle callback
451 // has been invoked, we rerun major GC to release objects which become
452 // garbage.
453 // Note: as weak callbacks can execute arbitrary code, we cannot
454 // hope that eventually there will be no weak callbacks invocations.
455 // Therefore stop recollecting after several attempts.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000456 mark_compact_collector()->SetFlags(kMakeHeapIterableMask);
457 isolate_->compilation_cache()->Clear();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800458 const int kMaxNumberOfAttempts = 7;
459 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
460 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR)) {
461 break;
462 }
463 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000464 mark_compact_collector()->SetFlags(kNoGCFlags);
465 new_space_.Shrink();
Ben Murdochc7cc0282012-03-05 14:35:55 +0000466 UncommitFromSpace();
467 Shrink();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000468 incremental_marking()->UncommitMarkingDeque();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800469}
470
471
472bool Heap::CollectGarbage(AllocationSpace space, GarbageCollector collector) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000473 // The VM is in the GC state until exiting this function.
Steve Block44f0eee2011-05-26 01:26:41 +0100474 VMState state(isolate_, GC);
Steve Blocka7e24c12009-10-30 11:49:00 +0000475
476#ifdef DEBUG
477 // Reset the allocation timeout to the GC interval, but make sure to
478 // allow at least a few allocations after a collection. The reason
479 // for this is that we have a lot of allocation sequences and we
480 // assume that a garbage collection will allow the subsequent
481 // allocation attempts to go through.
482 allocation_timeout_ = Max(6, FLAG_gc_interval);
483#endif
484
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000485 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
486 if (FLAG_trace_incremental_marking) {
487 PrintF("[IncrementalMarking] Scavenge during marking.\n");
488 }
489 }
490
491 if (collector == MARK_COMPACTOR &&
492 !mark_compact_collector()->PreciseSweepingRequired() &&
493 !incremental_marking()->IsStopped() &&
494 !incremental_marking()->should_hurry() &&
495 FLAG_incremental_marking_steps) {
496 if (FLAG_trace_incremental_marking) {
497 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
498 }
499 collector = SCAVENGER;
500 }
501
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800502 bool next_gc_likely_to_collect_more = false;
503
Steve Block44f0eee2011-05-26 01:26:41 +0100504 { GCTracer tracer(this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000505 GarbageCollectionPrologue();
506 // The GC count was incremented in the prologue. Tell the tracer about
507 // it.
508 tracer.set_gc_count(gc_count_);
509
Steve Blocka7e24c12009-10-30 11:49:00 +0000510 // Tell the tracer which collector we've selected.
511 tracer.set_collector(collector);
512
513 HistogramTimer* rate = (collector == SCAVENGER)
Steve Block44f0eee2011-05-26 01:26:41 +0100514 ? isolate_->counters()->gc_scavenger()
515 : isolate_->counters()->gc_compactor();
Steve Blocka7e24c12009-10-30 11:49:00 +0000516 rate->Start();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800517 next_gc_likely_to_collect_more =
518 PerformGarbageCollection(collector, &tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000519 rate->Stop();
520
521 GarbageCollectionEpilogue();
522 }
523
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000524 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
525 if (incremental_marking()->IsStopped()) {
526 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
527 incremental_marking()->Start();
528 }
529 }
530
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800531 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000532}
533
534
535void Heap::PerformScavenge() {
Steve Block44f0eee2011-05-26 01:26:41 +0100536 GCTracer tracer(this);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000537 if (incremental_marking()->IsStopped()) {
538 PerformGarbageCollection(SCAVENGER, &tracer);
539 } else {
540 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
541 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000542}
543
544
545#ifdef DEBUG
546// Helper class for verifying the symbol table.
547class SymbolTableVerifier : public ObjectVisitor {
548 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 void VisitPointers(Object** start, Object** end) {
550 // Visit all HeapObject pointers in [start, end).
551 for (Object** p = start; p < end; p++) {
552 if ((*p)->IsHeapObject()) {
553 // Check that the symbol is actually a symbol.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000554 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
Steve Blocka7e24c12009-10-30 11:49:00 +0000555 }
556 }
557 }
558};
559#endif // DEBUG
560
561
562static void VerifySymbolTable() {
563#ifdef DEBUG
564 SymbolTableVerifier verifier;
Steve Block44f0eee2011-05-26 01:26:41 +0100565 HEAP->symbol_table()->IterateElements(&verifier);
Steve Blocka7e24c12009-10-30 11:49:00 +0000566#endif // DEBUG
567}
568
569
Leon Clarkee46be812010-01-19 14:06:41 +0000570void Heap::ReserveSpace(
571 int new_space_size,
572 int pointer_space_size,
573 int data_space_size,
574 int code_space_size,
575 int map_space_size,
576 int cell_space_size,
577 int large_object_size) {
578 NewSpace* new_space = Heap::new_space();
579 PagedSpace* old_pointer_space = Heap::old_pointer_space();
580 PagedSpace* old_data_space = Heap::old_data_space();
581 PagedSpace* code_space = Heap::code_space();
582 PagedSpace* map_space = Heap::map_space();
583 PagedSpace* cell_space = Heap::cell_space();
584 LargeObjectSpace* lo_space = Heap::lo_space();
585 bool gc_performed = true;
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000586 int counter = 0;
587 static const int kThreshold = 20;
588 while (gc_performed && counter++ < kThreshold) {
Leon Clarkee46be812010-01-19 14:06:41 +0000589 gc_performed = false;
590 if (!new_space->ReserveSpace(new_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100591 Heap::CollectGarbage(NEW_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000592 gc_performed = true;
593 }
594 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100595 Heap::CollectGarbage(OLD_POINTER_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000596 gc_performed = true;
597 }
598 if (!(old_data_space->ReserveSpace(data_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100599 Heap::CollectGarbage(OLD_DATA_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000600 gc_performed = true;
601 }
602 if (!(code_space->ReserveSpace(code_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100603 Heap::CollectGarbage(CODE_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000604 gc_performed = true;
605 }
606 if (!(map_space->ReserveSpace(map_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100607 Heap::CollectGarbage(MAP_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000608 gc_performed = true;
609 }
610 if (!(cell_space->ReserveSpace(cell_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100611 Heap::CollectGarbage(CELL_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000612 gc_performed = true;
613 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100614 // We add a slack-factor of 2 in order to have space for a series of
615 // large-object allocations that are only just larger than the page size.
Leon Clarkee46be812010-01-19 14:06:41 +0000616 large_object_size *= 2;
617 // The ReserveSpace method on the large object space checks how much
618 // we can expand the old generation. This includes expansion caused by
619 // allocation in the other spaces.
620 large_object_size += cell_space_size + map_space_size + code_space_size +
621 data_space_size + pointer_space_size;
622 if (!(lo_space->ReserveSpace(large_object_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100623 Heap::CollectGarbage(LO_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000624 gc_performed = true;
625 }
626 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000627
628 if (gc_performed) {
629 // Failed to reserve the space after several attempts.
630 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
631 }
Leon Clarkee46be812010-01-19 14:06:41 +0000632}
633
634
Steve Blocka7e24c12009-10-30 11:49:00 +0000635void Heap::EnsureFromSpaceIsCommitted() {
636 if (new_space_.CommitFromSpaceIfNeeded()) return;
637
638 // Committing memory to from space failed.
639 // Try shrinking and try again.
640 Shrink();
641 if (new_space_.CommitFromSpaceIfNeeded()) return;
642
643 // Committing memory to from space failed again.
644 // Memory is exhausted and we will die.
645 V8::FatalProcessOutOfMemory("Committing semi space failed.");
646}
647
648
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800649void Heap::ClearJSFunctionResultCaches() {
Steve Block44f0eee2011-05-26 01:26:41 +0100650 if (isolate_->bootstrapper()->IsActive()) return;
Steve Block6ded16b2010-05-10 14:33:55 +0100651
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800652 Object* context = global_contexts_list_;
653 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000654 // Get the caches for this context. GC can happen when the context
655 // is not fully initialized, so the caches can be undefined.
656 Object* caches_or_undefined =
657 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
658 if (!caches_or_undefined->IsUndefined()) {
659 FixedArray* caches = FixedArray::cast(caches_or_undefined);
660 // Clear the caches:
661 int length = caches->length();
662 for (int i = 0; i < length; i++) {
663 JSFunctionResultCache::cast(caches->get(i))->Clear();
664 }
Steve Block6ded16b2010-05-10 14:33:55 +0100665 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800666 // Get the next context:
667 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
Steve Block6ded16b2010-05-10 14:33:55 +0100668 }
Steve Block6ded16b2010-05-10 14:33:55 +0100669}
670
671
Steve Block44f0eee2011-05-26 01:26:41 +0100672
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100673void Heap::ClearNormalizedMapCaches() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000674 if (isolate_->bootstrapper()->IsActive() &&
675 !incremental_marking()->IsMarking()) {
676 return;
677 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100678
679 Object* context = global_contexts_list_;
680 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000681 // GC can happen when the context is not fully initialized,
682 // so the cache can be undefined.
683 Object* cache =
684 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
685 if (!cache->IsUndefined()) {
686 NormalizedMapCache::cast(cache)->Clear();
687 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100688 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
689 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100690}
691
692
Steve Block8defd9f2010-07-08 12:39:36 +0100693void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
694 double survival_rate =
695 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
696 start_new_space_size;
697
Ben Murdochc7cc0282012-03-05 14:35:55 +0000698 if (survival_rate > kYoungSurvivalRateHighThreshold) {
Steve Block8defd9f2010-07-08 12:39:36 +0100699 high_survival_rate_period_length_++;
700 } else {
701 high_survival_rate_period_length_ = 0;
702 }
703
Ben Murdochc7cc0282012-03-05 14:35:55 +0000704 if (survival_rate < kYoungSurvivalRateLowThreshold) {
705 low_survival_rate_period_length_++;
706 } else {
707 low_survival_rate_period_length_ = 0;
708 }
709
Steve Block8defd9f2010-07-08 12:39:36 +0100710 double survival_rate_diff = survival_rate_ - survival_rate;
711
712 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
713 set_survival_rate_trend(DECREASING);
714 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
715 set_survival_rate_trend(INCREASING);
716 } else {
717 set_survival_rate_trend(STABLE);
718 }
719
720 survival_rate_ = survival_rate;
721}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100722
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800723bool Heap::PerformGarbageCollection(GarbageCollector collector,
John Reck59135872010-11-02 12:39:01 -0700724 GCTracer* tracer) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800725 bool next_gc_likely_to_collect_more = false;
726
Ben Murdochf87a2032010-10-22 12:50:53 +0100727 if (collector != SCAVENGER) {
Steve Block44f0eee2011-05-26 01:26:41 +0100728 PROFILE(isolate_, CodeMovingGCEvent());
Ben Murdochf87a2032010-10-22 12:50:53 +0100729 }
730
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000731 if (FLAG_verify_heap) {
732 VerifySymbolTable();
733 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000734 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
735 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100736 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000737 global_gc_prologue_callback_();
738 }
Steve Block6ded16b2010-05-10 14:33:55 +0100739
740 GCType gc_type =
741 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
742
743 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
744 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
745 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
746 }
747 }
748
Steve Blocka7e24c12009-10-30 11:49:00 +0000749 EnsureFromSpaceIsCommitted();
Steve Block6ded16b2010-05-10 14:33:55 +0100750
Ben Murdochf87a2032010-10-22 12:50:53 +0100751 int start_new_space_size = Heap::new_space()->SizeAsInt();
Steve Block8defd9f2010-07-08 12:39:36 +0100752
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000753 if (IsHighSurvivalRate()) {
754 // We speed up the incremental marker if it is running so that it
755 // does not fall behind the rate of promotion, which would cause a
756 // constantly growing old space.
757 incremental_marking()->NotifyOfHighPromotionRate();
758 }
759
Steve Blocka7e24c12009-10-30 11:49:00 +0000760 if (collector == MARK_COMPACTOR) {
Steve Block6ded16b2010-05-10 14:33:55 +0100761 // Perform mark-sweep with optional compaction.
Steve Blocka7e24c12009-10-30 11:49:00 +0000762 MarkCompact(tracer);
Ben Murdoch257744e2011-11-30 15:57:28 +0000763 sweep_generation_++;
Steve Block8defd9f2010-07-08 12:39:36 +0100764 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
765 IsStableOrIncreasingSurvivalTrend();
766
767 UpdateSurvivalRateTrend(start_new_space_size);
768
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000769 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSize();
Steve Block8defd9f2010-07-08 12:39:36 +0100770
John Reck59135872010-11-02 12:39:01 -0700771 if (high_survival_rate_during_scavenges &&
772 IsStableOrIncreasingSurvivalTrend()) {
773 // Stable high survival rates of young objects both during partial and
774 // full collection indicate that mutator is either building or modifying
775 // a structure with a long lifetime.
776 // In this case we aggressively raise old generation memory limits to
777 // postpone subsequent mark-sweep collection and thus trade memory
778 // space for the mutation speed.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000779 old_gen_limit_factor_ = 2;
780 } else {
781 old_gen_limit_factor_ = 1;
Steve Block8defd9f2010-07-08 12:39:36 +0100782 }
783
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000784 old_gen_promotion_limit_ =
785 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
786 old_gen_allocation_limit_ =
787 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
788
John Reck59135872010-11-02 12:39:01 -0700789 old_gen_exhausted_ = false;
Steve Block6ded16b2010-05-10 14:33:55 +0100790 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +0100791 tracer_ = tracer;
Steve Block6ded16b2010-05-10 14:33:55 +0100792 Scavenge();
Leon Clarkef7060e22010-06-03 12:02:55 +0100793 tracer_ = NULL;
Steve Block8defd9f2010-07-08 12:39:36 +0100794
795 UpdateSurvivalRateTrend(start_new_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000796 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000797
Ben Murdochc7cc0282012-03-05 14:35:55 +0000798 if (!new_space_high_promotion_mode_active_ &&
799 new_space_.Capacity() == new_space_.MaximumCapacity() &&
800 IsStableOrIncreasingSurvivalTrend() &&
801 IsHighSurvivalRate()) {
802 // Stable high survival rates even though young generation is at
803 // maximum capacity indicates that most objects will be promoted.
804 // To decrease scavenger pauses and final mark-sweep pauses, we
805 // have to limit maximal capacity of the young generation.
806 new_space_high_promotion_mode_active_ = true;
807 if (FLAG_trace_gc) {
808 PrintF("Limited new space size due to high promotion rate: %d MB\n",
809 new_space_.InitialCapacity() / MB);
810 }
811 } else if (new_space_high_promotion_mode_active_ &&
812 IsStableOrDecreasingSurvivalTrend() &&
813 IsLowSurvivalRate()) {
814 // Decreasing low survival rates might indicate that the above high
815 // promotion mode is over and we should allow the young generation
816 // to grow again.
817 new_space_high_promotion_mode_active_ = false;
818 if (FLAG_trace_gc) {
819 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
820 new_space_.MaximumCapacity() / MB);
821 }
822 }
823
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000824 if (new_space_high_promotion_mode_active_ &&
825 new_space_.Capacity() > new_space_.InitialCapacity()) {
826 new_space_.Shrink();
827 }
828
Steve Block44f0eee2011-05-26 01:26:41 +0100829 isolate_->counters()->objs_since_last_young()->Set(0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000830
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000831 gc_post_processing_depth_++;
Ben Murdoch257744e2011-11-30 15:57:28 +0000832 { DisableAssertNoAllocation allow_allocation;
John Reck59135872010-11-02 12:39:01 -0700833 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800834 next_gc_likely_to_collect_more =
Ben Murdoch257744e2011-11-30 15:57:28 +0000835 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
John Reck59135872010-11-02 12:39:01 -0700836 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000837 gc_post_processing_depth_--;
John Reck59135872010-11-02 12:39:01 -0700838
Steve Block3ce2e202009-11-05 08:53:23 +0000839 // Update relocatables.
840 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000841
842 if (collector == MARK_COMPACTOR) {
843 // Register the amount of external allocated memory.
844 amount_of_external_allocated_memory_at_last_global_gc_ =
845 amount_of_external_allocated_memory_;
846 }
847
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000848 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
Steve Block6ded16b2010-05-10 14:33:55 +0100849 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
850 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
851 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
852 }
853 }
854
Steve Blocka7e24c12009-10-30 11:49:00 +0000855 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
856 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100857 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000858 global_gc_epilogue_callback_();
859 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000860 if (FLAG_verify_heap) {
861 VerifySymbolTable();
862 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800863
864 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000865}
866
867
Steve Blocka7e24c12009-10-30 11:49:00 +0000868void Heap::MarkCompact(GCTracer* tracer) {
869 gc_state_ = MARK_COMPACT;
Steve Block44f0eee2011-05-26 01:26:41 +0100870 LOG(isolate_, ResourceEvent("markcompact", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000871
Steve Block44f0eee2011-05-26 01:26:41 +0100872 mark_compact_collector_.Prepare(tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000873
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000874 ms_count_++;
875 tracer->set_full_gc_count(ms_count_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000876
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000877 MarkCompactPrologue();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100878
Steve Block44f0eee2011-05-26 01:26:41 +0100879 mark_compact_collector_.CollectGarbage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000880
Steve Block44f0eee2011-05-26 01:26:41 +0100881 LOG(isolate_, ResourceEvent("markcompact", "end"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000882
883 gc_state_ = NOT_IN_GC;
884
Steve Block44f0eee2011-05-26 01:26:41 +0100885 isolate_->counters()->objs_since_last_full()->Set(0);
Steve Block6ded16b2010-05-10 14:33:55 +0100886
887 contexts_disposed_ = 0;
Ben Murdochc7cc0282012-03-05 14:35:55 +0000888
889 isolate_->set_context_exit_happened(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000890}
891
892
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000893void Heap::MarkCompactPrologue() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000894 // At any old GC clear the keyed lookup cache to enable collection of unused
895 // maps.
Steve Block44f0eee2011-05-26 01:26:41 +0100896 isolate_->keyed_lookup_cache()->Clear();
897 isolate_->context_slot_cache()->Clear();
898 isolate_->descriptor_lookup_cache()->Clear();
Ben Murdoch589d6972011-11-30 16:04:58 +0000899 StringSplitCache::Clear(string_split_cache());
Steve Blocka7e24c12009-10-30 11:49:00 +0000900
Steve Block44f0eee2011-05-26 01:26:41 +0100901 isolate_->compilation_cache()->MarkCompactPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000902
Kristian Monsen25f61362010-05-21 11:50:48 +0100903 CompletelyClearInstanceofCache();
904
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000905 // TODO(1605) select heuristic for flushing NumberString cache with
906 // FlushNumberStringCache
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000907 if (FLAG_cleanup_code_caches_at_gc) {
908 polymorphic_code_cache()->set_cache(undefined_value());
909 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000910
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100911 ClearNormalizedMapCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000912}
913
914
915Object* Heap::FindCodeObject(Address a) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000916 return isolate()->inner_pointer_to_code_cache()->
917 GcSafeFindCodeForInnerPointer(a);
Steve Blocka7e24c12009-10-30 11:49:00 +0000918}
919
920
921// Helper class for copying HeapObjects
922class ScavengeVisitor: public ObjectVisitor {
923 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100924 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000925
926 void VisitPointer(Object** p) { ScavengePointer(p); }
927
928 void VisitPointers(Object** start, Object** end) {
929 // Copy all HeapObject pointers in [start, end)
930 for (Object** p = start; p < end; p++) ScavengePointer(p);
931 }
932
933 private:
934 void ScavengePointer(Object** p) {
935 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +0100936 if (!heap_->InNewSpace(object)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +0000937 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
938 reinterpret_cast<HeapObject*>(object));
939 }
Steve Block44f0eee2011-05-26 01:26:41 +0100940
941 Heap* heap_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000942};
943
944
Steve Blocka7e24c12009-10-30 11:49:00 +0000945#ifdef DEBUG
946// Visitor class to verify pointers in code or data space do not point into
947// new space.
948class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
949 public:
950 void VisitPointers(Object** start, Object**end) {
951 for (Object** current = start; current < end; current++) {
952 if ((*current)->IsHeapObject()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100953 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000954 }
955 }
956 }
957};
958
959
960static void VerifyNonPointerSpacePointers() {
961 // Verify that there are no pointers to new space in spaces where we
962 // do not expect them.
963 VerifyNonPointerSpacePointersVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +0100964 HeapObjectIterator code_it(HEAP->code_space());
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000965 for (HeapObject* object = code_it.Next();
966 object != NULL; object = code_it.Next())
Steve Blocka7e24c12009-10-30 11:49:00 +0000967 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000968
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000969 // The old data space was normally swept conservatively so that the iterator
970 // doesn't work, so we normally skip the next bit.
971 if (!HEAP->old_data_space()->was_swept_conservatively()) {
972 HeapObjectIterator data_it(HEAP->old_data_space());
973 for (HeapObject* object = data_it.Next();
974 object != NULL; object = data_it.Next())
975 object->Iterate(&v);
976 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000977}
978#endif
979
980
Steve Block6ded16b2010-05-10 14:33:55 +0100981void Heap::CheckNewSpaceExpansionCriteria() {
982 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000983 survived_since_last_expansion_ > new_space_.Capacity() &&
984 !new_space_high_promotion_mode_active_) {
985 // Grow the size of new space if there is room to grow, enough data
986 // has survived scavenge since the last expansion and we are not in
987 // high promotion mode.
Steve Block6ded16b2010-05-10 14:33:55 +0100988 new_space_.Grow();
989 survived_since_last_expansion_ = 0;
990 }
991}
992
993
Ben Murdoch257744e2011-11-30 15:57:28 +0000994static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
995 return heap->InNewSpace(*p) &&
996 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
997}
998
999
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001000void Heap::ScavengeStoreBufferCallback(
1001 Heap* heap,
1002 MemoryChunk* page,
1003 StoreBufferEvent event) {
1004 heap->store_buffer_rebuilder_.Callback(page, event);
1005}
1006
1007
1008void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1009 if (event == kStoreBufferStartScanningPagesEvent) {
1010 start_of_current_page_ = NULL;
1011 current_page_ = NULL;
1012 } else if (event == kStoreBufferScanningPageEvent) {
1013 if (current_page_ != NULL) {
1014 // If this page already overflowed the store buffer during this iteration.
1015 if (current_page_->scan_on_scavenge()) {
1016 // Then we should wipe out the entries that have been added for it.
1017 store_buffer_->SetTop(start_of_current_page_);
1018 } else if (store_buffer_->Top() - start_of_current_page_ >=
1019 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1020 // Did we find too many pointers in the previous page? The heuristic is
1021 // that no page can take more then 1/5 the remaining slots in the store
1022 // buffer.
1023 current_page_->set_scan_on_scavenge(true);
1024 store_buffer_->SetTop(start_of_current_page_);
1025 } else {
1026 // In this case the page we scanned took a reasonable number of slots in
1027 // the store buffer. It has now been rehabilitated and is no longer
1028 // marked scan_on_scavenge.
1029 ASSERT(!current_page_->scan_on_scavenge());
1030 }
1031 }
1032 start_of_current_page_ = store_buffer_->Top();
1033 current_page_ = page;
1034 } else if (event == kStoreBufferFullEvent) {
1035 // The current page overflowed the store buffer again. Wipe out its entries
1036 // in the store buffer and mark it scan-on-scavenge again. This may happen
1037 // several times while scanning.
1038 if (current_page_ == NULL) {
1039 // Store Buffer overflowed while scanning promoted objects. These are not
1040 // in any particular page, though they are likely to be clustered by the
1041 // allocation routines.
Ben Murdochc7cc0282012-03-05 14:35:55 +00001042 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001043 } else {
1044 // Store Buffer overflowed while scanning a particular old space page for
1045 // pointers to new space.
1046 ASSERT(current_page_ == page);
1047 ASSERT(page != NULL);
1048 current_page_->set_scan_on_scavenge(true);
1049 ASSERT(start_of_current_page_ != store_buffer_->Top());
1050 store_buffer_->SetTop(start_of_current_page_);
1051 }
1052 } else {
1053 UNREACHABLE();
1054 }
1055}
1056
1057
1058void PromotionQueue::Initialize() {
1059 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1060 // entries (where each is a pair of intptr_t). This allows us to simplify
1061 // the test fpr when to switch pages.
1062 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1063 == 0);
1064 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1065 front_ = rear_ =
1066 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1067 emergency_stack_ = NULL;
1068 guard_ = false;
1069}
1070
1071
1072void PromotionQueue::RelocateQueueHead() {
1073 ASSERT(emergency_stack_ == NULL);
1074
1075 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1076 intptr_t* head_start = rear_;
1077 intptr_t* head_end =
1078 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1079
1080 int entries_count =
1081 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1082
1083 emergency_stack_ = new List<Entry>(2 * entries_count);
1084
1085 while (head_start != head_end) {
1086 int size = static_cast<int>(*(head_start++));
1087 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1088 emergency_stack_->Add(Entry(obj, size));
1089 }
1090 rear_ = head_end;
1091}
1092
1093
Steve Blocka7e24c12009-10-30 11:49:00 +00001094void Heap::Scavenge() {
1095#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001096 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
Steve Blocka7e24c12009-10-30 11:49:00 +00001097#endif
1098
1099 gc_state_ = SCAVENGE;
1100
1101 // Implements Cheney's copying algorithm
Steve Block44f0eee2011-05-26 01:26:41 +01001102 LOG(isolate_, ResourceEvent("scavenge", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001103
1104 // Clear descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01001105 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00001106
1107 // Used for updating survived_since_last_expansion_ at function end.
Ben Murdochc7cc0282012-03-05 14:35:55 +00001108 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +00001109
Steve Block6ded16b2010-05-10 14:33:55 +01001110 CheckNewSpaceExpansionCriteria();
Steve Blocka7e24c12009-10-30 11:49:00 +00001111
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001112 SelectScavengingVisitorsTable();
1113
1114 incremental_marking()->PrepareForScavenge();
1115
Ben Murdochc7cc0282012-03-05 14:35:55 +00001116 AdvanceSweepers(static_cast<int>(new_space_.Size()));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001117
Steve Blocka7e24c12009-10-30 11:49:00 +00001118 // Flip the semispaces. After flipping, to space is empty, from space has
1119 // live objects.
1120 new_space_.Flip();
1121 new_space_.ResetAllocationInfo();
1122
1123 // We need to sweep newly copied objects which can be either in the
1124 // to space or promoted to the old generation. For to-space
1125 // objects, we treat the bottom of the to space as a queue. Newly
1126 // copied and unswept objects lie between a 'front' mark and the
1127 // allocation pointer.
1128 //
1129 // Promoted objects can go into various old-generation spaces, and
1130 // can be allocated internally in the spaces (from the free list).
1131 // We treat the top of the to space as a queue of addresses of
1132 // promoted objects. The addresses of newly promoted and unswept
1133 // objects lie between a 'front' mark and a 'rear' mark that is
1134 // updated as a side effect of promoting an object.
1135 //
1136 // There is guaranteed to be enough room at the top of the to space
1137 // for the addresses of promoted objects: every object promoted
1138 // frees up its size in bytes from the top of the new space, and
1139 // objects are at least one pointer in size.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001140 Address new_space_front = new_space_.ToSpaceStart();
1141 promotion_queue_.Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +00001142
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001143#ifdef DEBUG
1144 store_buffer()->Clean();
1145#endif
1146
Steve Block44f0eee2011-05-26 01:26:41 +01001147 ScavengeVisitor scavenge_visitor(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00001148 // Copy roots.
Leon Clarkee46be812010-01-19 14:06:41 +00001149 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001150
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001151 // Copy objects reachable from the old generation.
1152 {
1153 StoreBufferRebuildScope scope(this,
1154 store_buffer(),
1155 &ScavengeStoreBufferCallback);
1156 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1157 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001158
1159 // Copy objects reachable from cells by scavenging cell values directly.
1160 HeapObjectIterator cell_iterator(cell_space_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001161 for (HeapObject* cell = cell_iterator.Next();
1162 cell != NULL; cell = cell_iterator.Next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001163 if (cell->IsJSGlobalPropertyCell()) {
1164 Address value_address =
1165 reinterpret_cast<Address>(cell) +
1166 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1167 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1168 }
1169 }
1170
Ben Murdochf87a2032010-10-22 12:50:53 +01001171 // Scavenge object reachable from the global contexts list directly.
1172 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1173
Leon Clarkee46be812010-01-19 14:06:41 +00001174 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001175 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
Ben Murdoch257744e2011-11-30 15:57:28 +00001176 &IsUnscavengedHeapObject);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001177 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1178 &scavenge_visitor);
Ben Murdoch257744e2011-11-30 15:57:28 +00001179 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1180
Steve Block6ded16b2010-05-10 14:33:55 +01001181 UpdateNewSpaceReferencesInExternalStringTable(
1182 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1183
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001184 promotion_queue_.Destroy();
1185
Steve Block1e0659c2011-05-24 12:43:12 +01001186 LiveObjectList::UpdateReferencesForScavengeGC();
Steve Block44f0eee2011-05-26 01:26:41 +01001187 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001188 incremental_marking()->UpdateMarkingDequeAfterScavenge();
Steve Block1e0659c2011-05-24 12:43:12 +01001189
Leon Clarkee46be812010-01-19 14:06:41 +00001190 ASSERT(new_space_front == new_space_.top());
1191
1192 // Set age mark.
1193 new_space_.set_age_mark(new_space_.top());
1194
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001195 new_space_.LowerInlineAllocationLimit(
1196 new_space_.inline_allocation_limit_step());
1197
Leon Clarkee46be812010-01-19 14:06:41 +00001198 // Update how much has survived scavenge.
Ben Murdochf87a2032010-10-22 12:50:53 +01001199 IncrementYoungSurvivorsCounter(static_cast<int>(
Ben Murdochc7cc0282012-03-05 14:35:55 +00001200 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
Leon Clarkee46be812010-01-19 14:06:41 +00001201
Steve Block44f0eee2011-05-26 01:26:41 +01001202 LOG(isolate_, ResourceEvent("scavenge", "end"));
Leon Clarkee46be812010-01-19 14:06:41 +00001203
1204 gc_state_ = NOT_IN_GC;
Ben Murdochc7cc0282012-03-05 14:35:55 +00001205
1206 scavenges_since_last_idle_round_++;
Leon Clarkee46be812010-01-19 14:06:41 +00001207}
1208
1209
Steve Block44f0eee2011-05-26 01:26:41 +01001210String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1211 Object** p) {
Steve Block6ded16b2010-05-10 14:33:55 +01001212 MapWord first_word = HeapObject::cast(*p)->map_word();
1213
1214 if (!first_word.IsForwardingAddress()) {
1215 // Unreachable external string can be finalized.
Steve Block44f0eee2011-05-26 01:26:41 +01001216 heap->FinalizeExternalString(String::cast(*p));
Steve Block6ded16b2010-05-10 14:33:55 +01001217 return NULL;
1218 }
1219
1220 // String is still reachable.
1221 return String::cast(first_word.ToForwardingAddress());
1222}
1223
1224
1225void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1226 ExternalStringTableUpdaterCallback updater_func) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001227 if (FLAG_verify_heap) {
1228 external_string_table_.Verify();
1229 }
Leon Clarkee46be812010-01-19 14:06:41 +00001230
Steve Block44f0eee2011-05-26 01:26:41 +01001231 if (external_string_table_.new_space_strings_.is_empty()) return;
Leon Clarkee46be812010-01-19 14:06:41 +00001232
Steve Block44f0eee2011-05-26 01:26:41 +01001233 Object** start = &external_string_table_.new_space_strings_[0];
1234 Object** end = start + external_string_table_.new_space_strings_.length();
Leon Clarkee46be812010-01-19 14:06:41 +00001235 Object** last = start;
1236
1237 for (Object** p = start; p < end; ++p) {
Steve Block44f0eee2011-05-26 01:26:41 +01001238 ASSERT(InFromSpace(*p));
1239 String* target = updater_func(this, p);
Leon Clarkee46be812010-01-19 14:06:41 +00001240
Steve Block6ded16b2010-05-10 14:33:55 +01001241 if (target == NULL) continue;
Leon Clarkee46be812010-01-19 14:06:41 +00001242
Leon Clarkee46be812010-01-19 14:06:41 +00001243 ASSERT(target->IsExternalString());
1244
Steve Block44f0eee2011-05-26 01:26:41 +01001245 if (InNewSpace(target)) {
Leon Clarkee46be812010-01-19 14:06:41 +00001246 // String is still in new space. Update the table entry.
1247 *last = target;
1248 ++last;
1249 } else {
1250 // String got promoted. Move it to the old string list.
Steve Block44f0eee2011-05-26 01:26:41 +01001251 external_string_table_.AddOldString(target);
Leon Clarkee46be812010-01-19 14:06:41 +00001252 }
1253 }
1254
1255 ASSERT(last <= end);
Steve Block44f0eee2011-05-26 01:26:41 +01001256 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
Leon Clarkee46be812010-01-19 14:06:41 +00001257}
1258
1259
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001260void Heap::UpdateReferencesInExternalStringTable(
1261 ExternalStringTableUpdaterCallback updater_func) {
1262
1263 // Update old space string references.
1264 if (external_string_table_.old_space_strings_.length() > 0) {
1265 Object** start = &external_string_table_.old_space_strings_[0];
1266 Object** end = start + external_string_table_.old_space_strings_.length();
1267 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1268 }
1269
1270 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1271}
1272
1273
Steve Block44f0eee2011-05-26 01:26:41 +01001274static Object* ProcessFunctionWeakReferences(Heap* heap,
1275 Object* function,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001276 WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001277 Object* undefined = heap->undefined_value();
1278 Object* head = undefined;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001279 JSFunction* tail = NULL;
1280 Object* candidate = function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001281 while (candidate != undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001282 // Check whether to keep the candidate in the list.
1283 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1284 Object* retain = retainer->RetainAs(candidate);
1285 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001286 if (head == undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001287 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001288 head = retain;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001289 } else {
1290 // Subsequent elements in the list.
1291 ASSERT(tail != NULL);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001292 tail->set_next_function_link(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001293 }
1294 // Retained function is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001295 candidate_function = reinterpret_cast<JSFunction*>(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001296 tail = candidate_function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001297
1298 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1299
1300 if (retain == undefined) break;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001301 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001302
Ben Murdochb0fe1622011-05-05 13:52:32 +01001303 // Move to next element in the list.
1304 candidate = candidate_function->next_function_link();
1305 }
1306
1307 // Terminate the list if there is one or more elements.
1308 if (tail != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001309 tail->set_next_function_link(undefined);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001310 }
1311
1312 return head;
1313}
1314
1315
Ben Murdochf87a2032010-10-22 12:50:53 +01001316void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001317 Object* undefined = undefined_value();
1318 Object* head = undefined;
Ben Murdochf87a2032010-10-22 12:50:53 +01001319 Context* tail = NULL;
1320 Object* candidate = global_contexts_list_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001321 while (candidate != undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001322 // Check whether to keep the candidate in the list.
1323 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1324 Object* retain = retainer->RetainAs(candidate);
1325 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001326 if (head == undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001327 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001328 head = retain;
Ben Murdochf87a2032010-10-22 12:50:53 +01001329 } else {
1330 // Subsequent elements in the list.
1331 ASSERT(tail != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01001332 tail->set_unchecked(this,
1333 Context::NEXT_CONTEXT_LINK,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001334 retain,
Ben Murdochf87a2032010-10-22 12:50:53 +01001335 UPDATE_WRITE_BARRIER);
1336 }
1337 // Retained context is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001338 candidate_context = reinterpret_cast<Context*>(retain);
Ben Murdochf87a2032010-10-22 12:50:53 +01001339 tail = candidate_context;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001340
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001341 if (retain == undefined) break;
1342
Ben Murdochb0fe1622011-05-05 13:52:32 +01001343 // Process the weak list of optimized functions for the context.
1344 Object* function_list_head =
1345 ProcessFunctionWeakReferences(
Steve Block44f0eee2011-05-26 01:26:41 +01001346 this,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001347 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1348 retainer);
Steve Block44f0eee2011-05-26 01:26:41 +01001349 candidate_context->set_unchecked(this,
1350 Context::OPTIMIZED_FUNCTIONS_LIST,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001351 function_list_head,
1352 UPDATE_WRITE_BARRIER);
Ben Murdochf87a2032010-10-22 12:50:53 +01001353 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001354
Ben Murdochf87a2032010-10-22 12:50:53 +01001355 // Move to next element in the list.
1356 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1357 }
1358
1359 // Terminate the list if there is one or more elements.
1360 if (tail != NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01001361 tail->set_unchecked(this,
1362 Context::NEXT_CONTEXT_LINK,
Ben Murdochf87a2032010-10-22 12:50:53 +01001363 Heap::undefined_value(),
1364 UPDATE_WRITE_BARRIER);
1365 }
1366
1367 // Update the head of the list of contexts.
Steve Block44f0eee2011-05-26 01:26:41 +01001368 global_contexts_list_ = head;
Ben Murdochf87a2032010-10-22 12:50:53 +01001369}
1370
1371
Ben Murdochc7cc0282012-03-05 14:35:55 +00001372void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1373 AssertNoAllocation no_allocation;
1374
1375 class VisitorAdapter : public ObjectVisitor {
1376 public:
1377 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1378 : visitor_(visitor) {}
1379 virtual void VisitPointers(Object** start, Object** end) {
1380 for (Object** p = start; p < end; p++) {
1381 if ((*p)->IsExternalString()) {
1382 visitor_->VisitExternalString(Utils::ToLocal(
1383 Handle<String>(String::cast(*p))));
1384 }
1385 }
1386 }
1387 private:
1388 v8::ExternalResourceVisitor* visitor_;
1389 } visitor_adapter(visitor);
1390 external_string_table_.Iterate(&visitor_adapter);
1391}
1392
1393
Iain Merrick75681382010-08-19 15:07:18 +01001394class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1395 public:
Steve Block44f0eee2011-05-26 01:26:41 +01001396 static inline void VisitPointer(Heap* heap, Object** p) {
Iain Merrick75681382010-08-19 15:07:18 +01001397 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +01001398 if (!heap->InNewSpace(object)) return;
Iain Merrick75681382010-08-19 15:07:18 +01001399 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1400 reinterpret_cast<HeapObject*>(object));
1401 }
1402};
1403
1404
Leon Clarkee46be812010-01-19 14:06:41 +00001405Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1406 Address new_space_front) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001407 do {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001408 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001409 // The addresses new_space_front and new_space_.top() define a
1410 // queue of unprocessed copied objects. Process them until the
1411 // queue is empty.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001412 while (new_space_front != new_space_.top()) {
1413 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1414 HeapObject* object = HeapObject::FromAddress(new_space_front);
1415 new_space_front +=
1416 NewSpaceScavenger::IterateBody(object->map(), object);
1417 } else {
1418 new_space_front =
1419 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1420 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001421 }
1422
1423 // Promote and process all the to-be-promoted objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001424 {
1425 StoreBufferRebuildScope scope(this,
1426 store_buffer(),
1427 &ScavengeStoreBufferCallback);
1428 while (!promotion_queue()->is_empty()) {
1429 HeapObject* target;
1430 int size;
1431 promotion_queue()->remove(&target, &size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001432
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001433 // Promoted object might be already partially visited
1434 // during old space pointer iteration. Thus we search specificly
1435 // for pointers to from semispace instead of looking for pointers
1436 // to new space.
1437 ASSERT(!target->IsMap());
1438 IterateAndMarkPointersToFromSpace(target->address(),
1439 target->address() + size,
1440 &ScavengeObject);
1441 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001442 }
1443
1444 // Take another spin if there are now unswept objects in new space
1445 // (there are currently no more unswept promoted objects).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001446 } while (new_space_front != new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001447
Leon Clarkee46be812010-01-19 14:06:41 +00001448 return new_space_front;
Steve Blocka7e24c12009-10-30 11:49:00 +00001449}
1450
1451
Ben Murdoch8b112d22011-06-08 16:22:53 +01001452enum LoggingAndProfiling {
1453 LOGGING_AND_PROFILING_ENABLED,
1454 LOGGING_AND_PROFILING_DISABLED
1455};
1456
1457
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001458enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
Ben Murdoch8b112d22011-06-08 16:22:53 +01001459
1460
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001461template<MarksHandling marks_handling,
1462 LoggingAndProfiling logging_and_profiling_mode>
Iain Merrick75681382010-08-19 15:07:18 +01001463class ScavengingVisitor : public StaticVisitorBase {
1464 public:
1465 static void Initialize() {
1466 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1467 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1468 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1469 table_.Register(kVisitByteArray, &EvacuateByteArray);
1470 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001471 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001472
Ben Murdochf87a2032010-10-22 12:50:53 +01001473 table_.Register(kVisitGlobalContext,
1474 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001475 template VisitSpecialized<Context::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001476
1477 table_.Register(kVisitConsString,
1478 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001479 template VisitSpecialized<ConsString::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001480
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001481 table_.Register(kVisitSlicedString,
1482 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1483 template VisitSpecialized<SlicedString::kSize>);
1484
Iain Merrick75681382010-08-19 15:07:18 +01001485 table_.Register(kVisitSharedFunctionInfo,
1486 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001487 template VisitSpecialized<SharedFunctionInfo::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001488
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001489 table_.Register(kVisitJSWeakMap,
1490 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1491 Visit);
1492
Ben Murdoch257744e2011-11-30 15:57:28 +00001493 table_.Register(kVisitJSRegExp,
1494 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1495 Visit);
1496
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001497 if (marks_handling == IGNORE_MARKS) {
1498 table_.Register(kVisitJSFunction,
1499 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1500 template VisitSpecialized<JSFunction::kSize>);
1501 } else {
1502 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1503 }
Iain Merrick75681382010-08-19 15:07:18 +01001504
1505 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1506 kVisitDataObject,
1507 kVisitDataObjectGeneric>();
1508
1509 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1510 kVisitJSObject,
1511 kVisitJSObjectGeneric>();
1512
1513 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1514 kVisitStruct,
1515 kVisitStructGeneric>();
1516 }
1517
Ben Murdoch8b112d22011-06-08 16:22:53 +01001518 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1519 return &table_;
Iain Merrick75681382010-08-19 15:07:18 +01001520 }
1521
Iain Merrick75681382010-08-19 15:07:18 +01001522 private:
1523 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1524 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1525
Steve Block44f0eee2011-05-26 01:26:41 +01001526 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
Iain Merrick75681382010-08-19 15:07:18 +01001527 bool should_record = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001528#ifdef DEBUG
Iain Merrick75681382010-08-19 15:07:18 +01001529 should_record = FLAG_heap_stats;
Steve Blocka7e24c12009-10-30 11:49:00 +00001530#endif
Iain Merrick75681382010-08-19 15:07:18 +01001531 should_record = should_record || FLAG_log_gc;
Iain Merrick75681382010-08-19 15:07:18 +01001532 if (should_record) {
Steve Block44f0eee2011-05-26 01:26:41 +01001533 if (heap->new_space()->Contains(obj)) {
1534 heap->new_space()->RecordAllocation(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001535 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001536 heap->new_space()->RecordPromotion(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001537 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001538 }
1539 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001540
Iain Merrick75681382010-08-19 15:07:18 +01001541 // Helper function used by CopyObject to copy a source object to an
1542 // allocated target object and update the forwarding pointer in the source
1543 // object. Returns the target object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001544 INLINE(static void MigrateObject(Heap* heap,
1545 HeapObject* source,
1546 HeapObject* target,
1547 int size)) {
Iain Merrick75681382010-08-19 15:07:18 +01001548 // Copy the content of source to target.
Steve Block44f0eee2011-05-26 01:26:41 +01001549 heap->CopyBlock(target->address(), source->address(), size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001550
Iain Merrick75681382010-08-19 15:07:18 +01001551 // Set the forwarding address.
1552 source->set_map_word(MapWord::FromForwardingAddress(target));
Steve Blocka7e24c12009-10-30 11:49:00 +00001553
Ben Murdoch8b112d22011-06-08 16:22:53 +01001554 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001555 // Update NewSpace stats if necessary.
1556 RecordCopiedObject(heap, target);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001557 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
Ben Murdoch8b112d22011-06-08 16:22:53 +01001558 Isolate* isolate = heap->isolate();
1559 if (isolate->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001560 CpuProfiler::is_profiling(isolate)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001561 if (target->IsSharedFunctionInfo()) {
1562 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1563 source->address(), target->address()));
1564 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001565 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001566 }
1567
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001568 if (marks_handling == TRANSFER_MARKS) {
1569 if (Marking::TransferColor(source, target)) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00001570 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001571 }
1572 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001573 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001574
Iain Merrick75681382010-08-19 15:07:18 +01001575 template<ObjectContents object_contents, SizeRestriction size_restriction>
1576 static inline void EvacuateObject(Map* map,
1577 HeapObject** slot,
1578 HeapObject* object,
1579 int object_size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001580 SLOW_ASSERT((size_restriction != SMALL) ||
1581 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1582 SLOW_ASSERT(object->Size() == object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001583
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001584 Heap* heap = map->GetHeap();
Steve Block44f0eee2011-05-26 01:26:41 +01001585 if (heap->ShouldBePromoted(object->address(), object_size)) {
John Reck59135872010-11-02 12:39:01 -07001586 MaybeObject* maybe_result;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001587
Iain Merrick75681382010-08-19 15:07:18 +01001588 if ((size_restriction != SMALL) &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001589 (object_size > Page::kMaxNonCodeHeapObjectSize)) {
1590 maybe_result = heap->lo_space()->AllocateRaw(object_size,
1591 NOT_EXECUTABLE);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001592 } else {
Iain Merrick75681382010-08-19 15:07:18 +01001593 if (object_contents == DATA_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001594 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001595 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001596 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001597 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001598 }
1599
John Reck59135872010-11-02 12:39:01 -07001600 Object* result = NULL; // Initialization to please compiler.
1601 if (maybe_result->ToObject(&result)) {
Iain Merrick75681382010-08-19 15:07:18 +01001602 HeapObject* target = HeapObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001603
1604 // Order is important: slot might be inside of the target if target
1605 // was allocated over a dead object and slot comes from the store
1606 // buffer.
1607 *slot = target;
1608 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001609
Iain Merrick75681382010-08-19 15:07:18 +01001610 if (object_contents == POINTER_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001611 heap->promotion_queue()->insert(target, object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001612 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001613
Steve Block44f0eee2011-05-26 01:26:41 +01001614 heap->tracer()->increment_promoted_objects_size(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001615 return;
1616 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001617 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001618 MaybeObject* allocation = heap->new_space()->AllocateRaw(object_size);
1619 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1620 Object* result = allocation->ToObjectUnchecked();
1621 HeapObject* target = HeapObject::cast(result);
1622
1623 // Order is important: slot might be inside of the target if target
1624 // was allocated over a dead object and slot comes from the store
1625 // buffer.
1626 *slot = target;
1627 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001628 return;
1629 }
1630
Iain Merrick75681382010-08-19 15:07:18 +01001631
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001632 static inline void EvacuateJSFunction(Map* map,
1633 HeapObject** slot,
1634 HeapObject* object) {
1635 ObjectEvacuationStrategy<POINTER_OBJECT>::
1636 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1637
1638 HeapObject* target = *slot;
1639 MarkBit mark_bit = Marking::MarkBitFrom(target);
1640 if (Marking::IsBlack(mark_bit)) {
1641 // This object is black and it might not be rescanned by marker.
1642 // We should explicitly record code entry slot for compaction because
1643 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1644 // miss it as it is not HeapObject-tagged.
1645 Address code_entry_slot =
1646 target->address() + JSFunction::kCodeEntryOffset;
1647 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1648 map->GetHeap()->mark_compact_collector()->
1649 RecordCodeEntrySlot(code_entry_slot, code);
1650 }
1651 }
1652
1653
Iain Merrick75681382010-08-19 15:07:18 +01001654 static inline void EvacuateFixedArray(Map* map,
1655 HeapObject** slot,
1656 HeapObject* object) {
1657 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1658 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1659 slot,
1660 object,
1661 object_size);
1662 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001663
1664
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001665 static inline void EvacuateFixedDoubleArray(Map* map,
1666 HeapObject** slot,
1667 HeapObject* object) {
1668 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1669 int object_size = FixedDoubleArray::SizeFor(length);
1670 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1671 slot,
1672 object,
1673 object_size);
1674 }
1675
1676
Iain Merrick75681382010-08-19 15:07:18 +01001677 static inline void EvacuateByteArray(Map* map,
1678 HeapObject** slot,
1679 HeapObject* object) {
1680 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1681 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1682 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001683
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001684
Iain Merrick75681382010-08-19 15:07:18 +01001685 static inline void EvacuateSeqAsciiString(Map* map,
1686 HeapObject** slot,
1687 HeapObject* object) {
1688 int object_size = SeqAsciiString::cast(object)->
1689 SeqAsciiStringSize(map->instance_type());
1690 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1691 }
1692
1693
1694 static inline void EvacuateSeqTwoByteString(Map* map,
1695 HeapObject** slot,
1696 HeapObject* object) {
1697 int object_size = SeqTwoByteString::cast(object)->
1698 SeqTwoByteStringSize(map->instance_type());
1699 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1700 }
1701
1702
1703 static inline bool IsShortcutCandidate(int type) {
1704 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1705 }
1706
1707 static inline void EvacuateShortcutCandidate(Map* map,
1708 HeapObject** slot,
1709 HeapObject* object) {
1710 ASSERT(IsShortcutCandidate(map->instance_type()));
1711
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001712 Heap* heap = map->GetHeap();
1713
1714 if (marks_handling == IGNORE_MARKS &&
1715 ConsString::cast(object)->unchecked_second() ==
1716 heap->empty_string()) {
Iain Merrick75681382010-08-19 15:07:18 +01001717 HeapObject* first =
1718 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1719
1720 *slot = first;
1721
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001722 if (!heap->InNewSpace(first)) {
Iain Merrick75681382010-08-19 15:07:18 +01001723 object->set_map_word(MapWord::FromForwardingAddress(first));
1724 return;
1725 }
1726
1727 MapWord first_word = first->map_word();
1728 if (first_word.IsForwardingAddress()) {
1729 HeapObject* target = first_word.ToForwardingAddress();
1730
1731 *slot = target;
1732 object->set_map_word(MapWord::FromForwardingAddress(target));
1733 return;
1734 }
1735
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001736 heap->DoScavengeObject(first->map(), slot, first);
Iain Merrick75681382010-08-19 15:07:18 +01001737 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1738 return;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001739 }
Iain Merrick75681382010-08-19 15:07:18 +01001740
1741 int object_size = ConsString::kSize;
1742 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001743 }
1744
Iain Merrick75681382010-08-19 15:07:18 +01001745 template<ObjectContents object_contents>
1746 class ObjectEvacuationStrategy {
1747 public:
1748 template<int object_size>
1749 static inline void VisitSpecialized(Map* map,
1750 HeapObject** slot,
1751 HeapObject* object) {
1752 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1753 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001754
Iain Merrick75681382010-08-19 15:07:18 +01001755 static inline void Visit(Map* map,
1756 HeapObject** slot,
1757 HeapObject* object) {
1758 int object_size = map->instance_size();
1759 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1760 }
1761 };
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001762
Ben Murdoch8b112d22011-06-08 16:22:53 +01001763 static VisitorDispatchTable<ScavengingCallback> table_;
Iain Merrick75681382010-08-19 15:07:18 +01001764};
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001765
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001766
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001767template<MarksHandling marks_handling,
1768 LoggingAndProfiling logging_and_profiling_mode>
Ben Murdoch8b112d22011-06-08 16:22:53 +01001769VisitorDispatchTable<ScavengingCallback>
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001770 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001771
1772
1773static void InitializeScavengingVisitorsTables() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001774 ScavengingVisitor<TRANSFER_MARKS,
1775 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1776 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1777 ScavengingVisitor<TRANSFER_MARKS,
1778 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1779 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
Ben Murdoch8b112d22011-06-08 16:22:53 +01001780}
1781
1782
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001783void Heap::SelectScavengingVisitorsTable() {
1784 bool logging_and_profiling =
1785 isolate()->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001786 CpuProfiler::is_profiling(isolate()) ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01001787 (isolate()->heap_profiler() != NULL &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001788 isolate()->heap_profiler()->is_profiling());
Ben Murdoch8b112d22011-06-08 16:22:53 +01001789
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001790 if (!incremental_marking()->IsMarking()) {
1791 if (!logging_and_profiling) {
1792 scavenging_visitors_table_.CopyFrom(
1793 ScavengingVisitor<IGNORE_MARKS,
1794 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1795 } else {
1796 scavenging_visitors_table_.CopyFrom(
1797 ScavengingVisitor<IGNORE_MARKS,
1798 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1799 }
1800 } else {
1801 if (!logging_and_profiling) {
1802 scavenging_visitors_table_.CopyFrom(
1803 ScavengingVisitor<TRANSFER_MARKS,
1804 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1805 } else {
1806 scavenging_visitors_table_.CopyFrom(
1807 ScavengingVisitor<TRANSFER_MARKS,
1808 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1809 }
1810
1811 if (incremental_marking()->IsCompacting()) {
1812 // When compacting forbid short-circuiting of cons-strings.
1813 // Scavenging code relies on the fact that new space object
1814 // can't be evacuated into evacuation candidate but
1815 // short-circuiting violates this assumption.
1816 scavenging_visitors_table_.Register(
1817 StaticVisitorBase::kVisitShortcutCandidate,
1818 scavenging_visitors_table_.GetVisitorById(
1819 StaticVisitorBase::kVisitConsString));
1820 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001821 }
1822}
Steve Blocka7e24c12009-10-30 11:49:00 +00001823
1824
1825void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001826 SLOW_ASSERT(HEAP->InFromSpace(object));
Steve Blocka7e24c12009-10-30 11:49:00 +00001827 MapWord first_word = object->map_word();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001828 SLOW_ASSERT(!first_word.IsForwardingAddress());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001829 Map* map = first_word.ToMap();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001830 map->GetHeap()->DoScavengeObject(map, p, object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001831}
1832
1833
John Reck59135872010-11-02 12:39:01 -07001834MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1835 int instance_size) {
1836 Object* result;
1837 { MaybeObject* maybe_result = AllocateRawMap();
1838 if (!maybe_result->ToObject(&result)) return maybe_result;
1839 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001840
1841 // Map::cast cannot be used due to uninitialized map field.
1842 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1843 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1844 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
Steve Block44f0eee2011-05-26 01:26:41 +01001845 reinterpret_cast<Map*>(result)->set_visitor_id(
1846 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Steve Blocka7e24c12009-10-30 11:49:00 +00001847 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001848 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001849 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001850 reinterpret_cast<Map*>(result)->set_bit_field(0);
1851 reinterpret_cast<Map*>(result)->set_bit_field2(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001852 return result;
1853}
1854
1855
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001856MaybeObject* Heap::AllocateMap(InstanceType instance_type,
1857 int instance_size,
1858 ElementsKind elements_kind) {
John Reck59135872010-11-02 12:39:01 -07001859 Object* result;
1860 { MaybeObject* maybe_result = AllocateRawMap();
1861 if (!maybe_result->ToObject(&result)) return maybe_result;
1862 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001863
1864 Map* map = reinterpret_cast<Map*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00001865 map->set_map_no_write_barrier(meta_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00001866 map->set_instance_type(instance_type);
Iain Merrick75681382010-08-19 15:07:18 +01001867 map->set_visitor_id(
1868 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001869 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
1870 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001871 map->set_instance_size(instance_size);
1872 map->set_inobject_properties(0);
1873 map->set_pre_allocated_property_fields(0);
Ben Murdoch257744e2011-11-30 15:57:28 +00001874 map->init_instance_descriptors();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001875 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1876 map->set_prototype_transitions(empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001877 map->set_unused_property_fields(0);
1878 map->set_bit_field(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001879 map->set_bit_field2(1 << Map::kIsExtensible);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001880 map->set_elements_kind(elements_kind);
Leon Clarkee46be812010-01-19 14:06:41 +00001881
1882 // If the map object is aligned fill the padding area with Smi 0 objects.
1883 if (Map::kPadStart < Map::kSize) {
1884 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1885 0,
1886 Map::kSize - Map::kPadStart);
1887 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001888 return map;
1889}
1890
1891
John Reck59135872010-11-02 12:39:01 -07001892MaybeObject* Heap::AllocateCodeCache() {
1893 Object* result;
1894 { MaybeObject* maybe_result = AllocateStruct(CODE_CACHE_TYPE);
1895 if (!maybe_result->ToObject(&result)) return maybe_result;
1896 }
Steve Block6ded16b2010-05-10 14:33:55 +01001897 CodeCache* code_cache = CodeCache::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001898 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1899 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
Steve Block6ded16b2010-05-10 14:33:55 +01001900 return code_cache;
1901}
1902
1903
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001904MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1905 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1906}
1907
1908
Ben Murdochc7cc0282012-03-05 14:35:55 +00001909MaybeObject* Heap::AllocateAccessorPair() {
1910 Object* result;
1911 { MaybeObject* maybe_result = AllocateStruct(ACCESSOR_PAIR_TYPE);
1912 if (!maybe_result->ToObject(&result)) return maybe_result;
1913 }
1914 AccessorPair* accessors = AccessorPair::cast(result);
1915 // Later we will have to distinguish between undefined and the hole...
1916 // accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
1917 // accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
1918 return accessors;
1919}
1920
1921
Steve Blocka7e24c12009-10-30 11:49:00 +00001922const Heap::StringTypeTable Heap::string_type_table[] = {
1923#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1924 {type, size, k##camel_name##MapRootIndex},
1925 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1926#undef STRING_TYPE_ELEMENT
1927};
1928
1929
1930const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1931#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1932 {contents, k##name##RootIndex},
1933 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1934#undef CONSTANT_SYMBOL_ELEMENT
1935};
1936
1937
1938const Heap::StructTable Heap::struct_table[] = {
1939#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1940 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1941 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1942#undef STRUCT_TABLE_ELEMENT
1943};
1944
1945
1946bool Heap::CreateInitialMaps() {
John Reck59135872010-11-02 12:39:01 -07001947 Object* obj;
1948 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1949 if (!maybe_obj->ToObject(&obj)) return false;
1950 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001951 // Map::cast cannot be used due to uninitialized map field.
1952 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1953 set_meta_map(new_meta_map);
1954 new_meta_map->set_map(new_meta_map);
1955
John Reck59135872010-11-02 12:39:01 -07001956 { MaybeObject* maybe_obj =
1957 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1958 if (!maybe_obj->ToObject(&obj)) return false;
1959 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001960 set_fixed_array_map(Map::cast(obj));
1961
John Reck59135872010-11-02 12:39:01 -07001962 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1963 if (!maybe_obj->ToObject(&obj)) return false;
1964 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001965 set_oddball_map(Map::cast(obj));
1966
Steve Block6ded16b2010-05-10 14:33:55 +01001967 // Allocate the empty array.
John Reck59135872010-11-02 12:39:01 -07001968 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1969 if (!maybe_obj->ToObject(&obj)) return false;
1970 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001971 set_empty_fixed_array(FixedArray::cast(obj));
1972
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001973 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07001974 if (!maybe_obj->ToObject(&obj)) return false;
1975 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001976 set_null_value(Oddball::cast(obj));
Steve Block44f0eee2011-05-26 01:26:41 +01001977 Oddball::cast(obj)->set_kind(Oddball::kNull);
Steve Blocka7e24c12009-10-30 11:49:00 +00001978
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001979 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
1980 if (!maybe_obj->ToObject(&obj)) return false;
1981 }
1982 set_undefined_value(Oddball::cast(obj));
1983 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
1984 ASSERT(!InNewSpace(undefined_value()));
1985
Steve Blocka7e24c12009-10-30 11:49:00 +00001986 // Allocate the empty descriptor array.
John Reck59135872010-11-02 12:39:01 -07001987 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1988 if (!maybe_obj->ToObject(&obj)) return false;
1989 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001990 set_empty_descriptor_array(DescriptorArray::cast(obj));
1991
1992 // Fix the instance_descriptors for the existing maps.
Ben Murdoch257744e2011-11-30 15:57:28 +00001993 meta_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00001994 meta_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01001995 meta_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00001996
Ben Murdoch257744e2011-11-30 15:57:28 +00001997 fixed_array_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00001998 fixed_array_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01001999 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002000
Ben Murdoch257744e2011-11-30 15:57:28 +00002001 oddball_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00002002 oddball_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01002003 oddball_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002004
2005 // Fix prototype object for existing maps.
2006 meta_map()->set_prototype(null_value());
2007 meta_map()->set_constructor(null_value());
2008
2009 fixed_array_map()->set_prototype(null_value());
2010 fixed_array_map()->set_constructor(null_value());
2011
2012 oddball_map()->set_prototype(null_value());
2013 oddball_map()->set_constructor(null_value());
2014
John Reck59135872010-11-02 12:39:01 -07002015 { MaybeObject* maybe_obj =
2016 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2017 if (!maybe_obj->ToObject(&obj)) return false;
2018 }
Iain Merrick75681382010-08-19 15:07:18 +01002019 set_fixed_cow_array_map(Map::cast(obj));
2020 ASSERT(fixed_array_map() != fixed_cow_array_map());
2021
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002022 { MaybeObject* maybe_obj =
2023 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2024 if (!maybe_obj->ToObject(&obj)) return false;
2025 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002026 set_scope_info_map(Map::cast(obj));
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002027
John Reck59135872010-11-02 12:39:01 -07002028 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2029 if (!maybe_obj->ToObject(&obj)) return false;
2030 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002031 set_heap_number_map(Map::cast(obj));
2032
Ben Murdoch257744e2011-11-30 15:57:28 +00002033 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
John Reck59135872010-11-02 12:39:01 -07002034 if (!maybe_obj->ToObject(&obj)) return false;
2035 }
Ben Murdoch257744e2011-11-30 15:57:28 +00002036 set_foreign_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002037
2038 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2039 const StringTypeTable& entry = string_type_table[i];
John Reck59135872010-11-02 12:39:01 -07002040 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2041 if (!maybe_obj->ToObject(&obj)) return false;
2042 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002043 roots_[entry.index] = Map::cast(obj);
2044 }
2045
John Reck59135872010-11-02 12:39:01 -07002046 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2047 if (!maybe_obj->ToObject(&obj)) return false;
2048 }
Steve Blockd0582a62009-12-15 09:54:21 +00002049 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002050 Map::cast(obj)->set_is_undetectable();
2051
John Reck59135872010-11-02 12:39:01 -07002052 { MaybeObject* maybe_obj =
2053 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2054 if (!maybe_obj->ToObject(&obj)) return false;
2055 }
Steve Blockd0582a62009-12-15 09:54:21 +00002056 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002057 Map::cast(obj)->set_is_undetectable();
2058
John Reck59135872010-11-02 12:39:01 -07002059 { MaybeObject* maybe_obj =
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002060 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2061 if (!maybe_obj->ToObject(&obj)) return false;
2062 }
2063 set_fixed_double_array_map(Map::cast(obj));
2064
2065 { MaybeObject* maybe_obj =
John Reck59135872010-11-02 12:39:01 -07002066 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2067 if (!maybe_obj->ToObject(&obj)) return false;
2068 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002069 set_byte_array_map(Map::cast(obj));
2070
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002071 { MaybeObject* maybe_obj =
2072 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2073 if (!maybe_obj->ToObject(&obj)) return false;
2074 }
2075 set_free_space_map(Map::cast(obj));
2076
Ben Murdochb0fe1622011-05-05 13:52:32 +01002077 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2078 if (!maybe_obj->ToObject(&obj)) return false;
2079 }
2080 set_empty_byte_array(ByteArray::cast(obj));
2081
John Reck59135872010-11-02 12:39:01 -07002082 { MaybeObject* maybe_obj =
Steve Block44f0eee2011-05-26 01:26:41 +01002083 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
John Reck59135872010-11-02 12:39:01 -07002084 if (!maybe_obj->ToObject(&obj)) return false;
2085 }
Steve Block44f0eee2011-05-26 01:26:41 +01002086 set_external_pixel_array_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002087
John Reck59135872010-11-02 12:39:01 -07002088 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2089 ExternalArray::kAlignedSize);
2090 if (!maybe_obj->ToObject(&obj)) return false;
2091 }
Steve Block3ce2e202009-11-05 08:53:23 +00002092 set_external_byte_array_map(Map::cast(obj));
2093
John Reck59135872010-11-02 12:39:01 -07002094 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2095 ExternalArray::kAlignedSize);
2096 if (!maybe_obj->ToObject(&obj)) return false;
2097 }
Steve Block3ce2e202009-11-05 08:53:23 +00002098 set_external_unsigned_byte_array_map(Map::cast(obj));
2099
John Reck59135872010-11-02 12:39:01 -07002100 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2101 ExternalArray::kAlignedSize);
2102 if (!maybe_obj->ToObject(&obj)) return false;
2103 }
Steve Block3ce2e202009-11-05 08:53:23 +00002104 set_external_short_array_map(Map::cast(obj));
2105
John Reck59135872010-11-02 12:39:01 -07002106 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2107 ExternalArray::kAlignedSize);
2108 if (!maybe_obj->ToObject(&obj)) return false;
2109 }
Steve Block3ce2e202009-11-05 08:53:23 +00002110 set_external_unsigned_short_array_map(Map::cast(obj));
2111
John Reck59135872010-11-02 12:39:01 -07002112 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2113 ExternalArray::kAlignedSize);
2114 if (!maybe_obj->ToObject(&obj)) return false;
2115 }
Steve Block3ce2e202009-11-05 08:53:23 +00002116 set_external_int_array_map(Map::cast(obj));
2117
John Reck59135872010-11-02 12:39:01 -07002118 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2119 ExternalArray::kAlignedSize);
2120 if (!maybe_obj->ToObject(&obj)) return false;
2121 }
Steve Block3ce2e202009-11-05 08:53:23 +00002122 set_external_unsigned_int_array_map(Map::cast(obj));
2123
John Reck59135872010-11-02 12:39:01 -07002124 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2125 ExternalArray::kAlignedSize);
2126 if (!maybe_obj->ToObject(&obj)) return false;
2127 }
Steve Block3ce2e202009-11-05 08:53:23 +00002128 set_external_float_array_map(Map::cast(obj));
2129
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002130 { MaybeObject* maybe_obj =
2131 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2132 if (!maybe_obj->ToObject(&obj)) return false;
2133 }
2134 set_non_strict_arguments_elements_map(Map::cast(obj));
2135
Ben Murdoch257744e2011-11-30 15:57:28 +00002136 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2137 ExternalArray::kAlignedSize);
2138 if (!maybe_obj->ToObject(&obj)) return false;
2139 }
2140 set_external_double_array_map(Map::cast(obj));
2141
John Reck59135872010-11-02 12:39:01 -07002142 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2143 if (!maybe_obj->ToObject(&obj)) return false;
2144 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002145 set_code_map(Map::cast(obj));
2146
John Reck59135872010-11-02 12:39:01 -07002147 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2148 JSGlobalPropertyCell::kSize);
2149 if (!maybe_obj->ToObject(&obj)) return false;
2150 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002151 set_global_property_cell_map(Map::cast(obj));
2152
John Reck59135872010-11-02 12:39:01 -07002153 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2154 if (!maybe_obj->ToObject(&obj)) return false;
2155 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002156 set_one_pointer_filler_map(Map::cast(obj));
2157
John Reck59135872010-11-02 12:39:01 -07002158 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2159 if (!maybe_obj->ToObject(&obj)) return false;
2160 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002161 set_two_pointer_filler_map(Map::cast(obj));
2162
2163 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2164 const StructTable& entry = struct_table[i];
John Reck59135872010-11-02 12:39:01 -07002165 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2166 if (!maybe_obj->ToObject(&obj)) return false;
2167 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002168 roots_[entry.index] = Map::cast(obj);
2169 }
2170
John Reck59135872010-11-02 12:39:01 -07002171 { MaybeObject* maybe_obj =
2172 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2173 if (!maybe_obj->ToObject(&obj)) return false;
2174 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002175 set_hash_table_map(Map::cast(obj));
2176
John Reck59135872010-11-02 12:39:01 -07002177 { MaybeObject* maybe_obj =
2178 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2179 if (!maybe_obj->ToObject(&obj)) return false;
2180 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002181 set_function_context_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002182
John Reck59135872010-11-02 12:39:01 -07002183 { MaybeObject* maybe_obj =
2184 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2185 if (!maybe_obj->ToObject(&obj)) return false;
2186 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002187 set_catch_context_map(Map::cast(obj));
2188
John Reck59135872010-11-02 12:39:01 -07002189 { MaybeObject* maybe_obj =
2190 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2191 if (!maybe_obj->ToObject(&obj)) return false;
2192 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002193 set_with_context_map(Map::cast(obj));
2194
2195 { MaybeObject* maybe_obj =
2196 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2197 if (!maybe_obj->ToObject(&obj)) return false;
2198 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002199 set_block_context_map(Map::cast(obj));
2200
2201 { MaybeObject* maybe_obj =
2202 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2203 if (!maybe_obj->ToObject(&obj)) return false;
2204 }
Ben Murdochf87a2032010-10-22 12:50:53 +01002205 Map* global_context_map = Map::cast(obj);
2206 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2207 set_global_context_map(global_context_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002208
John Reck59135872010-11-02 12:39:01 -07002209 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2210 SharedFunctionInfo::kAlignedSize);
2211 if (!maybe_obj->ToObject(&obj)) return false;
2212 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002213 set_shared_function_info_map(Map::cast(obj));
2214
Steve Block1e0659c2011-05-24 12:43:12 +01002215 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2216 JSMessageObject::kSize);
2217 if (!maybe_obj->ToObject(&obj)) return false;
2218 }
2219 set_message_object_map(Map::cast(obj));
2220
Steve Block44f0eee2011-05-26 01:26:41 +01002221 ASSERT(!InNewSpace(empty_fixed_array()));
Steve Blocka7e24c12009-10-30 11:49:00 +00002222 return true;
2223}
2224
2225
John Reck59135872010-11-02 12:39:01 -07002226MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002227 // Statically ensure that it is safe to allocate heap numbers in paged
2228 // spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002229 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002230 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2231
John Reck59135872010-11-02 12:39:01 -07002232 Object* result;
2233 { MaybeObject* maybe_result =
2234 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2235 if (!maybe_result->ToObject(&result)) return maybe_result;
2236 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002237
Ben Murdochc7cc0282012-03-05 14:35:55 +00002238 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002239 HeapNumber::cast(result)->set_value(value);
2240 return result;
2241}
2242
2243
John Reck59135872010-11-02 12:39:01 -07002244MaybeObject* Heap::AllocateHeapNumber(double value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002245 // Use general version, if we're forced to always allocate.
2246 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2247
2248 // This version of AllocateHeapNumber is optimized for
2249 // allocation in new space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002250 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002251 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
John Reck59135872010-11-02 12:39:01 -07002252 Object* result;
2253 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2254 if (!maybe_result->ToObject(&result)) return maybe_result;
2255 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002256 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002257 HeapNumber::cast(result)->set_value(value);
2258 return result;
2259}
2260
2261
John Reck59135872010-11-02 12:39:01 -07002262MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2263 Object* result;
2264 { MaybeObject* maybe_result = AllocateRawCell();
2265 if (!maybe_result->ToObject(&result)) return maybe_result;
2266 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002267 HeapObject::cast(result)->set_map_no_write_barrier(
2268 global_property_cell_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002269 JSGlobalPropertyCell::cast(result)->set_value(value);
2270 return result;
2271}
2272
2273
John Reck59135872010-11-02 12:39:01 -07002274MaybeObject* Heap::CreateOddball(const char* to_string,
Steve Block44f0eee2011-05-26 01:26:41 +01002275 Object* to_number,
2276 byte kind) {
John Reck59135872010-11-02 12:39:01 -07002277 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002278 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07002279 if (!maybe_result->ToObject(&result)) return maybe_result;
2280 }
Steve Block44f0eee2011-05-26 01:26:41 +01002281 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
Steve Blocka7e24c12009-10-30 11:49:00 +00002282}
2283
2284
2285bool Heap::CreateApiObjects() {
2286 Object* obj;
2287
John Reck59135872010-11-02 12:39:01 -07002288 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2289 if (!maybe_obj->ToObject(&obj)) return false;
2290 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002291 // Don't use Smi-only elements optimizations for objects with the neander
2292 // map. There are too many cases where element values are set directly with a
2293 // bottleneck to trap the Smi-only -> fast elements transition, and there
2294 // appears to be no benefit for optimize this case.
2295 Map* new_neander_map = Map::cast(obj);
2296 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2297 set_neander_map(new_neander_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002298
Steve Block44f0eee2011-05-26 01:26:41 +01002299 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
John Reck59135872010-11-02 12:39:01 -07002300 if (!maybe_obj->ToObject(&obj)) return false;
2301 }
2302 Object* elements;
2303 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2304 if (!maybe_elements->ToObject(&elements)) return false;
2305 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002306 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2307 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2308 set_message_listeners(JSObject::cast(obj));
2309
2310 return true;
2311}
2312
2313
Steve Blocka7e24c12009-10-30 11:49:00 +00002314void Heap::CreateJSEntryStub() {
2315 JSEntryStub stub;
2316 set_js_entry_code(*stub.GetCode());
2317}
2318
2319
2320void Heap::CreateJSConstructEntryStub() {
2321 JSConstructEntryStub stub;
2322 set_js_construct_entry_code(*stub.GetCode());
2323}
2324
2325
2326void Heap::CreateFixedStubs() {
2327 // Here we create roots for fixed stubs. They are needed at GC
2328 // for cooking and uncooking (check out frames.cc).
2329 // The eliminates the need for doing dictionary lookup in the
2330 // stub cache for these stubs.
2331 HandleScope scope;
2332 // gcc-4.4 has problem generating correct code of following snippet:
Steve Block44f0eee2011-05-26 01:26:41 +01002333 // { JSEntryStub stub;
2334 // js_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002335 // }
Steve Block44f0eee2011-05-26 01:26:41 +01002336 // { JSConstructEntryStub stub;
2337 // js_construct_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002338 // }
2339 // To workaround the problem, make separate functions without inlining.
Steve Blocka7e24c12009-10-30 11:49:00 +00002340 Heap::CreateJSEntryStub();
2341 Heap::CreateJSConstructEntryStub();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002342
2343 // Create stubs that should be there, so we don't unexpectedly have to
2344 // create them if we need them during the creation of another stub.
2345 // Stub creation mixes raw pointers and handles in an unsafe manner so
2346 // we cannot create stubs while we are creating stubs.
2347 CodeStub::GenerateStubsAheadOfTime();
Steve Blocka7e24c12009-10-30 11:49:00 +00002348}
2349
2350
2351bool Heap::CreateInitialObjects() {
2352 Object* obj;
2353
2354 // The -0 value must be set before NumberFromDouble works.
John Reck59135872010-11-02 12:39:01 -07002355 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2356 if (!maybe_obj->ToObject(&obj)) return false;
2357 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002358 set_minus_zero_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002359 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2360
John Reck59135872010-11-02 12:39:01 -07002361 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2362 if (!maybe_obj->ToObject(&obj)) return false;
2363 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002364 set_nan_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002365
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002366 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
John Reck59135872010-11-02 12:39:01 -07002367 if (!maybe_obj->ToObject(&obj)) return false;
2368 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002369 set_infinity_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002370
Ben Murdochc7cc0282012-03-05 14:35:55 +00002371 // The hole has not been created yet, but we want to put something
2372 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2373 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2374
Steve Blocka7e24c12009-10-30 11:49:00 +00002375 // Allocate initial symbol table.
John Reck59135872010-11-02 12:39:01 -07002376 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2377 if (!maybe_obj->ToObject(&obj)) return false;
2378 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002379 // Don't use set_symbol_table() due to asserts.
2380 roots_[kSymbolTableRootIndex] = obj;
2381
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002382 // Finish initializing oddballs after creating symboltable.
John Reck59135872010-11-02 12:39:01 -07002383 { MaybeObject* maybe_obj =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002384 undefined_value()->Initialize("undefined",
2385 nan_value(),
2386 Oddball::kUndefined);
2387 if (!maybe_obj->ToObject(&obj)) return false;
2388 }
2389
2390 // Initialize the null_value.
2391 { MaybeObject* maybe_obj =
2392 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
John Reck59135872010-11-02 12:39:01 -07002393 if (!maybe_obj->ToObject(&obj)) return false;
2394 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002395
Steve Block44f0eee2011-05-26 01:26:41 +01002396 { MaybeObject* maybe_obj = CreateOddball("true",
2397 Smi::FromInt(1),
2398 Oddball::kTrue);
John Reck59135872010-11-02 12:39:01 -07002399 if (!maybe_obj->ToObject(&obj)) return false;
2400 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002401 set_true_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002402
Steve Block44f0eee2011-05-26 01:26:41 +01002403 { MaybeObject* maybe_obj = CreateOddball("false",
2404 Smi::FromInt(0),
2405 Oddball::kFalse);
John Reck59135872010-11-02 12:39:01 -07002406 if (!maybe_obj->ToObject(&obj)) return false;
2407 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002408 set_false_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002409
Steve Block44f0eee2011-05-26 01:26:41 +01002410 { MaybeObject* maybe_obj = CreateOddball("hole",
2411 Smi::FromInt(-1),
2412 Oddball::kTheHole);
John Reck59135872010-11-02 12:39:01 -07002413 if (!maybe_obj->ToObject(&obj)) return false;
2414 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002415 set_the_hole_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002416
Ben Murdoch086aeea2011-05-13 15:57:08 +01002417 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002418 Smi::FromInt(-2),
Steve Block44f0eee2011-05-26 01:26:41 +01002419 Oddball::kArgumentMarker);
Ben Murdoch086aeea2011-05-13 15:57:08 +01002420 if (!maybe_obj->ToObject(&obj)) return false;
2421 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002422 set_arguments_marker(Oddball::cast(obj));
Ben Murdoch086aeea2011-05-13 15:57:08 +01002423
Steve Block44f0eee2011-05-26 01:26:41 +01002424 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002425 Smi::FromInt(-3),
Steve Block44f0eee2011-05-26 01:26:41 +01002426 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002427 if (!maybe_obj->ToObject(&obj)) return false;
2428 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002429 set_no_interceptor_result_sentinel(obj);
2430
Steve Block44f0eee2011-05-26 01:26:41 +01002431 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002432 Smi::FromInt(-4),
Steve Block44f0eee2011-05-26 01:26:41 +01002433 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002434 if (!maybe_obj->ToObject(&obj)) return false;
2435 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002436 set_termination_exception(obj);
2437
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002438 { MaybeObject* maybe_obj = CreateOddball("frame_alignment_marker",
2439 Smi::FromInt(-5),
2440 Oddball::kOther);
2441 if (!maybe_obj->ToObject(&obj)) return false;
2442 }
2443 set_frame_alignment_marker(Oddball::cast(obj));
2444 STATIC_ASSERT(Oddball::kLeastHiddenOddballNumber == -5);
2445
Steve Blocka7e24c12009-10-30 11:49:00 +00002446 // Allocate the empty string.
John Reck59135872010-11-02 12:39:01 -07002447 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2448 if (!maybe_obj->ToObject(&obj)) return false;
2449 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002450 set_empty_string(String::cast(obj));
2451
2452 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
John Reck59135872010-11-02 12:39:01 -07002453 { MaybeObject* maybe_obj =
2454 LookupAsciiSymbol(constant_symbol_table[i].contents);
2455 if (!maybe_obj->ToObject(&obj)) return false;
2456 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002457 roots_[constant_symbol_table[i].index] = String::cast(obj);
2458 }
2459
2460 // Allocate the hidden symbol which is used to identify the hidden properties
2461 // in JSObjects. The hash code has a special value so that it will not match
2462 // the empty string when searching for the property. It cannot be part of the
2463 // loop above because it needs to be allocated manually with the special
2464 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2465 // that it will always be at the first entry in property descriptors.
John Reck59135872010-11-02 12:39:01 -07002466 { MaybeObject* maybe_obj =
2467 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2468 if (!maybe_obj->ToObject(&obj)) return false;
2469 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002470 hidden_symbol_ = String::cast(obj);
2471
Ben Murdoch257744e2011-11-30 15:57:28 +00002472 // Allocate the foreign for __proto__.
John Reck59135872010-11-02 12:39:01 -07002473 { MaybeObject* maybe_obj =
Ben Murdoch257744e2011-11-30 15:57:28 +00002474 AllocateForeign((Address) &Accessors::ObjectPrototype);
John Reck59135872010-11-02 12:39:01 -07002475 if (!maybe_obj->ToObject(&obj)) return false;
2476 }
Ben Murdoch257744e2011-11-30 15:57:28 +00002477 set_prototype_accessors(Foreign::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002478
2479 // Allocate the code_stubs dictionary. The initial size is set to avoid
2480 // expanding the dictionary during bootstrapping.
Ben Murdochc7cc0282012-03-05 14:35:55 +00002481 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
John Reck59135872010-11-02 12:39:01 -07002482 if (!maybe_obj->ToObject(&obj)) return false;
2483 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002484 set_code_stubs(UnseededNumberDictionary::cast(obj));
2485
Steve Blocka7e24c12009-10-30 11:49:00 +00002486
2487 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2488 // is set to avoid expanding the dictionary during bootstrapping.
Ben Murdochc7cc0282012-03-05 14:35:55 +00002489 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
John Reck59135872010-11-02 12:39:01 -07002490 if (!maybe_obj->ToObject(&obj)) return false;
2491 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002492 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002493
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002494 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2495 if (!maybe_obj->ToObject(&obj)) return false;
2496 }
2497 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2498
Kristian Monsen25f61362010-05-21 11:50:48 +01002499 set_instanceof_cache_function(Smi::FromInt(0));
2500 set_instanceof_cache_map(Smi::FromInt(0));
2501 set_instanceof_cache_answer(Smi::FromInt(0));
2502
Steve Blocka7e24c12009-10-30 11:49:00 +00002503 CreateFixedStubs();
2504
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002505 // Allocate the dictionary of intrinsic function names.
John Reck59135872010-11-02 12:39:01 -07002506 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2507 if (!maybe_obj->ToObject(&obj)) return false;
2508 }
Steve Block44f0eee2011-05-26 01:26:41 +01002509 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2510 obj);
John Reck59135872010-11-02 12:39:01 -07002511 if (!maybe_obj->ToObject(&obj)) return false;
2512 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002513 set_intrinsic_function_names(StringDictionary::cast(obj));
2514
Leon Clarkee46be812010-01-19 14:06:41 +00002515 if (InitializeNumberStringCache()->IsFailure()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002516
Steve Block6ded16b2010-05-10 14:33:55 +01002517 // Allocate cache for single character ASCII strings.
John Reck59135872010-11-02 12:39:01 -07002518 { MaybeObject* maybe_obj =
2519 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2520 if (!maybe_obj->ToObject(&obj)) return false;
2521 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002522 set_single_character_string_cache(FixedArray::cast(obj));
2523
Ben Murdoch589d6972011-11-30 16:04:58 +00002524 // Allocate cache for string split.
2525 { MaybeObject* maybe_obj =
2526 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2527 if (!maybe_obj->ToObject(&obj)) return false;
2528 }
2529 set_string_split_cache(FixedArray::cast(obj));
2530
Steve Blocka7e24c12009-10-30 11:49:00 +00002531 // Allocate cache for external strings pointing to native source code.
John Reck59135872010-11-02 12:39:01 -07002532 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2533 if (!maybe_obj->ToObject(&obj)) return false;
2534 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002535 set_natives_source_cache(FixedArray::cast(obj));
2536
Steve Block44f0eee2011-05-26 01:26:41 +01002537 // Handling of script id generation is in FACTORY->NewScript.
Steve Blocka7e24c12009-10-30 11:49:00 +00002538 set_last_script_id(undefined_value());
2539
2540 // Initialize keyed lookup cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002541 isolate_->keyed_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002542
2543 // Initialize context slot cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002544 isolate_->context_slot_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002545
2546 // Initialize descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002547 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002548
2549 // Initialize compilation cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002550 isolate_->compilation_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002551
2552 return true;
2553}
2554
2555
Ben Murdoch589d6972011-11-30 16:04:58 +00002556Object* StringSplitCache::Lookup(
2557 FixedArray* cache, String* string, String* pattern) {
2558 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2559 uint32_t hash = string->Hash();
2560 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2561 ~(kArrayEntriesPerCacheEntry - 1));
2562 if (cache->get(index + kStringOffset) == string &&
2563 cache->get(index + kPatternOffset) == pattern) {
2564 return cache->get(index + kArrayOffset);
2565 }
2566 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2567 if (cache->get(index + kStringOffset) == string &&
2568 cache->get(index + kPatternOffset) == pattern) {
2569 return cache->get(index + kArrayOffset);
2570 }
2571 return Smi::FromInt(0);
2572}
2573
2574
2575void StringSplitCache::Enter(Heap* heap,
2576 FixedArray* cache,
2577 String* string,
2578 String* pattern,
2579 FixedArray* array) {
2580 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2581 uint32_t hash = string->Hash();
2582 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2583 ~(kArrayEntriesPerCacheEntry - 1));
2584 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2585 cache->set(index + kStringOffset, string);
2586 cache->set(index + kPatternOffset, pattern);
2587 cache->set(index + kArrayOffset, array);
2588 } else {
2589 uint32_t index2 =
2590 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2591 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2592 cache->set(index2 + kStringOffset, string);
2593 cache->set(index2 + kPatternOffset, pattern);
2594 cache->set(index2 + kArrayOffset, array);
2595 } else {
2596 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2597 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2598 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2599 cache->set(index + kStringOffset, string);
2600 cache->set(index + kPatternOffset, pattern);
2601 cache->set(index + kArrayOffset, array);
2602 }
2603 }
2604 if (array->length() < 100) { // Limit how many new symbols we want to make.
2605 for (int i = 0; i < array->length(); i++) {
2606 String* str = String::cast(array->get(i));
2607 Object* symbol;
2608 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2609 if (maybe_symbol->ToObject(&symbol)) {
2610 array->set(i, symbol);
2611 }
2612 }
2613 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002614 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
Ben Murdoch589d6972011-11-30 16:04:58 +00002615}
2616
2617
2618void StringSplitCache::Clear(FixedArray* cache) {
2619 for (int i = 0; i < kStringSplitCacheSize; i++) {
2620 cache->set(i, Smi::FromInt(0));
2621 }
2622}
2623
2624
John Reck59135872010-11-02 12:39:01 -07002625MaybeObject* Heap::InitializeNumberStringCache() {
Leon Clarkee46be812010-01-19 14:06:41 +00002626 // Compute the size of the number string cache based on the max heap size.
2627 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
2628 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
2629 int number_string_cache_size = max_semispace_size_ / 512;
2630 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
John Reck59135872010-11-02 12:39:01 -07002631 Object* obj;
2632 MaybeObject* maybe_obj =
2633 AllocateFixedArray(number_string_cache_size * 2, TENURED);
2634 if (maybe_obj->ToObject(&obj)) set_number_string_cache(FixedArray::cast(obj));
2635 return maybe_obj;
Leon Clarkee46be812010-01-19 14:06:41 +00002636}
2637
2638
2639void Heap::FlushNumberStringCache() {
2640 // Flush the number to string cache.
2641 int len = number_string_cache()->length();
2642 for (int i = 0; i < len; i++) {
Steve Block44f0eee2011-05-26 01:26:41 +01002643 number_string_cache()->set_undefined(this, i);
Leon Clarkee46be812010-01-19 14:06:41 +00002644 }
2645}
2646
2647
Steve Blocka7e24c12009-10-30 11:49:00 +00002648static inline int double_get_hash(double d) {
2649 DoubleRepresentation rep(d);
Leon Clarkee46be812010-01-19 14:06:41 +00002650 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
Steve Blocka7e24c12009-10-30 11:49:00 +00002651}
2652
2653
2654static inline int smi_get_hash(Smi* smi) {
Leon Clarkee46be812010-01-19 14:06:41 +00002655 return smi->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002656}
2657
2658
Steve Blocka7e24c12009-10-30 11:49:00 +00002659Object* Heap::GetNumberStringCache(Object* number) {
2660 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002661 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002662 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002663 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002664 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002665 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002666 }
2667 Object* key = number_string_cache()->get(hash * 2);
2668 if (key == number) {
2669 return String::cast(number_string_cache()->get(hash * 2 + 1));
2670 } else if (key->IsHeapNumber() &&
2671 number->IsHeapNumber() &&
2672 key->Number() == number->Number()) {
2673 return String::cast(number_string_cache()->get(hash * 2 + 1));
2674 }
2675 return undefined_value();
2676}
2677
2678
2679void Heap::SetNumberStringCache(Object* number, String* string) {
2680 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002681 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002682 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002683 hash = smi_get_hash(Smi::cast(number)) & mask;
Leon Clarke4515c472010-02-03 11:58:03 +00002684 number_string_cache()->set(hash * 2, Smi::cast(number));
Steve Blocka7e24c12009-10-30 11:49:00 +00002685 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002686 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002687 number_string_cache()->set(hash * 2, number);
2688 }
2689 number_string_cache()->set(hash * 2 + 1, string);
2690}
2691
2692
John Reck59135872010-11-02 12:39:01 -07002693MaybeObject* Heap::NumberToString(Object* number,
2694 bool check_number_string_cache) {
Steve Block44f0eee2011-05-26 01:26:41 +01002695 isolate_->counters()->number_to_string_runtime()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002696 if (check_number_string_cache) {
2697 Object* cached = GetNumberStringCache(number);
2698 if (cached != undefined_value()) {
2699 return cached;
2700 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002701 }
2702
2703 char arr[100];
2704 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2705 const char* str;
2706 if (number->IsSmi()) {
2707 int num = Smi::cast(number)->value();
2708 str = IntToCString(num, buffer);
2709 } else {
2710 double num = HeapNumber::cast(number)->value();
2711 str = DoubleToCString(num, buffer);
2712 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002713
John Reck59135872010-11-02 12:39:01 -07002714 Object* js_string;
2715 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2716 if (maybe_js_string->ToObject(&js_string)) {
2717 SetNumberStringCache(number, String::cast(js_string));
Steve Blocka7e24c12009-10-30 11:49:00 +00002718 }
John Reck59135872010-11-02 12:39:01 -07002719 return maybe_js_string;
Steve Blocka7e24c12009-10-30 11:49:00 +00002720}
2721
2722
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002723MaybeObject* Heap::Uint32ToString(uint32_t value,
2724 bool check_number_string_cache) {
2725 Object* number;
2726 MaybeObject* maybe = NumberFromUint32(value);
2727 if (!maybe->To<Object>(&number)) return maybe;
2728 return NumberToString(number, check_number_string_cache);
2729}
2730
2731
Steve Block3ce2e202009-11-05 08:53:23 +00002732Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2733 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2734}
2735
2736
2737Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2738 ExternalArrayType array_type) {
2739 switch (array_type) {
2740 case kExternalByteArray:
2741 return kExternalByteArrayMapRootIndex;
2742 case kExternalUnsignedByteArray:
2743 return kExternalUnsignedByteArrayMapRootIndex;
2744 case kExternalShortArray:
2745 return kExternalShortArrayMapRootIndex;
2746 case kExternalUnsignedShortArray:
2747 return kExternalUnsignedShortArrayMapRootIndex;
2748 case kExternalIntArray:
2749 return kExternalIntArrayMapRootIndex;
2750 case kExternalUnsignedIntArray:
2751 return kExternalUnsignedIntArrayMapRootIndex;
2752 case kExternalFloatArray:
2753 return kExternalFloatArrayMapRootIndex;
Ben Murdoch257744e2011-11-30 15:57:28 +00002754 case kExternalDoubleArray:
2755 return kExternalDoubleArrayMapRootIndex;
Steve Block44f0eee2011-05-26 01:26:41 +01002756 case kExternalPixelArray:
2757 return kExternalPixelArrayMapRootIndex;
Steve Block3ce2e202009-11-05 08:53:23 +00002758 default:
2759 UNREACHABLE();
2760 return kUndefinedValueRootIndex;
2761 }
2762}
2763
2764
John Reck59135872010-11-02 12:39:01 -07002765MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01002766 // We need to distinguish the minus zero value and this cannot be
2767 // done after conversion to int. Doing this by comparing bit
2768 // patterns is faster than using fpclassify() et al.
2769 static const DoubleRepresentation minus_zero(-0.0);
2770
2771 DoubleRepresentation rep(value);
2772 if (rep.bits == minus_zero.bits) {
2773 return AllocateHeapNumber(-0.0, pretenure);
2774 }
2775
2776 int int_value = FastD2I(value);
2777 if (value == int_value && Smi::IsValid(int_value)) {
2778 return Smi::FromInt(int_value);
2779 }
2780
2781 // Materialize the value in the heap.
2782 return AllocateHeapNumber(value, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00002783}
2784
2785
Ben Murdoch257744e2011-11-30 15:57:28 +00002786MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2787 // Statically ensure that it is safe to allocate foreigns in paged spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002788 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002789 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002790 Foreign* result;
2791 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2792 if (!maybe_result->To(&result)) return maybe_result;
2793 result->set_foreign_address(address);
Steve Blocka7e24c12009-10-30 11:49:00 +00002794 return result;
2795}
2796
2797
John Reck59135872010-11-02 12:39:01 -07002798MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002799 SharedFunctionInfo* share;
2800 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2801 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
Steve Blocka7e24c12009-10-30 11:49:00 +00002802
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002803 // Set pointer fields.
Steve Blocka7e24c12009-10-30 11:49:00 +00002804 share->set_name(name);
Steve Block44f0eee2011-05-26 01:26:41 +01002805 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
Steve Blocka7e24c12009-10-30 11:49:00 +00002806 share->set_code(illegal);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002807 share->set_scope_info(ScopeInfo::Empty());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002808 Code* construct_stub =
2809 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
Steve Blocka7e24c12009-10-30 11:49:00 +00002810 share->set_construct_stub(construct_stub);
Steve Blocka7e24c12009-10-30 11:49:00 +00002811 share->set_instance_class_name(Object_symbol());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002812 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
2813 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
2814 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
2815 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
2816 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
2817 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002818 share->set_deopt_counter(Smi::FromInt(FLAG_deopt_every_n_times));
2819
2820 // Set integer fields (smi or int, depending on the architecture).
2821 share->set_length(0);
2822 share->set_formal_parameter_count(0);
2823 share->set_expected_nof_properties(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002824 share->set_num_literals(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002825 share->set_start_position_and_type(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002826 share->set_end_position(0);
2827 share->set_function_token_position(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002828 // All compiler hints default to false or 0.
2829 share->set_compiler_hints(0);
2830 share->set_this_property_assignments_count(0);
2831 share->set_opt_count(0);
2832
2833 return share;
Steve Blocka7e24c12009-10-30 11:49:00 +00002834}
2835
2836
Steve Block1e0659c2011-05-24 12:43:12 +01002837MaybeObject* Heap::AllocateJSMessageObject(String* type,
2838 JSArray* arguments,
2839 int start_position,
2840 int end_position,
2841 Object* script,
2842 Object* stack_trace,
2843 Object* stack_frames) {
2844 Object* result;
2845 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2846 if (!maybe_result->ToObject(&result)) return maybe_result;
2847 }
2848 JSMessageObject* message = JSMessageObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002849 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2850 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Block1e0659c2011-05-24 12:43:12 +01002851 message->set_type(type);
2852 message->set_arguments(arguments);
2853 message->set_start_position(start_position);
2854 message->set_end_position(end_position);
2855 message->set_script(script);
2856 message->set_stack_trace(stack_trace);
2857 message->set_stack_frames(stack_frames);
2858 return result;
2859}
2860
2861
2862
Steve Blockd0582a62009-12-15 09:54:21 +00002863// Returns true for a character in a range. Both limits are inclusive.
2864static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2865 // This makes uses of the the unsigned wraparound.
2866 return character - from <= to - from;
2867}
2868
2869
John Reck59135872010-11-02 12:39:01 -07002870MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
Steve Block44f0eee2011-05-26 01:26:41 +01002871 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07002872 uint32_t c1,
2873 uint32_t c2) {
Steve Blockd0582a62009-12-15 09:54:21 +00002874 String* symbol;
2875 // Numeric strings have a different hash algorithm not known by
2876 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2877 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
Steve Block44f0eee2011-05-26 01:26:41 +01002878 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
Steve Blockd0582a62009-12-15 09:54:21 +00002879 return symbol;
2880 // Now we know the length is 2, we might as well make use of that fact
2881 // when building the new string.
2882 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2883 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
John Reck59135872010-11-02 12:39:01 -07002884 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002885 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
John Reck59135872010-11-02 12:39:01 -07002886 if (!maybe_result->ToObject(&result)) return maybe_result;
2887 }
Steve Blockd0582a62009-12-15 09:54:21 +00002888 char* dest = SeqAsciiString::cast(result)->GetChars();
2889 dest[0] = c1;
2890 dest[1] = c2;
2891 return result;
2892 } else {
John Reck59135872010-11-02 12:39:01 -07002893 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002894 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
John Reck59135872010-11-02 12:39:01 -07002895 if (!maybe_result->ToObject(&result)) return maybe_result;
2896 }
Steve Blockd0582a62009-12-15 09:54:21 +00002897 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2898 dest[0] = c1;
2899 dest[1] = c2;
2900 return result;
2901 }
2902}
2903
2904
John Reck59135872010-11-02 12:39:01 -07002905MaybeObject* Heap::AllocateConsString(String* first, String* second) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002906 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002907 if (first_length == 0) {
2908 return second;
2909 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002910
2911 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002912 if (second_length == 0) {
2913 return first;
2914 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002915
2916 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00002917
2918 // Optimization for 2-byte strings often used as keys in a decompression
2919 // dictionary. Check whether we already have the string in the symbol
2920 // table to prevent creation of many unneccesary strings.
2921 if (length == 2) {
2922 unsigned c1 = first->Get(0);
2923 unsigned c2 = second->Get(0);
Steve Block44f0eee2011-05-26 01:26:41 +01002924 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blockd0582a62009-12-15 09:54:21 +00002925 }
2926
Steve Block6ded16b2010-05-10 14:33:55 +01002927 bool first_is_ascii = first->IsAsciiRepresentation();
2928 bool second_is_ascii = second->IsAsciiRepresentation();
2929 bool is_ascii = first_is_ascii && second_is_ascii;
Steve Blocka7e24c12009-10-30 11:49:00 +00002930
2931 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00002932 // of the new cons string is too large.
2933 if (length > String::kMaxLength || length < 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01002934 isolate()->context()->mark_out_of_memory();
Steve Blocka7e24c12009-10-30 11:49:00 +00002935 return Failure::OutOfMemoryException();
2936 }
2937
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002938 bool is_ascii_data_in_two_byte_string = false;
2939 if (!is_ascii) {
2940 // At least one of the strings uses two-byte representation so we
Ben Murdochc7cc0282012-03-05 14:35:55 +00002941 // can't use the fast case code for short ASCII strings below, but
2942 // we can try to save memory if all chars actually fit in ASCII.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002943 is_ascii_data_in_two_byte_string =
2944 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
2945 if (is_ascii_data_in_two_byte_string) {
Steve Block44f0eee2011-05-26 01:26:41 +01002946 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002947 }
2948 }
2949
Steve Blocka7e24c12009-10-30 11:49:00 +00002950 // If the resulting string is small make a flat string.
Ben Murdochc7cc0282012-03-05 14:35:55 +00002951 if (length < ConsString::kMinLength) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002952 // Note that neither of the two inputs can be a slice because:
Ben Murdochc7cc0282012-03-05 14:35:55 +00002953 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
Steve Blocka7e24c12009-10-30 11:49:00 +00002954 ASSERT(first->IsFlat());
2955 ASSERT(second->IsFlat());
2956 if (is_ascii) {
John Reck59135872010-11-02 12:39:01 -07002957 Object* result;
2958 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2959 if (!maybe_result->ToObject(&result)) return maybe_result;
2960 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002961 // Copy the characters into the new object.
2962 char* dest = SeqAsciiString::cast(result)->GetChars();
2963 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00002964 const char* src;
2965 if (first->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002966 src = ExternalAsciiString::cast(first)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00002967 } else {
2968 src = SeqAsciiString::cast(first)->GetChars();
2969 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002970 for (int i = 0; i < first_length; i++) *dest++ = src[i];
2971 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00002972 if (second->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002973 src = ExternalAsciiString::cast(second)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00002974 } else {
2975 src = SeqAsciiString::cast(second)->GetChars();
2976 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002977 for (int i = 0; i < second_length; i++) *dest++ = src[i];
2978 return result;
2979 } else {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002980 if (is_ascii_data_in_two_byte_string) {
John Reck59135872010-11-02 12:39:01 -07002981 Object* result;
2982 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2983 if (!maybe_result->ToObject(&result)) return maybe_result;
2984 }
Steve Block6ded16b2010-05-10 14:33:55 +01002985 // Copy the characters into the new object.
2986 char* dest = SeqAsciiString::cast(result)->GetChars();
2987 String::WriteToFlat(first, dest, 0, first_length);
2988 String::WriteToFlat(second, dest + first_length, 0, second_length);
Steve Block44f0eee2011-05-26 01:26:41 +01002989 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002990 return result;
2991 }
2992
John Reck59135872010-11-02 12:39:01 -07002993 Object* result;
2994 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
2995 if (!maybe_result->ToObject(&result)) return maybe_result;
2996 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002997 // Copy the characters into the new object.
2998 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2999 String::WriteToFlat(first, dest, 0, first_length);
3000 String::WriteToFlat(second, dest + first_length, 0, second_length);
3001 return result;
3002 }
3003 }
3004
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003005 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3006 cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00003007
John Reck59135872010-11-02 12:39:01 -07003008 Object* result;
3009 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3010 if (!maybe_result->ToObject(&result)) return maybe_result;
3011 }
Leon Clarke4515c472010-02-03 11:58:03 +00003012
3013 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003014 ConsString* cons_string = ConsString::cast(result);
Leon Clarke4515c472010-02-03 11:58:03 +00003015 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003016 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00003017 cons_string->set_hash_field(String::kEmptyHashField);
3018 cons_string->set_first(first, mode);
3019 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003020 return result;
3021}
3022
3023
John Reck59135872010-11-02 12:39:01 -07003024MaybeObject* Heap::AllocateSubString(String* buffer,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003025 int start,
3026 int end,
3027 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003028 int length = end - start;
Ben Murdochc7cc0282012-03-05 14:35:55 +00003029 if (length <= 0) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003030 return empty_string();
3031 } else if (length == 1) {
Steve Block44f0eee2011-05-26 01:26:41 +01003032 return LookupSingleCharacterStringFromCode(buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00003033 } else if (length == 2) {
3034 // Optimization for 2-byte strings often used as keys in a decompression
3035 // dictionary. Check whether we already have the string in the symbol
3036 // table to prevent creation of many unneccesary strings.
3037 unsigned c1 = buffer->Get(start);
3038 unsigned c2 = buffer->Get(start + 1);
Steve Block44f0eee2011-05-26 01:26:41 +01003039 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00003040 }
3041
3042 // Make an attempt to flatten the buffer to reduce access time.
Leon Clarkef7060e22010-06-03 12:02:55 +01003043 buffer = buffer->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00003044
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003045 if (!FLAG_string_slices ||
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003046 !buffer->IsFlat() ||
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003047 length < SlicedString::kMinLength ||
3048 pretenure == TENURED) {
3049 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003050 // WriteToFlat takes care of the case when an indirect string has a
3051 // different encoding from its underlying string. These encodings may
3052 // differ because of externalization.
3053 bool is_ascii = buffer->IsAsciiRepresentation();
3054 { MaybeObject* maybe_result = is_ascii
3055 ? AllocateRawAsciiString(length, pretenure)
3056 : AllocateRawTwoByteString(length, pretenure);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003057 if (!maybe_result->ToObject(&result)) return maybe_result;
3058 }
3059 String* string_result = String::cast(result);
3060 // Copy the characters into the new object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003061 if (is_ascii) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003062 ASSERT(string_result->IsAsciiRepresentation());
3063 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3064 String::WriteToFlat(buffer, dest, start, end);
3065 } else {
3066 ASSERT(string_result->IsTwoByteRepresentation());
3067 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3068 String::WriteToFlat(buffer, dest, start, end);
3069 }
3070 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003071 }
Steve Blockd0582a62009-12-15 09:54:21 +00003072
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003073 ASSERT(buffer->IsFlat());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003074#if DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003075 if (FLAG_verify_heap) {
3076 buffer->StringVerify();
3077 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003078#endif
3079
3080 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003081 // When slicing an indirect string we use its encoding for a newly created
3082 // slice and don't check the encoding of the underlying string. This is safe
3083 // even if the encodings are different because of externalization. If an
3084 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3085 // codes of the underlying string must still fit into ASCII (because
3086 // externalization must not change char codes).
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003087 { Map* map = buffer->IsAsciiRepresentation()
3088 ? sliced_ascii_string_map()
3089 : sliced_string_map();
3090 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3091 if (!maybe_result->ToObject(&result)) return maybe_result;
3092 }
3093
3094 AssertNoAllocation no_gc;
3095 SlicedString* sliced_string = SlicedString::cast(result);
3096 sliced_string->set_length(length);
3097 sliced_string->set_hash_field(String::kEmptyHashField);
3098 if (buffer->IsConsString()) {
3099 ConsString* cons = ConsString::cast(buffer);
3100 ASSERT(cons->second()->length() == 0);
3101 sliced_string->set_parent(cons->first());
3102 sliced_string->set_offset(start);
3103 } else if (buffer->IsSlicedString()) {
3104 // Prevent nesting sliced strings.
3105 SlicedString* parent_slice = SlicedString::cast(buffer);
3106 sliced_string->set_parent(parent_slice->parent());
3107 sliced_string->set_offset(start + parent_slice->offset());
3108 } else {
3109 sliced_string->set_parent(buffer);
3110 sliced_string->set_offset(start);
3111 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003112 ASSERT(sliced_string->parent()->IsSeqString() ||
3113 sliced_string->parent()->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +00003114 return result;
3115}
3116
3117
John Reck59135872010-11-02 12:39:01 -07003118MaybeObject* Heap::AllocateExternalStringFromAscii(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003119 const ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003120 size_t length = resource->length();
3121 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003122 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003123 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00003124 }
3125
Steve Blockd0582a62009-12-15 09:54:21 +00003126 Map* map = external_ascii_string_map();
John Reck59135872010-11-02 12:39:01 -07003127 Object* result;
3128 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3129 if (!maybe_result->ToObject(&result)) return maybe_result;
3130 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003131
3132 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003133 external_string->set_length(static_cast<int>(length));
3134 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003135 external_string->set_resource(resource);
3136
3137 return result;
3138}
3139
3140
John Reck59135872010-11-02 12:39:01 -07003141MaybeObject* Heap::AllocateExternalStringFromTwoByte(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003142 const ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003143 size_t length = resource->length();
3144 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003145 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003146 return Failure::OutOfMemoryException();
3147 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003148
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003149 // For small strings we check whether the resource contains only
Steve Block9fac8402011-05-12 15:51:54 +01003150 // ASCII characters. If yes, we use a different string map.
3151 static const size_t kAsciiCheckLengthLimit = 32;
3152 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3153 String::IsAscii(resource->data(), static_cast<int>(length));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003154 Map* map = is_ascii ?
Steve Block44f0eee2011-05-26 01:26:41 +01003155 external_string_with_ascii_data_map() : external_string_map();
John Reck59135872010-11-02 12:39:01 -07003156 Object* result;
3157 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3158 if (!maybe_result->ToObject(&result)) return maybe_result;
3159 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003160
3161 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003162 external_string->set_length(static_cast<int>(length));
3163 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003164 external_string->set_resource(resource);
3165
3166 return result;
3167}
3168
3169
John Reck59135872010-11-02 12:39:01 -07003170MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003171 if (code <= String::kMaxAsciiCharCode) {
Steve Block44f0eee2011-05-26 01:26:41 +01003172 Object* value = single_character_string_cache()->get(code);
3173 if (value != undefined_value()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00003174
3175 char buffer[1];
3176 buffer[0] = static_cast<char>(code);
John Reck59135872010-11-02 12:39:01 -07003177 Object* result;
3178 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00003179
John Reck59135872010-11-02 12:39:01 -07003180 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003181 single_character_string_cache()->set(code, result);
Steve Blocka7e24c12009-10-30 11:49:00 +00003182 return result;
3183 }
3184
John Reck59135872010-11-02 12:39:01 -07003185 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01003186 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
John Reck59135872010-11-02 12:39:01 -07003187 if (!maybe_result->ToObject(&result)) return maybe_result;
3188 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003189 String* answer = String::cast(result);
3190 answer->Set(0, code);
3191 return answer;
3192}
3193
3194
John Reck59135872010-11-02 12:39:01 -07003195MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003196 if (length < 0 || length > ByteArray::kMaxLength) {
3197 return Failure::OutOfMemoryException();
3198 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003199 if (pretenure == NOT_TENURED) {
3200 return AllocateByteArray(length);
3201 }
3202 int size = ByteArray::SizeFor(length);
John Reck59135872010-11-02 12:39:01 -07003203 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003204 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
John Reck59135872010-11-02 12:39:01 -07003205 ? old_data_space_->AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003206 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
John Reck59135872010-11-02 12:39:01 -07003207 if (!maybe_result->ToObject(&result)) return maybe_result;
3208 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003209
Ben Murdochc7cc0282012-03-05 14:35:55 +00003210 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3211 byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003212 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003213 return result;
3214}
3215
3216
John Reck59135872010-11-02 12:39:01 -07003217MaybeObject* Heap::AllocateByteArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00003218 if (length < 0 || length > ByteArray::kMaxLength) {
3219 return Failure::OutOfMemoryException();
3220 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003221 int size = ByteArray::SizeFor(length);
3222 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003223 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003224 Object* result;
3225 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3226 if (!maybe_result->ToObject(&result)) return maybe_result;
3227 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003228
Ben Murdochc7cc0282012-03-05 14:35:55 +00003229 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3230 byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003231 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003232 return result;
3233}
3234
3235
3236void Heap::CreateFillerObjectAt(Address addr, int size) {
3237 if (size == 0) return;
3238 HeapObject* filler = HeapObject::FromAddress(addr);
3239 if (size == kPointerSize) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003240 filler->set_map_no_write_barrier(one_pointer_filler_map());
Steve Block6ded16b2010-05-10 14:33:55 +01003241 } else if (size == 2 * kPointerSize) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003242 filler->set_map_no_write_barrier(two_pointer_filler_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003243 } else {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003244 filler->set_map_no_write_barrier(free_space_map());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003245 FreeSpace::cast(filler)->set_size(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003246 }
3247}
3248
3249
John Reck59135872010-11-02 12:39:01 -07003250MaybeObject* Heap::AllocateExternalArray(int length,
3251 ExternalArrayType array_type,
3252 void* external_pointer,
3253 PretenureFlag pretenure) {
Steve Block3ce2e202009-11-05 08:53:23 +00003254 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003255 Object* result;
3256 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3257 space,
3258 OLD_DATA_SPACE);
3259 if (!maybe_result->ToObject(&result)) return maybe_result;
3260 }
Steve Block3ce2e202009-11-05 08:53:23 +00003261
Ben Murdochc7cc0282012-03-05 14:35:55 +00003262 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
Steve Block3ce2e202009-11-05 08:53:23 +00003263 MapForExternalArrayType(array_type));
3264 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3265 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3266 external_pointer);
3267
3268 return result;
3269}
3270
3271
John Reck59135872010-11-02 12:39:01 -07003272MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3273 Code::Flags flags,
Steve Block44f0eee2011-05-26 01:26:41 +01003274 Handle<Object> self_reference,
3275 bool immovable) {
Leon Clarkeac952652010-07-15 11:15:24 +01003276 // Allocate ByteArray before the Code object, so that we do not risk
3277 // leaving uninitialized Code object (and breaking the heap).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003278 ByteArray* reloc_info;
3279 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3280 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
Leon Clarkeac952652010-07-15 11:15:24 +01003281
Steve Block44f0eee2011-05-26 01:26:41 +01003282 // Compute size.
Leon Clarkeac952652010-07-15 11:15:24 +01003283 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003284 int obj_size = Code::SizeFor(body_size);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003285 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
John Reck59135872010-11-02 12:39:01 -07003286 MaybeObject* maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003287 // Large code objects and code objects which should stay at a fixed address
3288 // are allocated in large object space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003289 if (obj_size > code_space()->AreaSize() || immovable) {
3290 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003291 } else {
John Reck59135872010-11-02 12:39:01 -07003292 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003293 }
3294
John Reck59135872010-11-02 12:39:01 -07003295 Object* result;
3296 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003297
3298 // Initialize the object
Ben Murdochc7cc0282012-03-05 14:35:55 +00003299 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003300 Code* code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003301 ASSERT(!isolate_->code_range()->exists() ||
3302 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003303 code->set_instruction_size(desc.instr_size);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003304 code->set_relocation_info(reloc_info);
Steve Blocka7e24c12009-10-30 11:49:00 +00003305 code->set_flags(flags);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003306 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3307 code->set_check_type(RECEIVER_MAP_CHECK);
3308 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003309 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3310 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
Ben Murdochc7cc0282012-03-05 14:35:55 +00003311 code->set_gc_metadata(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00003312 // Allow self references to created code object by patching the handle to
3313 // point to the newly allocated Code object.
3314 if (!self_reference.is_null()) {
3315 *(self_reference.location()) = code;
3316 }
3317 // Migrate generated code.
3318 // The generated code can contain Object** values (typically from handles)
3319 // that are dereferenced during the copy to point directly to the actual heap
3320 // objects. These pointers can include references to the code object itself,
3321 // through the self_reference parameter.
3322 code->CopyFrom(desc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003323
3324#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003325 if (FLAG_verify_heap) {
3326 code->Verify();
3327 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003328#endif
3329 return code;
3330}
3331
3332
John Reck59135872010-11-02 12:39:01 -07003333MaybeObject* Heap::CopyCode(Code* code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003334 // Allocate an object the same size as the code object.
3335 int obj_size = code->Size();
John Reck59135872010-11-02 12:39:01 -07003336 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003337 if (obj_size > code_space()->AreaSize()) {
3338 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003339 } else {
John Reck59135872010-11-02 12:39:01 -07003340 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003341 }
3342
John Reck59135872010-11-02 12:39:01 -07003343 Object* result;
3344 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003345
3346 // Copy code object.
3347 Address old_addr = code->address();
3348 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003349 CopyBlock(new_addr, old_addr, obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003350 // Relocate the copy.
3351 Code* new_code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003352 ASSERT(!isolate_->code_range()->exists() ||
3353 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003354 new_code->Relocate(new_addr - old_addr);
3355 return new_code;
3356}
3357
3358
John Reck59135872010-11-02 12:39:01 -07003359MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
Leon Clarkeac952652010-07-15 11:15:24 +01003360 // Allocate ByteArray before the Code object, so that we do not risk
3361 // leaving uninitialized Code object (and breaking the heap).
John Reck59135872010-11-02 12:39:01 -07003362 Object* reloc_info_array;
3363 { MaybeObject* maybe_reloc_info_array =
3364 AllocateByteArray(reloc_info.length(), TENURED);
3365 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3366 return maybe_reloc_info_array;
3367 }
3368 }
Leon Clarkeac952652010-07-15 11:15:24 +01003369
3370 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
Steve Block6ded16b2010-05-10 14:33:55 +01003371
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003372 int new_obj_size = Code::SizeFor(new_body_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003373
3374 Address old_addr = code->address();
3375
3376 size_t relocation_offset =
Leon Clarkeac952652010-07-15 11:15:24 +01003377 static_cast<size_t>(code->instruction_end() - old_addr);
Steve Block6ded16b2010-05-10 14:33:55 +01003378
John Reck59135872010-11-02 12:39:01 -07003379 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003380 if (new_obj_size > code_space()->AreaSize()) {
3381 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
Steve Block6ded16b2010-05-10 14:33:55 +01003382 } else {
John Reck59135872010-11-02 12:39:01 -07003383 maybe_result = code_space_->AllocateRaw(new_obj_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003384 }
3385
John Reck59135872010-11-02 12:39:01 -07003386 Object* result;
3387 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block6ded16b2010-05-10 14:33:55 +01003388
3389 // Copy code object.
3390 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3391
3392 // Copy header and instructions.
3393 memcpy(new_addr, old_addr, relocation_offset);
3394
Steve Block6ded16b2010-05-10 14:33:55 +01003395 Code* new_code = Code::cast(result);
Leon Clarkeac952652010-07-15 11:15:24 +01003396 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
Steve Block6ded16b2010-05-10 14:33:55 +01003397
Leon Clarkeac952652010-07-15 11:15:24 +01003398 // Copy patched rinfo.
3399 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
Steve Block6ded16b2010-05-10 14:33:55 +01003400
3401 // Relocate the copy.
Steve Block44f0eee2011-05-26 01:26:41 +01003402 ASSERT(!isolate_->code_range()->exists() ||
3403 isolate_->code_range()->contains(code->address()));
Steve Block6ded16b2010-05-10 14:33:55 +01003404 new_code->Relocate(new_addr - old_addr);
3405
3406#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003407 if (FLAG_verify_heap) {
3408 code->Verify();
3409 }
Steve Block6ded16b2010-05-10 14:33:55 +01003410#endif
3411 return new_code;
3412}
3413
3414
John Reck59135872010-11-02 12:39:01 -07003415MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003416 ASSERT(gc_state_ == NOT_IN_GC);
3417 ASSERT(map->instance_type() != MAP_TYPE);
Leon Clarkee46be812010-01-19 14:06:41 +00003418 // If allocation failures are disallowed, we may allocate in a different
3419 // space when new space is full and the object is not a large object.
3420 AllocationSpace retry_space =
3421 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
John Reck59135872010-11-02 12:39:01 -07003422 Object* result;
3423 { MaybeObject* maybe_result =
3424 AllocateRaw(map->instance_size(), space, retry_space);
3425 if (!maybe_result->ToObject(&result)) return maybe_result;
3426 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003427 // No need for write barrier since object is white and map is in old space.
Ben Murdochc7cc0282012-03-05 14:35:55 +00003428 HeapObject::cast(result)->set_map_no_write_barrier(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00003429 return result;
3430}
3431
3432
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003433void Heap::InitializeFunction(JSFunction* function,
3434 SharedFunctionInfo* shared,
3435 Object* prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003436 ASSERT(!prototype->IsMap());
3437 function->initialize_properties();
3438 function->initialize_elements();
3439 function->set_shared(shared);
Iain Merrick75681382010-08-19 15:07:18 +01003440 function->set_code(shared->code());
Steve Blocka7e24c12009-10-30 11:49:00 +00003441 function->set_prototype_or_initial_map(prototype);
3442 function->set_context(undefined_value());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003443 function->set_literals_or_bindings(empty_fixed_array());
Ben Murdochb0fe1622011-05-05 13:52:32 +01003444 function->set_next_function_link(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00003445}
3446
3447
John Reck59135872010-11-02 12:39:01 -07003448MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003449 // Allocate the prototype. Make sure to use the object function
3450 // from the function's context, since the function can be from a
3451 // different context.
3452 JSFunction* object_function =
3453 function->context()->global_context()->object_function();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003454
3455 // Each function prototype gets a copy of the object function map.
3456 // This avoid unwanted sharing of maps between prototypes of different
3457 // constructors.
3458 Map* new_map;
3459 ASSERT(object_function->has_initial_map());
3460 { MaybeObject* maybe_map =
3461 object_function->initial_map()->CopyDropTransitions();
3462 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3463 }
John Reck59135872010-11-02 12:39:01 -07003464 Object* prototype;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003465 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
John Reck59135872010-11-02 12:39:01 -07003466 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3467 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003468 // When creating the prototype for the function we must set its
3469 // constructor to the function.
John Reck59135872010-11-02 12:39:01 -07003470 Object* result;
3471 { MaybeObject* maybe_result =
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003472 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3473 constructor_symbol(), function, DONT_ENUM);
John Reck59135872010-11-02 12:39:01 -07003474 if (!maybe_result->ToObject(&result)) return maybe_result;
3475 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003476 return prototype;
3477}
3478
3479
John Reck59135872010-11-02 12:39:01 -07003480MaybeObject* Heap::AllocateFunction(Map* function_map,
3481 SharedFunctionInfo* shared,
3482 Object* prototype,
3483 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003484 AllocationSpace space =
3485 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003486 Object* result;
3487 { MaybeObject* maybe_result = Allocate(function_map, space);
3488 if (!maybe_result->ToObject(&result)) return maybe_result;
3489 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003490 InitializeFunction(JSFunction::cast(result), shared, prototype);
3491 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003492}
3493
3494
John Reck59135872010-11-02 12:39:01 -07003495MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003496 // To get fast allocation and map sharing for arguments objects we
3497 // allocate them based on an arguments boilerplate.
3498
Steve Block44f0eee2011-05-26 01:26:41 +01003499 JSObject* boilerplate;
3500 int arguments_object_size;
3501 bool strict_mode_callee = callee->IsJSFunction() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003502 !JSFunction::cast(callee)->shared()->is_classic_mode();
Steve Block44f0eee2011-05-26 01:26:41 +01003503 if (strict_mode_callee) {
3504 boilerplate =
3505 isolate()->context()->global_context()->
3506 strict_mode_arguments_boilerplate();
3507 arguments_object_size = kArgumentsObjectSizeStrict;
3508 } else {
3509 boilerplate =
3510 isolate()->context()->global_context()->arguments_boilerplate();
3511 arguments_object_size = kArgumentsObjectSize;
3512 }
3513
Steve Blocka7e24c12009-10-30 11:49:00 +00003514 // This calls Copy directly rather than using Heap::AllocateRaw so we
3515 // duplicate the check here.
3516 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3517
Leon Clarkee46be812010-01-19 14:06:41 +00003518 // Check that the size of the boilerplate matches our
3519 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3520 // on the size being a known constant.
Steve Block44f0eee2011-05-26 01:26:41 +01003521 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
Leon Clarkee46be812010-01-19 14:06:41 +00003522
3523 // Do the allocation.
John Reck59135872010-11-02 12:39:01 -07003524 Object* result;
3525 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01003526 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07003527 if (!maybe_result->ToObject(&result)) return maybe_result;
3528 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003529
3530 // Copy the content. The arguments boilerplate doesn't have any
3531 // fields that point to new space so it's safe to skip the write
3532 // barrier here.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003533 CopyBlock(HeapObject::cast(result)->address(),
3534 boilerplate->address(),
Steve Block44f0eee2011-05-26 01:26:41 +01003535 JSObject::kHeaderSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003536
Steve Block44f0eee2011-05-26 01:26:41 +01003537 // Set the length property.
3538 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
Steve Blocka7e24c12009-10-30 11:49:00 +00003539 Smi::FromInt(length),
3540 SKIP_WRITE_BARRIER);
Steve Block44f0eee2011-05-26 01:26:41 +01003541 // Set the callee property for non-strict mode arguments object only.
3542 if (!strict_mode_callee) {
3543 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3544 callee);
3545 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003546
3547 // Check the state of the object
3548 ASSERT(JSObject::cast(result)->HasFastProperties());
3549 ASSERT(JSObject::cast(result)->HasFastElements());
3550
3551 return result;
3552}
3553
3554
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003555static bool HasDuplicates(DescriptorArray* descriptors) {
3556 int count = descriptors->number_of_descriptors();
3557 if (count > 1) {
3558 String* prev_key = descriptors->GetKey(0);
3559 for (int i = 1; i != count; i++) {
3560 String* current_key = descriptors->GetKey(i);
3561 if (prev_key == current_key) return true;
3562 prev_key = current_key;
3563 }
3564 }
3565 return false;
3566}
3567
3568
John Reck59135872010-11-02 12:39:01 -07003569MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003570 ASSERT(!fun->has_initial_map());
3571
3572 // First create a new map with the size and number of in-object properties
3573 // suggested by the function.
3574 int instance_size = fun->shared()->CalculateInstanceSize();
3575 int in_object_properties = fun->shared()->CalculateInObjectProperties();
John Reck59135872010-11-02 12:39:01 -07003576 Object* map_obj;
Steve Block44f0eee2011-05-26 01:26:41 +01003577 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
John Reck59135872010-11-02 12:39:01 -07003578 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3579 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003580
3581 // Fetch or allocate prototype.
3582 Object* prototype;
3583 if (fun->has_instance_prototype()) {
3584 prototype = fun->instance_prototype();
3585 } else {
John Reck59135872010-11-02 12:39:01 -07003586 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3587 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3588 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003589 }
3590 Map* map = Map::cast(map_obj);
3591 map->set_inobject_properties(in_object_properties);
3592 map->set_unused_property_fields(in_object_properties);
3593 map->set_prototype(prototype);
Steve Block8defd9f2010-07-08 12:39:36 +01003594 ASSERT(map->has_fast_elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003595
Andrei Popescu402d9372010-02-26 13:31:12 +00003596 // If the function has only simple this property assignments add
3597 // field descriptors for these to the initial map as the object
3598 // cannot be constructed without having these properties. Guard by
3599 // the inline_new flag so we only change the map if we generate a
3600 // specialized construct stub.
Steve Blocka7e24c12009-10-30 11:49:00 +00003601 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Andrei Popescu402d9372010-02-26 13:31:12 +00003602 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003603 int count = fun->shared()->this_property_assignments_count();
3604 if (count > in_object_properties) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003605 // Inline constructor can only handle inobject properties.
3606 fun->shared()->ForbidInlineConstructor();
3607 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003608 DescriptorArray* descriptors;
John Reck59135872010-11-02 12:39:01 -07003609 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003610 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
John Reck59135872010-11-02 12:39:01 -07003611 return maybe_descriptors_obj;
3612 }
3613 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003614 DescriptorArray::WhitenessWitness witness(descriptors);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003615 for (int i = 0; i < count; i++) {
3616 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3617 ASSERT(name->IsSymbol());
3618 FieldDescriptor field(name, i, NONE);
3619 field.SetEnumerationIndex(i);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003620 descriptors->Set(i, &field, witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003621 }
3622 descriptors->SetNextEnumerationIndex(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003623 descriptors->SortUnchecked(witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003624
3625 // The descriptors may contain duplicates because the compiler does not
3626 // guarantee the uniqueness of property names (it would have required
3627 // quadratic time). Once the descriptors are sorted we can check for
3628 // duplicates in linear time.
3629 if (HasDuplicates(descriptors)) {
3630 fun->shared()->ForbidInlineConstructor();
3631 } else {
3632 map->set_instance_descriptors(descriptors);
3633 map->set_pre_allocated_property_fields(count);
3634 map->set_unused_property_fields(in_object_properties - count);
3635 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003636 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003637 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003638
3639 fun->shared()->StartInobjectSlackTracking(map);
3640
Steve Blocka7e24c12009-10-30 11:49:00 +00003641 return map;
3642}
3643
3644
3645void Heap::InitializeJSObjectFromMap(JSObject* obj,
3646 FixedArray* properties,
3647 Map* map) {
3648 obj->set_properties(properties);
3649 obj->initialize_elements();
3650 // TODO(1240798): Initialize the object's body using valid initial values
3651 // according to the object's initial map. For example, if the map's
3652 // instance type is JS_ARRAY_TYPE, the length field should be initialized
Ben Murdochc7cc0282012-03-05 14:35:55 +00003653 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3654 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
Steve Blocka7e24c12009-10-30 11:49:00 +00003655 // verification code has to cope with (temporarily) invalid objects. See
3656 // for example, JSArray::JSArrayVerify).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003657 Object* filler;
3658 // We cannot always fill with one_pointer_filler_map because objects
3659 // created from API functions expect their internal fields to be initialized
3660 // with undefined_value.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003661 // Pre-allocated fields need to be initialized with undefined_value as well
3662 // so that object accesses before the constructor completes (e.g. in the
3663 // debugger) will not cause a crash.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003664 if (map->constructor()->IsJSFunction() &&
3665 JSFunction::cast(map->constructor())->shared()->
3666 IsInobjectSlackTrackingInProgress()) {
3667 // We might want to shrink the object later.
3668 ASSERT(obj->GetInternalFieldCount() == 0);
3669 filler = Heap::one_pointer_filler_map();
3670 } else {
3671 filler = Heap::undefined_value();
3672 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003673 obj->InitializeBody(map, Heap::undefined_value(), filler);
Steve Blocka7e24c12009-10-30 11:49:00 +00003674}
3675
3676
John Reck59135872010-11-02 12:39:01 -07003677MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003678 // JSFunctions should be allocated using AllocateFunction to be
3679 // properly initialized.
3680 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3681
Steve Block8defd9f2010-07-08 12:39:36 +01003682 // Both types of global objects should be allocated using
3683 // AllocateGlobalObject to be properly initialized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003684 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3685 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3686
3687 // Allocate the backing storage for the properties.
3688 int prop_size =
3689 map->pre_allocated_property_fields() +
3690 map->unused_property_fields() -
3691 map->inobject_properties();
3692 ASSERT(prop_size >= 0);
John Reck59135872010-11-02 12:39:01 -07003693 Object* properties;
3694 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3695 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3696 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003697
3698 // Allocate the JSObject.
3699 AllocationSpace space =
3700 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003701 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
John Reck59135872010-11-02 12:39:01 -07003702 Object* obj;
3703 { MaybeObject* maybe_obj = Allocate(map, space);
3704 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3705 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003706
3707 // Initialize the JSObject.
3708 InitializeJSObjectFromMap(JSObject::cast(obj),
3709 FixedArray::cast(properties),
3710 map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003711 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3712 JSObject::cast(obj)->HasFastElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003713 return obj;
3714}
3715
3716
John Reck59135872010-11-02 12:39:01 -07003717MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3718 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003719 // Allocate the initial map if absent.
3720 if (!constructor->has_initial_map()) {
John Reck59135872010-11-02 12:39:01 -07003721 Object* initial_map;
3722 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3723 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3724 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003725 constructor->set_initial_map(Map::cast(initial_map));
3726 Map::cast(initial_map)->set_constructor(constructor);
3727 }
3728 // Allocate the object based on the constructors initial map.
John Reck59135872010-11-02 12:39:01 -07003729 MaybeObject* result =
Steve Blocka7e24c12009-10-30 11:49:00 +00003730 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
John Reck59135872010-11-02 12:39:01 -07003731#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00003732 // Make sure result is NOT a global object if valid.
John Reck59135872010-11-02 12:39:01 -07003733 Object* non_failure;
3734 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3735#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003736 return result;
3737}
3738
3739
Ben Murdoch257744e2011-11-30 15:57:28 +00003740MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3741 // Allocate map.
3742 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3743 // maps. Will probably depend on the identity of the handler object, too.
3744 Map* map;
3745 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3746 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3747 map->set_prototype(prototype);
Ben Murdoch257744e2011-11-30 15:57:28 +00003748
3749 // Allocate the proxy object.
Ben Murdoch589d6972011-11-30 16:04:58 +00003750 JSProxy* result;
Ben Murdoch257744e2011-11-30 15:57:28 +00003751 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
Ben Murdoch589d6972011-11-30 16:04:58 +00003752 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3753 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3754 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003755 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003756 return result;
3757}
3758
3759
3760MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3761 Object* call_trap,
3762 Object* construct_trap,
3763 Object* prototype) {
3764 // Allocate map.
3765 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3766 // maps. Will probably depend on the identity of the handler object, too.
3767 Map* map;
3768 MaybeObject* maybe_map_obj =
3769 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3770 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3771 map->set_prototype(prototype);
3772
3773 // Allocate the proxy object.
3774 JSFunctionProxy* result;
3775 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3776 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3777 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3778 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003779 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003780 result->set_call_trap(call_trap);
3781 result->set_construct_trap(construct_trap);
Ben Murdoch257744e2011-11-30 15:57:28 +00003782 return result;
3783}
3784
3785
John Reck59135872010-11-02 12:39:01 -07003786MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003787 ASSERT(constructor->has_initial_map());
3788 Map* map = constructor->initial_map();
3789
3790 // Make sure no field properties are described in the initial map.
3791 // This guarantees us that normalizing the properties does not
3792 // require us to change property values to JSGlobalPropertyCells.
3793 ASSERT(map->NextFreePropertyIndex() == 0);
3794
3795 // Make sure we don't have a ton of pre-allocated slots in the
3796 // global objects. They will be unused once we normalize the object.
3797 ASSERT(map->unused_property_fields() == 0);
3798 ASSERT(map->inobject_properties() == 0);
3799
3800 // Initial size of the backing store to avoid resize of the storage during
3801 // bootstrapping. The size differs between the JS global object ad the
3802 // builtins object.
3803 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3804
3805 // Allocate a dictionary object for backing storage.
John Reck59135872010-11-02 12:39:01 -07003806 Object* obj;
3807 { MaybeObject* maybe_obj =
3808 StringDictionary::Allocate(
3809 map->NumberOfDescribedProperties() * 2 + initial_size);
3810 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3811 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003812 StringDictionary* dictionary = StringDictionary::cast(obj);
3813
3814 // The global object might be created from an object template with accessors.
3815 // Fill these accessors into the dictionary.
3816 DescriptorArray* descs = map->instance_descriptors();
3817 for (int i = 0; i < descs->number_of_descriptors(); i++) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01003818 PropertyDetails details(descs->GetDetails(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00003819 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3820 PropertyDetails d =
3821 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3822 Object* value = descs->GetCallbacksObject(i);
Steve Block44f0eee2011-05-26 01:26:41 +01003823 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
John Reck59135872010-11-02 12:39:01 -07003824 if (!maybe_value->ToObject(&value)) return maybe_value;
3825 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003826
John Reck59135872010-11-02 12:39:01 -07003827 Object* result;
3828 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3829 if (!maybe_result->ToObject(&result)) return maybe_result;
3830 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003831 dictionary = StringDictionary::cast(result);
3832 }
3833
3834 // Allocate the global object and initialize it with the backing store.
John Reck59135872010-11-02 12:39:01 -07003835 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3836 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3837 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003838 JSObject* global = JSObject::cast(obj);
3839 InitializeJSObjectFromMap(global, dictionary, map);
3840
3841 // Create a new map for the global object.
John Reck59135872010-11-02 12:39:01 -07003842 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3843 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3844 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003845 Map* new_map = Map::cast(obj);
3846
Ben Murdochc7cc0282012-03-05 14:35:55 +00003847 // Set up the global object as a normalized object.
Steve Blocka7e24c12009-10-30 11:49:00 +00003848 global->set_map(new_map);
Ben Murdoch257744e2011-11-30 15:57:28 +00003849 global->map()->clear_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00003850 global->set_properties(dictionary);
3851
3852 // Make sure result is a global object with properties in dictionary.
3853 ASSERT(global->IsGlobalObject());
3854 ASSERT(!global->HasFastProperties());
3855 return global;
3856}
3857
3858
John Reck59135872010-11-02 12:39:01 -07003859MaybeObject* Heap::CopyJSObject(JSObject* source) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003860 // Never used to copy functions. If functions need to be copied we
3861 // have to be careful to clear the literals array.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003862 SLOW_ASSERT(!source->IsJSFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00003863
3864 // Make the clone.
3865 Map* map = source->map();
3866 int object_size = map->instance_size();
3867 Object* clone;
3868
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003869 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
3870
Steve Blocka7e24c12009-10-30 11:49:00 +00003871 // If we're forced to always allocate, we use the general allocation
3872 // functions which may leave us with an object in old space.
3873 if (always_allocate()) {
John Reck59135872010-11-02 12:39:01 -07003874 { MaybeObject* maybe_clone =
3875 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
3876 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3877 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003878 Address clone_address = HeapObject::cast(clone)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003879 CopyBlock(clone_address,
3880 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003881 object_size);
3882 // Update write barrier for all fields that lie beyond the header.
Steve Block6ded16b2010-05-10 14:33:55 +01003883 RecordWrites(clone_address,
3884 JSObject::kHeaderSize,
3885 (object_size - JSObject::kHeaderSize) / kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003886 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003887 wb_mode = SKIP_WRITE_BARRIER;
John Reck59135872010-11-02 12:39:01 -07003888 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
3889 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3890 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003891 SLOW_ASSERT(InNewSpace(clone));
Steve Blocka7e24c12009-10-30 11:49:00 +00003892 // Since we know the clone is allocated in new space, we can copy
3893 // the contents without worrying about updating the write barrier.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003894 CopyBlock(HeapObject::cast(clone)->address(),
3895 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003896 object_size);
3897 }
3898
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003899 SLOW_ASSERT(
3900 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003901 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003902 FixedArray* properties = FixedArray::cast(source->properties());
3903 // Update elements if necessary.
Steve Block6ded16b2010-05-10 14:33:55 +01003904 if (elements->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003905 Object* elem;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003906 { MaybeObject* maybe_elem;
3907 if (elements->map() == fixed_cow_array_map()) {
3908 maybe_elem = FixedArray::cast(elements);
3909 } else if (source->HasFastDoubleElements()) {
3910 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
3911 } else {
3912 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
3913 }
John Reck59135872010-11-02 12:39:01 -07003914 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
3915 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003916 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003917 }
3918 // Update properties if necessary.
3919 if (properties->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003920 Object* prop;
3921 { MaybeObject* maybe_prop = CopyFixedArray(properties);
3922 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
3923 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003924 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003925 }
3926 // Return the new clone.
3927 return clone;
3928}
3929
3930
Ben Murdoch589d6972011-11-30 16:04:58 +00003931MaybeObject* Heap::ReinitializeJSReceiver(
3932 JSReceiver* object, InstanceType type, int size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003933 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
Ben Murdoch589d6972011-11-30 16:04:58 +00003934
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003935 // Allocate fresh map.
3936 // TODO(rossberg): Once we optimize proxies, cache these maps.
3937 Map* map;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003938 MaybeObject* maybe = AllocateMap(type, size);
3939 if (!maybe->To<Map>(&map)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003940
Ben Murdoch589d6972011-11-30 16:04:58 +00003941 // Check that the receiver has at least the size of the fresh object.
3942 int size_difference = object->map()->instance_size() - map->instance_size();
3943 ASSERT(size_difference >= 0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003944
3945 map->set_prototype(object->map()->prototype());
3946
3947 // Allocate the backing storage for the properties.
3948 int prop_size = map->unused_property_fields() - map->inobject_properties();
3949 Object* properties;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003950 maybe = AllocateFixedArray(prop_size, TENURED);
3951 if (!maybe->ToObject(&properties)) return maybe;
3952
3953 // Functions require some allocation, which might fail here.
3954 SharedFunctionInfo* shared = NULL;
3955 if (type == JS_FUNCTION_TYPE) {
3956 String* name;
3957 maybe = LookupAsciiSymbol("<freezing call trap>");
3958 if (!maybe->To<String>(&name)) return maybe;
3959 maybe = AllocateSharedFunctionInfo(name);
3960 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003961 }
3962
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003963 // Because of possible retries of this function after failure,
3964 // we must NOT fail after this point, where we have changed the type!
3965
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003966 // Reset the map for the object.
3967 object->set_map(map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003968 JSObject* jsobj = JSObject::cast(object);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003969
3970 // Reinitialize the object from the constructor map.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003971 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
Ben Murdoch589d6972011-11-30 16:04:58 +00003972
3973 // Functions require some minimal initialization.
3974 if (type == JS_FUNCTION_TYPE) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003975 map->set_function_with_prototype(true);
3976 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
3977 JSFunction::cast(object)->set_context(
3978 isolate()->context()->global_context());
Ben Murdoch589d6972011-11-30 16:04:58 +00003979 }
3980
3981 // Put in filler if the new object is smaller than the old.
3982 if (size_difference > 0) {
3983 CreateFillerObjectAt(
3984 object->address() + map->instance_size(), size_difference);
3985 }
3986
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003987 return object;
3988}
3989
3990
John Reck59135872010-11-02 12:39:01 -07003991MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
3992 JSGlobalProxy* object) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003993 ASSERT(constructor->has_initial_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003994 Map* map = constructor->initial_map();
3995
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003996 // Check that the already allocated object has the same size and type as
Steve Blocka7e24c12009-10-30 11:49:00 +00003997 // objects allocated using the constructor.
3998 ASSERT(map->instance_size() == object->map()->instance_size());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003999 ASSERT(map->instance_type() == object->map()->instance_type());
Steve Blocka7e24c12009-10-30 11:49:00 +00004000
4001 // Allocate the backing storage for the properties.
4002 int prop_size = map->unused_property_fields() - map->inobject_properties();
John Reck59135872010-11-02 12:39:01 -07004003 Object* properties;
4004 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4005 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4006 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004007
4008 // Reset the map for the object.
4009 object->set_map(constructor->initial_map());
4010
4011 // Reinitialize the object from the constructor map.
4012 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4013 return object;
4014}
4015
4016
John Reck59135872010-11-02 12:39:01 -07004017MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4018 PretenureFlag pretenure) {
Ben Murdoch589d6972011-11-30 16:04:58 +00004019 if (string.length() == 1) {
4020 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4021 }
John Reck59135872010-11-02 12:39:01 -07004022 Object* result;
4023 { MaybeObject* maybe_result =
4024 AllocateRawAsciiString(string.length(), pretenure);
4025 if (!maybe_result->ToObject(&result)) return maybe_result;
4026 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004027
4028 // Copy the characters into the new object.
4029 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4030 for (int i = 0; i < string.length(); i++) {
4031 string_result->SeqAsciiStringSet(i, string[i]);
4032 }
4033 return result;
4034}
4035
4036
Steve Block9fac8402011-05-12 15:51:54 +01004037MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4038 PretenureFlag pretenure) {
Leon Clarkeac952652010-07-15 11:15:24 +01004039 // V8 only supports characters in the Basic Multilingual Plane.
4040 const uc32 kMaxSupportedChar = 0xFFFF;
Steve Blocka7e24c12009-10-30 11:49:00 +00004041 // Count the number of characters in the UTF-8 string and check if
4042 // it is an ASCII string.
Ben Murdoch8b112d22011-06-08 16:22:53 +01004043 Access<UnicodeCache::Utf8Decoder>
4044 decoder(isolate_->unicode_cache()->utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00004045 decoder->Reset(string.start(), string.length());
4046 int chars = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00004047 while (decoder->has_more()) {
Steve Block9fac8402011-05-12 15:51:54 +01004048 decoder->GetNext();
Steve Blocka7e24c12009-10-30 11:49:00 +00004049 chars++;
4050 }
4051
John Reck59135872010-11-02 12:39:01 -07004052 Object* result;
4053 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4054 if (!maybe_result->ToObject(&result)) return maybe_result;
4055 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004056
4057 // Convert and copy the characters into the new object.
4058 String* string_result = String::cast(result);
4059 decoder->Reset(string.start(), string.length());
4060 for (int i = 0; i < chars; i++) {
4061 uc32 r = decoder->GetNext();
Leon Clarkeac952652010-07-15 11:15:24 +01004062 if (r > kMaxSupportedChar) { r = unibrow::Utf8::kBadChar; }
Steve Blocka7e24c12009-10-30 11:49:00 +00004063 string_result->Set(i, r);
4064 }
4065 return result;
4066}
4067
4068
John Reck59135872010-11-02 12:39:01 -07004069MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4070 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004071 // Check if the string is an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004072 MaybeObject* maybe_result;
Steve Block9fac8402011-05-12 15:51:54 +01004073 if (String::IsAscii(string.start(), string.length())) {
John Reck59135872010-11-02 12:39:01 -07004074 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004075 } else { // It's not an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004076 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004077 }
John Reck59135872010-11-02 12:39:01 -07004078 Object* result;
4079 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004080
4081 // Copy the characters into the new object, which may be either ASCII or
4082 // UTF-16.
4083 String* string_result = String::cast(result);
4084 for (int i = 0; i < string.length(); i++) {
4085 string_result->Set(i, string[i]);
4086 }
4087 return result;
4088}
4089
4090
4091Map* Heap::SymbolMapForString(String* string) {
4092 // If the string is in new space it cannot be used as a symbol.
4093 if (InNewSpace(string)) return NULL;
4094
4095 // Find the corresponding symbol map for strings.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004096 switch (string->map()->instance_type()) {
4097 case STRING_TYPE: return symbol_map();
4098 case ASCII_STRING_TYPE: return ascii_symbol_map();
4099 case CONS_STRING_TYPE: return cons_symbol_map();
4100 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4101 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4102 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4103 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4104 return external_symbol_with_ascii_data_map();
4105 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4106 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4107 return short_external_ascii_symbol_map();
4108 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4109 return short_external_symbol_with_ascii_data_map();
4110 default: return NULL; // No match found.
Steve Block44f0eee2011-05-26 01:26:41 +01004111 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004112}
4113
4114
John Reck59135872010-11-02 12:39:01 -07004115MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4116 int chars,
4117 uint32_t hash_field) {
Leon Clarkee46be812010-01-19 14:06:41 +00004118 ASSERT(chars >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004119 // Ensure the chars matches the number of characters in the buffer.
4120 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
Ben Murdochc7cc0282012-03-05 14:35:55 +00004121 // Determine whether the string is ASCII.
Steve Blocka7e24c12009-10-30 11:49:00 +00004122 bool is_ascii = true;
Leon Clarkee46be812010-01-19 14:06:41 +00004123 while (buffer->has_more()) {
4124 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4125 is_ascii = false;
4126 break;
4127 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004128 }
4129 buffer->Rewind();
4130
4131 // Compute map and object size.
4132 int size;
4133 Map* map;
4134
4135 if (is_ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +00004136 if (chars > SeqAsciiString::kMaxLength) {
4137 return Failure::OutOfMemoryException();
4138 }
Steve Blockd0582a62009-12-15 09:54:21 +00004139 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004140 size = SeqAsciiString::SizeFor(chars);
4141 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00004142 if (chars > SeqTwoByteString::kMaxLength) {
4143 return Failure::OutOfMemoryException();
4144 }
Steve Blockd0582a62009-12-15 09:54:21 +00004145 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004146 size = SeqTwoByteString::SizeFor(chars);
4147 }
4148
4149 // Allocate string.
John Reck59135872010-11-02 12:39:01 -07004150 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004151 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4152 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
John Reck59135872010-11-02 12:39:01 -07004153 : old_data_space_->AllocateRaw(size);
4154 if (!maybe_result->ToObject(&result)) return maybe_result;
4155 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004156
Ben Murdochc7cc0282012-03-05 14:35:55 +00004157 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
Steve Blockd0582a62009-12-15 09:54:21 +00004158 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00004159 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00004160 answer->set_length(chars);
4161 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004162
4163 ASSERT_EQ(size, answer->Size());
4164
4165 // Fill in the characters.
4166 for (int i = 0; i < chars; i++) {
4167 answer->Set(i, buffer->GetNext());
4168 }
4169 return answer;
4170}
4171
4172
John Reck59135872010-11-02 12:39:01 -07004173MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004174 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4175 return Failure::OutOfMemoryException();
4176 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004177
4178 int size = SeqAsciiString::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004179 ASSERT(size <= SeqAsciiString::kMaxSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004180
Leon Clarkee46be812010-01-19 14:06:41 +00004181 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4182 AllocationSpace retry_space = OLD_DATA_SPACE;
4183
Steve Blocka7e24c12009-10-30 11:49:00 +00004184 if (space == NEW_SPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00004185 if (size > kMaxObjectSizeInNewSpace) {
4186 // Allocate in large object space, retry space will be ignored.
4187 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004188 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004189 // Allocate in new space, retry in large object space.
4190 retry_space = LO_SPACE;
4191 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004192 } else if (space == OLD_DATA_SPACE &&
4193 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004194 space = LO_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004195 }
John Reck59135872010-11-02 12:39:01 -07004196 Object* result;
4197 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4198 if (!maybe_result->ToObject(&result)) return maybe_result;
4199 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004200
Steve Blocka7e24c12009-10-30 11:49:00 +00004201 // Partially initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004202 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004203 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004204 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004205 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4206 return result;
4207}
4208
4209
John Reck59135872010-11-02 12:39:01 -07004210MaybeObject* Heap::AllocateRawTwoByteString(int length,
4211 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004212 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4213 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00004214 }
Leon Clarkee46be812010-01-19 14:06:41 +00004215 int size = SeqTwoByteString::SizeFor(length);
4216 ASSERT(size <= SeqTwoByteString::kMaxSize);
4217 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4218 AllocationSpace retry_space = OLD_DATA_SPACE;
4219
4220 if (space == NEW_SPACE) {
4221 if (size > kMaxObjectSizeInNewSpace) {
4222 // Allocate in large object space, retry space will be ignored.
4223 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004224 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004225 // Allocate in new space, retry in large object space.
4226 retry_space = LO_SPACE;
4227 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004228 } else if (space == OLD_DATA_SPACE &&
4229 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004230 space = LO_SPACE;
4231 }
John Reck59135872010-11-02 12:39:01 -07004232 Object* result;
4233 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4234 if (!maybe_result->ToObject(&result)) return maybe_result;
4235 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004236
Steve Blocka7e24c12009-10-30 11:49:00 +00004237 // Partially initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004238 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004239 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004240 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004241 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4242 return result;
4243}
4244
4245
John Reck59135872010-11-02 12:39:01 -07004246MaybeObject* Heap::AllocateEmptyFixedArray() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004247 int size = FixedArray::SizeFor(0);
John Reck59135872010-11-02 12:39:01 -07004248 Object* result;
4249 { MaybeObject* maybe_result =
4250 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4251 if (!maybe_result->ToObject(&result)) return maybe_result;
4252 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004253 // Initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004254 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4255 fixed_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004256 reinterpret_cast<FixedArray*>(result)->set_length(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004257 return result;
4258}
4259
4260
John Reck59135872010-11-02 12:39:01 -07004261MaybeObject* Heap::AllocateRawFixedArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00004262 if (length < 0 || length > FixedArray::kMaxLength) {
4263 return Failure::OutOfMemoryException();
4264 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004265 ASSERT(length > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004266 // Use the general function if we're forced to always allocate.
4267 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4268 // Allocate the raw data for a fixed array.
4269 int size = FixedArray::SizeFor(length);
4270 return size <= kMaxObjectSizeInNewSpace
4271 ? new_space_.AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004272 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004273}
4274
4275
John Reck59135872010-11-02 12:39:01 -07004276MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004277 int len = src->length();
John Reck59135872010-11-02 12:39:01 -07004278 Object* obj;
4279 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4280 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4281 }
Steve Block44f0eee2011-05-26 01:26:41 +01004282 if (InNewSpace(obj)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004283 HeapObject* dst = HeapObject::cast(obj);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004284 dst->set_map_no_write_barrier(map);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004285 CopyBlock(dst->address() + kPointerSize,
4286 src->address() + kPointerSize,
4287 FixedArray::SizeFor(len) - kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004288 return obj;
4289 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00004290 HeapObject::cast(obj)->set_map_no_write_barrier(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00004291 FixedArray* result = FixedArray::cast(obj);
4292 result->set_length(len);
Leon Clarke4515c472010-02-03 11:58:03 +00004293
Steve Blocka7e24c12009-10-30 11:49:00 +00004294 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00004295 AssertNoAllocation no_gc;
4296 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00004297 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4298 return result;
4299}
4300
4301
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004302MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4303 Map* map) {
4304 int len = src->length();
4305 Object* obj;
4306 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4307 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4308 }
4309 HeapObject* dst = HeapObject::cast(obj);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004310 dst->set_map_no_write_barrier(map);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004311 CopyBlock(
4312 dst->address() + FixedDoubleArray::kLengthOffset,
4313 src->address() + FixedDoubleArray::kLengthOffset,
4314 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4315 return obj;
4316}
4317
4318
John Reck59135872010-11-02 12:39:01 -07004319MaybeObject* Heap::AllocateFixedArray(int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004320 ASSERT(length >= 0);
4321 if (length == 0) return empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07004322 Object* result;
4323 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4324 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004325 }
John Reck59135872010-11-02 12:39:01 -07004326 // Initialize header.
4327 FixedArray* array = reinterpret_cast<FixedArray*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004328 array->set_map_no_write_barrier(fixed_array_map());
John Reck59135872010-11-02 12:39:01 -07004329 array->set_length(length);
4330 // Initialize body.
Steve Block44f0eee2011-05-26 01:26:41 +01004331 ASSERT(!InNewSpace(undefined_value()));
John Reck59135872010-11-02 12:39:01 -07004332 MemsetPointer(array->data_start(), undefined_value(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00004333 return result;
4334}
4335
4336
John Reck59135872010-11-02 12:39:01 -07004337MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004338 if (length < 0 || length > FixedArray::kMaxLength) {
4339 return Failure::OutOfMemoryException();
4340 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004341
Leon Clarkee46be812010-01-19 14:06:41 +00004342 AllocationSpace space =
4343 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004344 int size = FixedArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004345 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4346 // Too big for new space.
4347 space = LO_SPACE;
4348 } else if (space == OLD_POINTER_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004349 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004350 // Too big for old pointer space.
4351 space = LO_SPACE;
4352 }
4353
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004354 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004355 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004356
4357 return AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00004358}
4359
4360
John Reck59135872010-11-02 12:39:01 -07004361MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
Steve Block44f0eee2011-05-26 01:26:41 +01004362 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07004363 int length,
4364 PretenureFlag pretenure,
4365 Object* filler) {
Steve Block6ded16b2010-05-10 14:33:55 +01004366 ASSERT(length >= 0);
Steve Block44f0eee2011-05-26 01:26:41 +01004367 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4368 if (length == 0) return heap->empty_fixed_array();
Steve Block6ded16b2010-05-10 14:33:55 +01004369
Steve Block44f0eee2011-05-26 01:26:41 +01004370 ASSERT(!heap->InNewSpace(filler));
John Reck59135872010-11-02 12:39:01 -07004371 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004372 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004373 if (!maybe_result->ToObject(&result)) return maybe_result;
4374 }
Steve Block6ded16b2010-05-10 14:33:55 +01004375
Ben Murdochc7cc0282012-03-05 14:35:55 +00004376 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004377 FixedArray* array = FixedArray::cast(result);
4378 array->set_length(length);
4379 MemsetPointer(array->data_start(), filler, length);
4380 return array;
4381}
4382
4383
John Reck59135872010-11-02 12:39:01 -07004384MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004385 return AllocateFixedArrayWithFiller(this,
4386 length,
4387 pretenure,
4388 undefined_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004389}
4390
4391
John Reck59135872010-11-02 12:39:01 -07004392MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4393 PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004394 return AllocateFixedArrayWithFiller(this,
4395 length,
4396 pretenure,
4397 the_hole_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004398}
4399
4400
John Reck59135872010-11-02 12:39:01 -07004401MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
Steve Block6ded16b2010-05-10 14:33:55 +01004402 if (length == 0) return empty_fixed_array();
4403
John Reck59135872010-11-02 12:39:01 -07004404 Object* obj;
4405 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4406 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4407 }
Steve Block6ded16b2010-05-10 14:33:55 +01004408
Ben Murdochc7cc0282012-03-05 14:35:55 +00004409 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4410 fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004411 FixedArray::cast(obj)->set_length(length);
4412 return obj;
4413}
4414
4415
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004416MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4417 int size = FixedDoubleArray::SizeFor(0);
4418 Object* result;
4419 { MaybeObject* maybe_result =
4420 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4421 if (!maybe_result->ToObject(&result)) return maybe_result;
4422 }
4423 // Initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004424 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004425 fixed_double_array_map());
4426 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4427 return result;
4428}
4429
4430
4431MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4432 int length,
4433 PretenureFlag pretenure) {
4434 if (length == 0) return empty_fixed_double_array();
4435
4436 Object* obj;
4437 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4438 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4439 }
4440
Ben Murdochc7cc0282012-03-05 14:35:55 +00004441 reinterpret_cast<FixedDoubleArray*>(obj)->set_map_no_write_barrier(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004442 fixed_double_array_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004443 FixedDoubleArray::cast(obj)->set_length(length);
4444 return obj;
4445}
4446
4447
4448MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4449 PretenureFlag pretenure) {
4450 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4451 return Failure::OutOfMemoryException();
4452 }
4453
4454 AllocationSpace space =
4455 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4456 int size = FixedDoubleArray::SizeFor(length);
4457 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4458 // Too big for new space.
4459 space = LO_SPACE;
4460 } else if (space == OLD_DATA_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004461 size > Page::kMaxNonCodeHeapObjectSize) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004462 // Too big for old data space.
4463 space = LO_SPACE;
4464 }
4465
4466 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004467 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004468
4469 return AllocateRaw(size, space, retry_space);
4470}
4471
4472
John Reck59135872010-11-02 12:39:01 -07004473MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4474 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004475 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004476 if (!maybe_result->ToObject(&result)) return maybe_result;
4477 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00004478 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4479 hash_table_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004480 ASSERT(result->IsHashTable());
4481 return result;
4482}
4483
4484
John Reck59135872010-11-02 12:39:01 -07004485MaybeObject* Heap::AllocateGlobalContext() {
4486 Object* result;
4487 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01004488 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004489 if (!maybe_result->ToObject(&result)) return maybe_result;
4490 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004491 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004492 context->set_map_no_write_barrier(global_context_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004493 ASSERT(context->IsGlobalContext());
4494 ASSERT(result->IsContext());
4495 return result;
4496}
4497
4498
John Reck59135872010-11-02 12:39:01 -07004499MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004500 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004501 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004502 { MaybeObject* maybe_result = AllocateFixedArray(length);
John Reck59135872010-11-02 12:39:01 -07004503 if (!maybe_result->ToObject(&result)) return maybe_result;
4504 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004505 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004506 context->set_map_no_write_barrier(function_context_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004507 context->set_closure(function);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004508 context->set_previous(function->context());
Steve Blocka7e24c12009-10-30 11:49:00 +00004509 context->set_extension(NULL);
4510 context->set_global(function->context()->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004511 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004512}
4513
4514
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004515MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4516 Context* previous,
4517 String* name,
4518 Object* thrown_object) {
4519 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4520 Object* result;
4521 { MaybeObject* maybe_result =
4522 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4523 if (!maybe_result->ToObject(&result)) return maybe_result;
4524 }
4525 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004526 context->set_map_no_write_barrier(catch_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004527 context->set_closure(function);
4528 context->set_previous(previous);
4529 context->set_extension(name);
4530 context->set_global(previous->global());
4531 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4532 return context;
4533}
4534
4535
4536MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4537 Context* previous,
4538 JSObject* extension) {
John Reck59135872010-11-02 12:39:01 -07004539 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004540 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004541 if (!maybe_result->ToObject(&result)) return maybe_result;
4542 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004543 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004544 context->set_map_no_write_barrier(with_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004545 context->set_closure(function);
Steve Blocka7e24c12009-10-30 11:49:00 +00004546 context->set_previous(previous);
4547 context->set_extension(extension);
4548 context->set_global(previous->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004549 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004550}
4551
4552
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004553MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4554 Context* previous,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004555 ScopeInfo* scope_info) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004556 Object* result;
4557 { MaybeObject* maybe_result =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004558 AllocateFixedArrayWithHoles(scope_info->ContextLength());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004559 if (!maybe_result->ToObject(&result)) return maybe_result;
4560 }
4561 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004562 context->set_map_no_write_barrier(block_context_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004563 context->set_closure(function);
4564 context->set_previous(previous);
4565 context->set_extension(scope_info);
4566 context->set_global(previous->global());
4567 return context;
4568}
4569
4570
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004571MaybeObject* Heap::AllocateScopeInfo(int length) {
4572 FixedArray* scope_info;
4573 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4574 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
Ben Murdochc7cc0282012-03-05 14:35:55 +00004575 scope_info->set_map_no_write_barrier(scope_info_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004576 return scope_info;
4577}
4578
4579
John Reck59135872010-11-02 12:39:01 -07004580MaybeObject* Heap::AllocateStruct(InstanceType type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004581 Map* map;
4582 switch (type) {
Steve Block44f0eee2011-05-26 01:26:41 +01004583#define MAKE_CASE(NAME, Name, name) \
4584 case NAME##_TYPE: map = name##_map(); break;
Steve Blocka7e24c12009-10-30 11:49:00 +00004585STRUCT_LIST(MAKE_CASE)
4586#undef MAKE_CASE
4587 default:
4588 UNREACHABLE();
4589 return Failure::InternalError();
4590 }
4591 int size = map->instance_size();
4592 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004593 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
John Reck59135872010-11-02 12:39:01 -07004594 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004595 { MaybeObject* maybe_result = Allocate(map, space);
John Reck59135872010-11-02 12:39:01 -07004596 if (!maybe_result->ToObject(&result)) return maybe_result;
4597 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004598 Struct::cast(result)->InitializeBody(size);
4599 return result;
4600}
4601
4602
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004603bool Heap::IsHeapIterable() {
4604 return (!old_pointer_space()->was_swept_conservatively() &&
4605 !old_data_space()->was_swept_conservatively());
4606}
4607
4608
4609void Heap::EnsureHeapIsIterable() {
4610 ASSERT(IsAllocationAllowed());
4611 if (!IsHeapIterable()) {
4612 CollectAllGarbage(kMakeHeapIterableMask);
4613 }
4614 ASSERT(IsHeapIterable());
4615}
4616
4617
Ben Murdochc7cc0282012-03-05 14:35:55 +00004618bool Heap::IdleNotification(int hint) {
4619 if (hint >= 1000) return IdleGlobalGC();
4620 if (contexts_disposed_ > 0 || !FLAG_incremental_marking ||
4621 FLAG_expose_gc || Serializer::enabled()) {
4622 return true;
4623 }
4624
4625 // By doing small chunks of GC work in each IdleNotification,
4626 // perform a round of incremental GCs and after that wait until
4627 // the mutator creates enough garbage to justify a new round.
4628 // An incremental GC progresses as follows:
4629 // 1. many incremental marking steps,
4630 // 2. one old space mark-sweep-compact,
4631 // 3. many lazy sweep steps.
4632 // Use mark-sweep-compact events to count incremental GCs in a round.
4633
4634 intptr_t size_factor = Min(Max(hint, 30), 1000) / 10;
4635 // The size factor is in range [3..100].
4636 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
4637
4638 if (incremental_marking()->IsStopped()) {
4639 if (!IsSweepingComplete() &&
4640 !AdvanceSweepers(static_cast<int>(step_size))) {
4641 return false;
4642 }
4643 }
4644
4645 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4646 if (EnoughGarbageSinceLastIdleRound()) {
4647 StartIdleRound();
4648 } else {
4649 return true;
4650 }
4651 }
4652
4653 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
4654 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
4655 ms_count_at_last_idle_notification_ = ms_count_;
4656
4657 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4658 FinishIdleRound();
4659 return true;
4660 }
4661
4662 if (incremental_marking()->IsStopped()) {
4663 if (hint < 1000 && !WorthStartingGCWhenIdle()) {
4664 FinishIdleRound();
4665 return true;
4666 }
4667 incremental_marking()->Start();
4668 }
4669
4670 // This flag prevents incremental marking from requesting GC via stack guard
4671 idle_notification_will_schedule_next_gc_ = true;
4672 incremental_marking()->Step(step_size);
4673 idle_notification_will_schedule_next_gc_ = false;
4674
4675 if (incremental_marking()->IsComplete()) {
4676 bool uncommit = false;
4677 if (gc_count_at_last_idle_gc_ == gc_count_) {
4678 // No GC since the last full GC, the mutator is probably not active.
4679 isolate_->compilation_cache()->Clear();
4680 uncommit = true;
4681 }
4682 CollectAllGarbage(kNoGCFlags);
4683 gc_count_at_last_idle_gc_ = gc_count_;
4684 if (uncommit) {
4685 new_space_.Shrink();
4686 UncommitFromSpace();
4687 }
4688 }
4689 return false;
4690}
4691
4692
4693bool Heap::IdleGlobalGC() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004694 static const int kIdlesBeforeScavenge = 4;
4695 static const int kIdlesBeforeMarkSweep = 7;
4696 static const int kIdlesBeforeMarkCompact = 8;
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004697 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
Ben Murdoche0cee9b2011-05-25 10:26:03 +01004698 static const unsigned int kGCsBetweenCleanup = 4;
Steve Block44f0eee2011-05-26 01:26:41 +01004699
4700 if (!last_idle_notification_gc_count_init_) {
4701 last_idle_notification_gc_count_ = gc_count_;
4702 last_idle_notification_gc_count_init_ = true;
4703 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004704
Steve Block6ded16b2010-05-10 14:33:55 +01004705 bool uncommit = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004706 bool finished = false;
4707
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004708 // Reset the number of idle notifications received when a number of
4709 // GCs have taken place. This allows another round of cleanup based
4710 // on idle notifications if enough work has been carried out to
4711 // provoke a number of garbage collections.
Steve Block44f0eee2011-05-26 01:26:41 +01004712 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4713 number_idle_notifications_ =
4714 Min(number_idle_notifications_ + 1, kMaxIdleCount);
Steve Blocka7e24c12009-10-30 11:49:00 +00004715 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01004716 number_idle_notifications_ = 0;
4717 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004718 }
4719
Steve Block44f0eee2011-05-26 01:26:41 +01004720 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
Steve Block6ded16b2010-05-10 14:33:55 +01004721 if (contexts_disposed_ > 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01004722 HistogramTimerScope scope(isolate_->counters()->gc_context());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004723 CollectAllGarbage(kNoGCFlags);
Steve Block6ded16b2010-05-10 14:33:55 +01004724 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +01004725 CollectGarbage(NEW_SPACE);
Steve Block6ded16b2010-05-10 14:33:55 +01004726 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004727 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004728 last_idle_notification_gc_count_ = gc_count_;
4729 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00004730 // Before doing the mark-sweep collections we clear the
4731 // compilation cache to avoid hanging on to source code and
4732 // generated code for cached functions.
Steve Block44f0eee2011-05-26 01:26:41 +01004733 isolate_->compilation_cache()->Clear();
Steve Blockd0582a62009-12-15 09:54:21 +00004734
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004735 CollectAllGarbage(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +00004736 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004737 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004738
Steve Block44f0eee2011-05-26 01:26:41 +01004739 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004740 CollectAllGarbage(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +00004741 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004742 last_idle_notification_gc_count_ = gc_count_;
4743 number_idle_notifications_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00004744 finished = true;
Steve Block6ded16b2010-05-10 14:33:55 +01004745 } else if (contexts_disposed_ > 0) {
4746 if (FLAG_expose_gc) {
4747 contexts_disposed_ = 0;
4748 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01004749 HistogramTimerScope scope(isolate_->counters()->gc_context());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004750 CollectAllGarbage(kNoGCFlags);
Steve Block44f0eee2011-05-26 01:26:41 +01004751 last_idle_notification_gc_count_ = gc_count_;
Steve Block6ded16b2010-05-10 14:33:55 +01004752 }
4753 // If this is the first idle notification, we reset the
4754 // notification count to avoid letting idle notifications for
4755 // context disposal garbage collections start a potentially too
4756 // aggressive idle GC cycle.
Steve Block44f0eee2011-05-26 01:26:41 +01004757 if (number_idle_notifications_ <= 1) {
4758 number_idle_notifications_ = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01004759 uncommit = false;
4760 }
Steve Block44f0eee2011-05-26 01:26:41 +01004761 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004762 // If we have received more than kIdlesBeforeMarkCompact idle
4763 // notifications we do not perform any cleanup because we don't
4764 // expect to gain much by doing so.
4765 finished = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004766 }
4767
Steve Block6ded16b2010-05-10 14:33:55 +01004768 // Make sure that we have no pending context disposals and
4769 // conditionally uncommit from space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004770 // Take into account that we might have decided to delay full collection
4771 // because incremental marking is in progress.
4772 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
Steve Block44f0eee2011-05-26 01:26:41 +01004773 if (uncommit) UncommitFromSpace();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004774
Steve Blocka7e24c12009-10-30 11:49:00 +00004775 return finished;
4776}
4777
4778
4779#ifdef DEBUG
4780
4781void Heap::Print() {
Ben Murdochc7cc0282012-03-05 14:35:55 +00004782 if (!HasBeenSetUp()) return;
Steve Block44f0eee2011-05-26 01:26:41 +01004783 isolate()->PrintStack();
Steve Blocka7e24c12009-10-30 11:49:00 +00004784 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004785 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4786 space->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +00004787}
4788
4789
4790void Heap::ReportCodeStatistics(const char* title) {
4791 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4792 PagedSpace::ResetCodeStatistics();
4793 // We do not look for code in new space, map space, or old space. If code
4794 // somehow ends up in those spaces, we would miss it here.
4795 code_space_->CollectCodeStatistics();
4796 lo_space_->CollectCodeStatistics();
4797 PagedSpace::ReportCodeStatistics();
4798}
4799
4800
4801// This function expects that NewSpace's allocated objects histogram is
4802// populated (via a call to CollectStatistics or else as a side effect of a
4803// just-completed scavenge collection).
4804void Heap::ReportHeapStatistics(const char* title) {
4805 USE(title);
4806 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
4807 title, gc_count_);
Ben Murdochf87a2032010-10-22 12:50:53 +01004808 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
4809 old_gen_promotion_limit_);
4810 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
4811 old_gen_allocation_limit_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004812 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004813
4814 PrintF("\n");
4815 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
Steve Block44f0eee2011-05-26 01:26:41 +01004816 isolate_->global_handles()->PrintStats();
Steve Blocka7e24c12009-10-30 11:49:00 +00004817 PrintF("\n");
4818
4819 PrintF("Heap statistics : ");
Steve Block44f0eee2011-05-26 01:26:41 +01004820 isolate_->memory_allocator()->ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00004821 PrintF("To space : ");
4822 new_space_.ReportStatistics();
4823 PrintF("Old pointer space : ");
4824 old_pointer_space_->ReportStatistics();
4825 PrintF("Old data space : ");
4826 old_data_space_->ReportStatistics();
4827 PrintF("Code space : ");
4828 code_space_->ReportStatistics();
4829 PrintF("Map space : ");
4830 map_space_->ReportStatistics();
4831 PrintF("Cell space : ");
4832 cell_space_->ReportStatistics();
4833 PrintF("Large object space : ");
4834 lo_space_->ReportStatistics();
4835 PrintF(">>>>>> ========================================= >>>>>>\n");
4836}
4837
4838#endif // DEBUG
4839
4840bool Heap::Contains(HeapObject* value) {
4841 return Contains(value->address());
4842}
4843
4844
4845bool Heap::Contains(Address addr) {
4846 if (OS::IsOutsideAllocatedSpace(addr)) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00004847 return HasBeenSetUp() &&
Steve Blocka7e24c12009-10-30 11:49:00 +00004848 (new_space_.ToSpaceContains(addr) ||
4849 old_pointer_space_->Contains(addr) ||
4850 old_data_space_->Contains(addr) ||
4851 code_space_->Contains(addr) ||
4852 map_space_->Contains(addr) ||
4853 cell_space_->Contains(addr) ||
4854 lo_space_->SlowContains(addr));
4855}
4856
4857
4858bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
4859 return InSpace(value->address(), space);
4860}
4861
4862
4863bool Heap::InSpace(Address addr, AllocationSpace space) {
4864 if (OS::IsOutsideAllocatedSpace(addr)) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00004865 if (!HasBeenSetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00004866
4867 switch (space) {
4868 case NEW_SPACE:
4869 return new_space_.ToSpaceContains(addr);
4870 case OLD_POINTER_SPACE:
4871 return old_pointer_space_->Contains(addr);
4872 case OLD_DATA_SPACE:
4873 return old_data_space_->Contains(addr);
4874 case CODE_SPACE:
4875 return code_space_->Contains(addr);
4876 case MAP_SPACE:
4877 return map_space_->Contains(addr);
4878 case CELL_SPACE:
4879 return cell_space_->Contains(addr);
4880 case LO_SPACE:
4881 return lo_space_->SlowContains(addr);
4882 }
4883
4884 return false;
4885}
4886
4887
4888#ifdef DEBUG
4889void Heap::Verify() {
Ben Murdochc7cc0282012-03-05 14:35:55 +00004890 ASSERT(HasBeenSetUp());
Steve Blocka7e24c12009-10-30 11:49:00 +00004891
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004892 store_buffer()->Verify();
4893
Steve Blocka7e24c12009-10-30 11:49:00 +00004894 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00004895 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00004896
4897 new_space_.Verify();
4898
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004899 old_pointer_space_->Verify(&visitor);
4900 map_space_->Verify(&visitor);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004901
4902 VerifyPointersVisitor no_dirty_regions_visitor;
4903 old_data_space_->Verify(&no_dirty_regions_visitor);
4904 code_space_->Verify(&no_dirty_regions_visitor);
4905 cell_space_->Verify(&no_dirty_regions_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00004906
4907 lo_space_->Verify();
4908}
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004909
Steve Blocka7e24c12009-10-30 11:49:00 +00004910#endif // DEBUG
4911
4912
John Reck59135872010-11-02 12:39:01 -07004913MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004914 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004915 Object* new_table;
4916 { MaybeObject* maybe_new_table =
4917 symbol_table()->LookupSymbol(string, &symbol);
4918 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004920 // Can't use set_symbol_table because SymbolTable::cast knows that
4921 // SymbolTable is a singleton and checks for identity.
4922 roots_[kSymbolTableRootIndex] = new_table;
4923 ASSERT(symbol != NULL);
4924 return symbol;
4925}
4926
4927
Steve Block9fac8402011-05-12 15:51:54 +01004928MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
4929 Object* symbol = NULL;
4930 Object* new_table;
4931 { MaybeObject* maybe_new_table =
4932 symbol_table()->LookupAsciiSymbol(string, &symbol);
4933 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4934 }
4935 // Can't use set_symbol_table because SymbolTable::cast knows that
4936 // SymbolTable is a singleton and checks for identity.
4937 roots_[kSymbolTableRootIndex] = new_table;
4938 ASSERT(symbol != NULL);
4939 return symbol;
4940}
4941
4942
Ben Murdoch257744e2011-11-30 15:57:28 +00004943MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
4944 int from,
4945 int length) {
4946 Object* symbol = NULL;
4947 Object* new_table;
4948 { MaybeObject* maybe_new_table =
4949 symbol_table()->LookupSubStringAsciiSymbol(string,
4950 from,
4951 length,
4952 &symbol);
4953 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4954 }
4955 // Can't use set_symbol_table because SymbolTable::cast knows that
4956 // SymbolTable is a singleton and checks for identity.
4957 roots_[kSymbolTableRootIndex] = new_table;
4958 ASSERT(symbol != NULL);
4959 return symbol;
4960}
4961
4962
Steve Block9fac8402011-05-12 15:51:54 +01004963MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
4964 Object* symbol = NULL;
4965 Object* new_table;
4966 { MaybeObject* maybe_new_table =
4967 symbol_table()->LookupTwoByteSymbol(string, &symbol);
4968 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4969 }
4970 // Can't use set_symbol_table because SymbolTable::cast knows that
4971 // SymbolTable is a singleton and checks for identity.
4972 roots_[kSymbolTableRootIndex] = new_table;
4973 ASSERT(symbol != NULL);
4974 return symbol;
4975}
4976
4977
John Reck59135872010-11-02 12:39:01 -07004978MaybeObject* Heap::LookupSymbol(String* string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004979 if (string->IsSymbol()) return string;
4980 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004981 Object* new_table;
4982 { MaybeObject* maybe_new_table =
4983 symbol_table()->LookupString(string, &symbol);
4984 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4985 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004986 // Can't use set_symbol_table because SymbolTable::cast knows that
4987 // SymbolTable is a singleton and checks for identity.
4988 roots_[kSymbolTableRootIndex] = new_table;
4989 ASSERT(symbol != NULL);
4990 return symbol;
4991}
4992
4993
4994bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
4995 if (string->IsSymbol()) {
4996 *symbol = string;
4997 return true;
4998 }
4999 return symbol_table()->LookupSymbolIfExists(string, symbol);
5000}
5001
5002
5003#ifdef DEBUG
5004void Heap::ZapFromSpace() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005005 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5006 new_space_.FromSpaceEnd());
5007 while (it.has_next()) {
5008 NewSpacePage* page = it.next();
5009 for (Address cursor = page->area_start(), limit = page->area_end();
5010 cursor < limit;
5011 cursor += kPointerSize) {
5012 Memory::Address_at(cursor) = kFromSpaceZapValue;
5013 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005014 }
5015}
5016#endif // DEBUG
5017
5018
Ben Murdoch3bec4d22010-07-22 14:51:16 +01005019void Heap::IterateAndMarkPointersToFromSpace(Address start,
5020 Address end,
5021 ObjectSlotCallback callback) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005022 Address slot_address = start;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005023
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005024 // We are not collecting slots on new space objects during mutation
5025 // thus we have to scan for pointers to evacuation candidates when we
5026 // promote objects. But we should not record any slots in non-black
5027 // objects. Grey object's slots would be rescanned.
5028 // White object might not survive until the end of collection
5029 // it would be a violation of the invariant to record it's slots.
5030 bool record_slots = false;
5031 if (incremental_marking()->IsCompacting()) {
5032 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5033 record_slots = Marking::IsBlack(mark_bit);
5034 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005035
5036 while (slot_address < end) {
5037 Object** slot = reinterpret_cast<Object**>(slot_address);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005038 Object* object = *slot;
5039 // If the store buffer becomes overfull we mark pages as being exempt from
5040 // the store buffer. These pages are scanned to find pointers that point
5041 // to the new space. In that case we may hit newly promoted objects and
5042 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5043 if (object->IsHeapObject()) {
5044 if (Heap::InFromSpace(object)) {
5045 callback(reinterpret_cast<HeapObject**>(slot),
5046 HeapObject::cast(object));
5047 Object* new_object = *slot;
5048 if (InNewSpace(new_object)) {
5049 SLOW_ASSERT(Heap::InToSpace(new_object));
5050 SLOW_ASSERT(new_object->IsHeapObject());
5051 store_buffer_.EnterDirectlyIntoStoreBuffer(
5052 reinterpret_cast<Address>(slot));
5053 }
5054 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5055 } else if (record_slots &&
5056 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5057 mark_compact_collector()->RecordSlot(slot, slot, object);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005058 }
5059 }
5060 slot_address += kPointerSize;
5061 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005062}
5063
5064
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005065#ifdef DEBUG
5066typedef bool (*CheckStoreBufferFilter)(Object** addr);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005067
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005068
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005069bool IsAMapPointerAddress(Object** addr) {
5070 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5071 int mod = a % Map::kSize;
5072 return mod >= Map::kPointerFieldsBeginOffset &&
5073 mod < Map::kPointerFieldsEndOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005074}
5075
5076
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005077bool EverythingsAPointer(Object** addr) {
5078 return true;
5079}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005080
Steve Blocka7e24c12009-10-30 11:49:00 +00005081
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005082static void CheckStoreBuffer(Heap* heap,
5083 Object** current,
5084 Object** limit,
5085 Object**** store_buffer_position,
5086 Object*** store_buffer_top,
5087 CheckStoreBufferFilter filter,
5088 Address special_garbage_start,
5089 Address special_garbage_end) {
5090 Map* free_space_map = heap->free_space_map();
5091 for ( ; current < limit; current++) {
5092 Object* o = *current;
5093 Address current_address = reinterpret_cast<Address>(current);
5094 // Skip free space.
5095 if (o == free_space_map) {
5096 Address current_address = reinterpret_cast<Address>(current);
5097 FreeSpace* free_space =
5098 FreeSpace::cast(HeapObject::FromAddress(current_address));
5099 int skip = free_space->Size();
5100 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5101 ASSERT(skip > 0);
5102 current_address += skip - kPointerSize;
5103 current = reinterpret_cast<Object**>(current_address);
5104 continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00005105 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005106 // Skip the current linear allocation space between top and limit which is
5107 // unmarked with the free space map, but can contain junk.
5108 if (current_address == special_garbage_start &&
5109 special_garbage_end != special_garbage_start) {
5110 current_address = special_garbage_end - kPointerSize;
5111 current = reinterpret_cast<Object**>(current_address);
5112 continue;
5113 }
5114 if (!(*filter)(current)) continue;
5115 ASSERT(current_address < special_garbage_start ||
5116 current_address >= special_garbage_end);
5117 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5118 // We have to check that the pointer does not point into new space
5119 // without trying to cast it to a heap object since the hash field of
5120 // a string can contain values like 1 and 3 which are tagged null
5121 // pointers.
5122 if (!heap->InNewSpace(o)) continue;
5123 while (**store_buffer_position < current &&
5124 *store_buffer_position < store_buffer_top) {
5125 (*store_buffer_position)++;
5126 }
5127 if (**store_buffer_position != current ||
5128 *store_buffer_position == store_buffer_top) {
5129 Object** obj_start = current;
5130 while (!(*obj_start)->IsMap()) obj_start--;
5131 UNREACHABLE();
5132 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005133 }
5134}
5135
5136
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005137// Check that the store buffer contains all intergenerational pointers by
5138// scanning a page and ensuring that all pointers to young space are in the
5139// store buffer.
5140void Heap::OldPointerSpaceCheckStoreBuffer() {
5141 OldSpace* space = old_pointer_space();
5142 PageIterator pages(space);
5143
5144 store_buffer()->SortUniq();
5145
5146 while (pages.has_next()) {
5147 Page* page = pages.next();
5148 Object** current = reinterpret_cast<Object**>(page->area_start());
5149
5150 Address end = page->area_end();
5151
5152 Object*** store_buffer_position = store_buffer()->Start();
5153 Object*** store_buffer_top = store_buffer()->Top();
5154
5155 Object** limit = reinterpret_cast<Object**>(end);
5156 CheckStoreBuffer(this,
5157 current,
5158 limit,
5159 &store_buffer_position,
5160 store_buffer_top,
5161 &EverythingsAPointer,
5162 space->top(),
5163 space->limit());
5164 }
5165}
5166
5167
5168void Heap::MapSpaceCheckStoreBuffer() {
5169 MapSpace* space = map_space();
5170 PageIterator pages(space);
5171
5172 store_buffer()->SortUniq();
5173
5174 while (pages.has_next()) {
5175 Page* page = pages.next();
5176 Object** current = reinterpret_cast<Object**>(page->area_start());
5177
5178 Address end = page->area_end();
5179
5180 Object*** store_buffer_position = store_buffer()->Start();
5181 Object*** store_buffer_top = store_buffer()->Top();
5182
5183 Object** limit = reinterpret_cast<Object**>(end);
5184 CheckStoreBuffer(this,
5185 current,
5186 limit,
5187 &store_buffer_position,
5188 store_buffer_top,
5189 &IsAMapPointerAddress,
5190 space->top(),
5191 space->limit());
5192 }
5193}
5194
5195
5196void Heap::LargeObjectSpaceCheckStoreBuffer() {
5197 LargeObjectIterator it(lo_space());
5198 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5199 // We only have code, sequential strings, or fixed arrays in large
5200 // object space, and only fixed arrays can possibly contain pointers to
5201 // the young generation.
5202 if (object->IsFixedArray()) {
5203 Object*** store_buffer_position = store_buffer()->Start();
5204 Object*** store_buffer_top = store_buffer()->Top();
5205 Object** current = reinterpret_cast<Object**>(object->address());
5206 Object** limit =
5207 reinterpret_cast<Object**>(object->address() + object->Size());
5208 CheckStoreBuffer(this,
5209 current,
5210 limit,
5211 &store_buffer_position,
5212 store_buffer_top,
5213 &EverythingsAPointer,
5214 NULL,
5215 NULL);
5216 }
5217 }
5218}
5219#endif
5220
5221
Steve Blockd0582a62009-12-15 09:54:21 +00005222void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5223 IterateStrongRoots(v, mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00005224 IterateWeakRoots(v, mode);
5225}
5226
5227
5228void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005229 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Ben Murdochc7cc0282012-03-05 14:35:55 +00005230 v->Synchronize(VisitorSynchronization::kSymbolTable);
Ben Murdoch257744e2011-11-30 15:57:28 +00005231 if (mode != VISIT_ALL_IN_SCAVENGE &&
5232 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00005233 // Scavenge collections have special processing for this.
Steve Block44f0eee2011-05-26 01:26:41 +01005234 external_string_table_.Iterate(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005235 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005236 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
Steve Blocka7e24c12009-10-30 11:49:00 +00005237}
5238
5239
Steve Blockd0582a62009-12-15 09:54:21 +00005240void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005241 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005242 v->Synchronize(VisitorSynchronization::kStrongRootList);
Steve Blocka7e24c12009-10-30 11:49:00 +00005243
Iain Merrick75681382010-08-19 15:07:18 +01005244 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
Ben Murdochc7cc0282012-03-05 14:35:55 +00005245 v->Synchronize(VisitorSynchronization::kSymbol);
Steve Blocka7e24c12009-10-30 11:49:00 +00005246
Steve Block44f0eee2011-05-26 01:26:41 +01005247 isolate_->bootstrapper()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005248 v->Synchronize(VisitorSynchronization::kBootstrapper);
Steve Block44f0eee2011-05-26 01:26:41 +01005249 isolate_->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005250 v->Synchronize(VisitorSynchronization::kTop);
Steve Blocka7e24c12009-10-30 11:49:00 +00005251 Relocatable::Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005252 v->Synchronize(VisitorSynchronization::kRelocatable);
Steve Blocka7e24c12009-10-30 11:49:00 +00005253
5254#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +01005255 isolate_->debug()->Iterate(v);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005256 if (isolate_->deoptimizer_data() != NULL) {
5257 isolate_->deoptimizer_data()->Iterate(v);
5258 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005259#endif
Ben Murdochc7cc0282012-03-05 14:35:55 +00005260 v->Synchronize(VisitorSynchronization::kDebug);
Steve Block44f0eee2011-05-26 01:26:41 +01005261 isolate_->compilation_cache()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005262 v->Synchronize(VisitorSynchronization::kCompilationCache);
Steve Blocka7e24c12009-10-30 11:49:00 +00005263
5264 // Iterate over local handles in handle scopes.
Steve Block44f0eee2011-05-26 01:26:41 +01005265 isolate_->handle_scope_implementer()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005266 v->Synchronize(VisitorSynchronization::kHandleScope);
Steve Blocka7e24c12009-10-30 11:49:00 +00005267
Leon Clarkee46be812010-01-19 14:06:41 +00005268 // Iterate over the builtin code objects and code stubs in the
5269 // heap. Note that it is not necessary to iterate over code objects
5270 // on scavenge collections.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005271 if (mode != VISIT_ALL_IN_SCAVENGE) {
Steve Block44f0eee2011-05-26 01:26:41 +01005272 isolate_->builtins()->IterateBuiltins(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005273 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005274 v->Synchronize(VisitorSynchronization::kBuiltins);
Steve Blocka7e24c12009-10-30 11:49:00 +00005275
5276 // Iterate over global handles.
Ben Murdoch257744e2011-11-30 15:57:28 +00005277 switch (mode) {
5278 case VISIT_ONLY_STRONG:
5279 isolate_->global_handles()->IterateStrongRoots(v);
5280 break;
5281 case VISIT_ALL_IN_SCAVENGE:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005282 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
Ben Murdoch257744e2011-11-30 15:57:28 +00005283 break;
5284 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5285 case VISIT_ALL:
5286 isolate_->global_handles()->IterateAllRoots(v);
5287 break;
Steve Blockd0582a62009-12-15 09:54:21 +00005288 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005289 v->Synchronize(VisitorSynchronization::kGlobalHandles);
Steve Blocka7e24c12009-10-30 11:49:00 +00005290
5291 // Iterate over pointers being held by inactive threads.
Steve Block44f0eee2011-05-26 01:26:41 +01005292 isolate_->thread_manager()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005293 v->Synchronize(VisitorSynchronization::kThreadManager);
Leon Clarked91b9f72010-01-27 17:25:45 +00005294
5295 // Iterate over the pointers the Serialization/Deserialization code is
5296 // holding.
5297 // During garbage collection this keeps the partial snapshot cache alive.
5298 // During deserialization of the startup snapshot this creates the partial
5299 // snapshot cache and deserializes the objects it refers to. During
5300 // serialization this does nothing, since the partial snapshot cache is
5301 // empty. However the next thing we do is create the partial snapshot,
5302 // filling up the partial snapshot cache with objects it needs as we go.
5303 SerializerDeserializer::Iterate(v);
5304 // We don't do a v->Synchronize call here, because in debug mode that will
5305 // output a flag to the snapshot. However at this point the serializer and
5306 // deserializer are deliberately a little unsynchronized (see above) so the
5307 // checking of the sync flag in the snapshot would fail.
Steve Blocka7e24c12009-10-30 11:49:00 +00005308}
Steve Blocka7e24c12009-10-30 11:49:00 +00005309
5310
Steve Blocka7e24c12009-10-30 11:49:00 +00005311// TODO(1236194): Since the heap size is configurable on the command line
5312// and through the API, we should gracefully handle the case that the heap
5313// size is not big enough to fit all the initial objects.
Russell Brenner90bac252010-11-18 13:33:46 -08005314bool Heap::ConfigureHeap(int max_semispace_size,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005315 intptr_t max_old_gen_size,
5316 intptr_t max_executable_size) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00005317 if (HasBeenSetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005318
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005319 if (max_semispace_size > 0) {
5320 if (max_semispace_size < Page::kPageSize) {
5321 max_semispace_size = Page::kPageSize;
5322 if (FLAG_trace_gc) {
5323 PrintF("Max semispace size cannot be less than %dkbytes\n",
5324 Page::kPageSize >> 10);
5325 }
5326 }
5327 max_semispace_size_ = max_semispace_size;
5328 }
Steve Block3ce2e202009-11-05 08:53:23 +00005329
5330 if (Snapshot::IsEnabled()) {
5331 // If we are using a snapshot we always reserve the default amount
5332 // of memory for each semispace because code in the snapshot has
5333 // write-barrier code that relies on the size and alignment of new
5334 // space. We therefore cannot use a larger max semispace size
5335 // than the default reserved semispace size.
5336 if (max_semispace_size_ > reserved_semispace_size_) {
5337 max_semispace_size_ = reserved_semispace_size_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005338 if (FLAG_trace_gc) {
5339 PrintF("Max semispace size cannot be more than %dkbytes\n",
5340 reserved_semispace_size_ >> 10);
5341 }
Steve Block3ce2e202009-11-05 08:53:23 +00005342 }
5343 } else {
5344 // If we are not using snapshots we reserve space for the actual
5345 // max semispace size.
5346 reserved_semispace_size_ = max_semispace_size_;
5347 }
5348
5349 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Russell Brenner90bac252010-11-18 13:33:46 -08005350 if (max_executable_size > 0) {
5351 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5352 }
5353
5354 // The max executable size must be less than or equal to the max old
5355 // generation size.
5356 if (max_executable_size_ > max_old_generation_size_) {
5357 max_executable_size_ = max_old_generation_size_;
5358 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005359
5360 // The new space size must be a power of two to support single-bit testing
5361 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00005362 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5363 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5364 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5365 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00005366
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005367 // The old generation is paged and needs at least one page for each space.
5368 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5369 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5370 Page::kPageSize),
5371 RoundUp(max_old_generation_size_,
5372 Page::kPageSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00005373
Steve Block44f0eee2011-05-26 01:26:41 +01005374 configured_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00005375 return true;
5376}
5377
5378
5379bool Heap::ConfigureHeapDefault() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005380 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5381 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5382 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
Steve Blocka7e24c12009-10-30 11:49:00 +00005383}
5384
5385
Ben Murdochbb769b22010-08-11 14:56:33 +01005386void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
Iain Merrick75681382010-08-19 15:07:18 +01005387 *stats->start_marker = HeapStats::kStartMarker;
5388 *stats->end_marker = HeapStats::kEndMarker;
Ben Murdochf87a2032010-10-22 12:50:53 +01005389 *stats->new_space_size = new_space_.SizeAsInt();
5390 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
Steve Blockd0582a62009-12-15 09:54:21 +00005391 *stats->old_pointer_space_size = old_pointer_space_->Size();
5392 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5393 *stats->old_data_space_size = old_data_space_->Size();
5394 *stats->old_data_space_capacity = old_data_space_->Capacity();
5395 *stats->code_space_size = code_space_->Size();
5396 *stats->code_space_capacity = code_space_->Capacity();
5397 *stats->map_space_size = map_space_->Size();
5398 *stats->map_space_capacity = map_space_->Capacity();
5399 *stats->cell_space_size = cell_space_->Size();
5400 *stats->cell_space_capacity = cell_space_->Capacity();
5401 *stats->lo_space_size = lo_space_->Size();
Steve Block44f0eee2011-05-26 01:26:41 +01005402 isolate_->global_handles()->RecordStats(stats);
5403 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
Ben Murdochbb769b22010-08-11 14:56:33 +01005404 *stats->memory_allocator_capacity =
Steve Block44f0eee2011-05-26 01:26:41 +01005405 isolate()->memory_allocator()->Size() +
5406 isolate()->memory_allocator()->Available();
Iain Merrick75681382010-08-19 15:07:18 +01005407 *stats->os_error = OS::GetLastError();
Steve Block44f0eee2011-05-26 01:26:41 +01005408 isolate()->memory_allocator()->Available();
Ben Murdochbb769b22010-08-11 14:56:33 +01005409 if (take_snapshot) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005410 HeapIterator iterator;
Ben Murdochbb769b22010-08-11 14:56:33 +01005411 for (HeapObject* obj = iterator.next();
5412 obj != NULL;
5413 obj = iterator.next()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005414 InstanceType type = obj->map()->instance_type();
5415 ASSERT(0 <= type && type <= LAST_TYPE);
5416 stats->objects_per_type[type]++;
5417 stats->size_per_type[type] += obj->Size();
5418 }
5419 }
Steve Blockd0582a62009-12-15 09:54:21 +00005420}
5421
5422
Ben Murdochf87a2032010-10-22 12:50:53 +01005423intptr_t Heap::PromotedSpaceSize() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005424 return old_pointer_space_->Size()
5425 + old_data_space_->Size()
5426 + code_space_->Size()
5427 + map_space_->Size()
5428 + cell_space_->Size()
5429 + lo_space_->Size();
5430}
5431
5432
Ben Murdochc7cc0282012-03-05 14:35:55 +00005433intptr_t Heap::PromotedSpaceSizeOfObjects() {
5434 return old_pointer_space_->SizeOfObjects()
5435 + old_data_space_->SizeOfObjects()
5436 + code_space_->SizeOfObjects()
5437 + map_space_->SizeOfObjects()
5438 + cell_space_->SizeOfObjects()
5439 + lo_space_->SizeOfObjects();
5440}
5441
5442
Steve Blocka7e24c12009-10-30 11:49:00 +00005443int Heap::PromotedExternalMemorySize() {
5444 if (amount_of_external_allocated_memory_
5445 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5446 return amount_of_external_allocated_memory_
5447 - amount_of_external_allocated_memory_at_last_global_gc_;
5448}
5449
Steve Block44f0eee2011-05-26 01:26:41 +01005450#ifdef DEBUG
5451
5452// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5453static const int kMarkTag = 2;
5454
5455
5456class HeapDebugUtils {
5457 public:
5458 explicit HeapDebugUtils(Heap* heap)
5459 : search_for_any_global_(false),
5460 search_target_(NULL),
5461 found_target_(false),
5462 object_stack_(20),
5463 heap_(heap) {
5464 }
5465
5466 class MarkObjectVisitor : public ObjectVisitor {
5467 public:
5468 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5469
5470 void VisitPointers(Object** start, Object** end) {
5471 // Copy all HeapObject pointers in [start, end)
5472 for (Object** p = start; p < end; p++) {
5473 if ((*p)->IsHeapObject())
5474 utils_->MarkObjectRecursively(p);
5475 }
5476 }
5477
5478 HeapDebugUtils* utils_;
5479 };
5480
5481 void MarkObjectRecursively(Object** p) {
5482 if (!(*p)->IsHeapObject()) return;
5483
5484 HeapObject* obj = HeapObject::cast(*p);
5485
5486 Object* map = obj->map();
5487
5488 if (!map->IsHeapObject()) return; // visited before
5489
5490 if (found_target_) return; // stop if target found
5491 object_stack_.Add(obj);
5492 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5493 (!search_for_any_global_ && (obj == search_target_))) {
5494 found_target_ = true;
5495 return;
5496 }
5497
5498 // not visited yet
5499 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5500
5501 Address map_addr = map_p->address();
5502
Ben Murdochc7cc0282012-03-05 14:35:55 +00005503 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
Steve Block44f0eee2011-05-26 01:26:41 +01005504
5505 MarkObjectRecursively(&map);
5506
5507 MarkObjectVisitor mark_visitor(this);
5508
5509 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5510 &mark_visitor);
5511
5512 if (!found_target_) // don't pop if found the target
5513 object_stack_.RemoveLast();
5514 }
5515
5516
5517 class UnmarkObjectVisitor : public ObjectVisitor {
5518 public:
5519 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5520
5521 void VisitPointers(Object** start, Object** end) {
5522 // Copy all HeapObject pointers in [start, end)
5523 for (Object** p = start; p < end; p++) {
5524 if ((*p)->IsHeapObject())
5525 utils_->UnmarkObjectRecursively(p);
5526 }
5527 }
5528
5529 HeapDebugUtils* utils_;
5530 };
5531
5532
5533 void UnmarkObjectRecursively(Object** p) {
5534 if (!(*p)->IsHeapObject()) return;
5535
5536 HeapObject* obj = HeapObject::cast(*p);
5537
5538 Object* map = obj->map();
5539
5540 if (map->IsHeapObject()) return; // unmarked already
5541
5542 Address map_addr = reinterpret_cast<Address>(map);
5543
5544 map_addr -= kMarkTag;
5545
5546 ASSERT_TAG_ALIGNED(map_addr);
5547
5548 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5549
Ben Murdochc7cc0282012-03-05 14:35:55 +00005550 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
Steve Block44f0eee2011-05-26 01:26:41 +01005551
5552 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5553
5554 UnmarkObjectVisitor unmark_visitor(this);
5555
5556 obj->IterateBody(Map::cast(map_p)->instance_type(),
5557 obj->SizeFromMap(Map::cast(map_p)),
5558 &unmark_visitor);
5559 }
5560
5561
5562 void MarkRootObjectRecursively(Object** root) {
5563 if (search_for_any_global_) {
5564 ASSERT(search_target_ == NULL);
5565 } else {
5566 ASSERT(search_target_->IsHeapObject());
5567 }
5568 found_target_ = false;
5569 object_stack_.Clear();
5570
5571 MarkObjectRecursively(root);
5572 UnmarkObjectRecursively(root);
5573
5574 if (found_target_) {
5575 PrintF("=====================================\n");
5576 PrintF("==== Path to object ====\n");
5577 PrintF("=====================================\n\n");
5578
5579 ASSERT(!object_stack_.is_empty());
5580 for (int i = 0; i < object_stack_.length(); i++) {
5581 if (i > 0) PrintF("\n |\n |\n V\n\n");
5582 Object* obj = object_stack_[i];
5583 obj->Print();
5584 }
5585 PrintF("=====================================\n");
5586 }
5587 }
5588
5589 // Helper class for visiting HeapObjects recursively.
5590 class MarkRootVisitor: public ObjectVisitor {
5591 public:
5592 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5593
5594 void VisitPointers(Object** start, Object** end) {
5595 // Visit all HeapObject pointers in [start, end)
5596 for (Object** p = start; p < end; p++) {
5597 if ((*p)->IsHeapObject())
5598 utils_->MarkRootObjectRecursively(p);
5599 }
5600 }
5601
5602 HeapDebugUtils* utils_;
5603 };
5604
5605 bool search_for_any_global_;
5606 Object* search_target_;
5607 bool found_target_;
5608 List<Object*> object_stack_;
5609 Heap* heap_;
5610
5611 friend class Heap;
5612};
5613
5614#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005615
Ben Murdochc7cc0282012-03-05 14:35:55 +00005616bool Heap::SetUp(bool create_heap_objects) {
Steve Block44f0eee2011-05-26 01:26:41 +01005617#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005618 allocation_timeout_ = FLAG_gc_interval;
Steve Block44f0eee2011-05-26 01:26:41 +01005619 debug_utils_ = new HeapDebugUtils(this);
5620#endif
5621
Steve Blocka7e24c12009-10-30 11:49:00 +00005622 // Initialize heap spaces and initial maps and objects. Whenever something
5623 // goes wrong, just return false. The caller should check the results and
5624 // call Heap::TearDown() to release allocated memory.
5625 //
Ben Murdochc7cc0282012-03-05 14:35:55 +00005626 // If the heap is not yet configured (e.g. through the API), configure it.
Steve Blocka7e24c12009-10-30 11:49:00 +00005627 // Configuration is based on the flags new-space-size (really the semispace
5628 // size) and old-space-size if set or the initial values of semispace_size_
5629 // and old_generation_size_ otherwise.
Steve Block44f0eee2011-05-26 01:26:41 +01005630 if (!configured_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005631 if (!ConfigureHeapDefault()) return false;
5632 }
5633
Steve Block44f0eee2011-05-26 01:26:41 +01005634 gc_initializer_mutex->Lock();
5635 static bool initialized_gc = false;
5636 if (!initialized_gc) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005637 initialized_gc = true;
5638 InitializeScavengingVisitorsTables();
5639 NewSpaceScavenger::Initialize();
5640 MarkCompactCollector::Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01005641 }
5642 gc_initializer_mutex->Unlock();
Iain Merrick75681382010-08-19 15:07:18 +01005643
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005644 MarkMapPointersAsEncoded(false);
5645
Ben Murdochc7cc0282012-03-05 14:35:55 +00005646 // Set up memory allocator.
5647 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
Steve Block44f0eee2011-05-26 01:26:41 +01005648 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005649
Ben Murdochc7cc0282012-03-05 14:35:55 +00005650 // Set up new space.
5651 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
Steve Block3ce2e202009-11-05 08:53:23 +00005652 return false;
5653 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005654
5655 // Initialize old pointer space.
5656 old_pointer_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005657 new OldSpace(this,
5658 max_old_generation_size_,
5659 OLD_POINTER_SPACE,
5660 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005661 if (old_pointer_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005662 if (!old_pointer_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005663
5664 // Initialize old data space.
5665 old_data_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005666 new OldSpace(this,
5667 max_old_generation_size_,
5668 OLD_DATA_SPACE,
5669 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005670 if (old_data_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005671 if (!old_data_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005672
5673 // Initialize the code space, set its maximum capacity to the old
5674 // generation size. It needs executable memory.
5675 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5676 // virtual address space, so that they can call each other with near calls.
5677 if (code_range_size_ > 0) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00005678 if (!isolate_->code_range()->SetUp(code_range_size_)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005679 return false;
5680 }
5681 }
5682
5683 code_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005684 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005685 if (code_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005686 if (!code_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005687
5688 // Initialize map space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005689 map_space_ = new MapSpace(this,
5690 max_old_generation_size_,
5691 FLAG_max_map_space_pages,
5692 MAP_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005693 if (map_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005694 if (!map_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005695
5696 // Initialize global property cell space.
Steve Block44f0eee2011-05-26 01:26:41 +01005697 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005698 if (cell_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005699 if (!cell_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005700
5701 // The large object code space may contain code or data. We set the memory
5702 // to be non-executable here for safety, but this means we need to enable it
5703 // explicitly when allocating large code objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005704 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005705 if (lo_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005706 if (!lo_space_->SetUp()) return false;
5707
5708 // Set up the seed that is used to randomize the string hash function.
5709 ASSERT(hash_seed() == 0);
5710 if (FLAG_randomize_hashes) {
5711 if (FLAG_hash_seed == 0) {
5712 set_hash_seed(
5713 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
5714 } else {
5715 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5716 }
5717 }
5718
Steve Blocka7e24c12009-10-30 11:49:00 +00005719 if (create_heap_objects) {
5720 // Create initial maps.
5721 if (!CreateInitialMaps()) return false;
5722 if (!CreateApiObjects()) return false;
5723
5724 // Create initial objects
5725 if (!CreateInitialObjects()) return false;
Ben Murdochf87a2032010-10-22 12:50:53 +01005726
5727 global_contexts_list_ = undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005728 }
5729
Steve Block44f0eee2011-05-26 01:26:41 +01005730 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5731 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005732
Ben Murdochc7cc0282012-03-05 14:35:55 +00005733 store_buffer()->SetUp();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005734
Steve Blocka7e24c12009-10-30 11:49:00 +00005735 return true;
5736}
5737
5738
Steve Blockd0582a62009-12-15 09:54:21 +00005739void Heap::SetStackLimits() {
Steve Block44f0eee2011-05-26 01:26:41 +01005740 ASSERT(isolate_ != NULL);
5741 ASSERT(isolate_ == isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00005742 // On 64 bit machines, pointers are generally out of range of Smis. We write
5743 // something that looks like an out of range Smi to the GC.
5744
Steve Blockd0582a62009-12-15 09:54:21 +00005745 // Set up the special root array entries containing the stack limits.
5746 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00005747 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00005748 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005749 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blockd0582a62009-12-15 09:54:21 +00005750 roots_[kRealStackLimitRootIndex] =
5751 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005752 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00005753}
5754
5755
5756void Heap::TearDown() {
Leon Clarkef7060e22010-06-03 12:02:55 +01005757 if (FLAG_print_cumulative_gc_stat) {
5758 PrintF("\n\n");
5759 PrintF("gc_count=%d ", gc_count_);
5760 PrintF("mark_sweep_count=%d ", ms_count_);
Steve Block44f0eee2011-05-26 01:26:41 +01005761 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5762 PrintF("min_in_mutator=%d ", get_min_in_mutator());
Ben Murdochf87a2032010-10-22 12:50:53 +01005763 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
Steve Block44f0eee2011-05-26 01:26:41 +01005764 get_max_alive_after_gc());
Leon Clarkef7060e22010-06-03 12:02:55 +01005765 PrintF("\n\n");
5766 }
5767
Steve Block44f0eee2011-05-26 01:26:41 +01005768 isolate_->global_handles()->TearDown();
Steve Blocka7e24c12009-10-30 11:49:00 +00005769
Steve Block44f0eee2011-05-26 01:26:41 +01005770 external_string_table_.TearDown();
Leon Clarkee46be812010-01-19 14:06:41 +00005771
Steve Blocka7e24c12009-10-30 11:49:00 +00005772 new_space_.TearDown();
5773
5774 if (old_pointer_space_ != NULL) {
5775 old_pointer_space_->TearDown();
5776 delete old_pointer_space_;
5777 old_pointer_space_ = NULL;
5778 }
5779
5780 if (old_data_space_ != NULL) {
5781 old_data_space_->TearDown();
5782 delete old_data_space_;
5783 old_data_space_ = NULL;
5784 }
5785
5786 if (code_space_ != NULL) {
5787 code_space_->TearDown();
5788 delete code_space_;
5789 code_space_ = NULL;
5790 }
5791
5792 if (map_space_ != NULL) {
5793 map_space_->TearDown();
5794 delete map_space_;
5795 map_space_ = NULL;
5796 }
5797
5798 if (cell_space_ != NULL) {
5799 cell_space_->TearDown();
5800 delete cell_space_;
5801 cell_space_ = NULL;
5802 }
5803
5804 if (lo_space_ != NULL) {
5805 lo_space_->TearDown();
5806 delete lo_space_;
5807 lo_space_ = NULL;
5808 }
5809
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005810 store_buffer()->TearDown();
5811 incremental_marking()->TearDown();
5812
Steve Block44f0eee2011-05-26 01:26:41 +01005813 isolate_->memory_allocator()->TearDown();
5814
5815#ifdef DEBUG
5816 delete debug_utils_;
5817 debug_utils_ = NULL;
5818#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005819}
5820
5821
5822void Heap::Shrink() {
5823 // Try to shrink all paged spaces.
5824 PagedSpaces spaces;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005825 for (PagedSpace* space = spaces.next();
5826 space != NULL;
5827 space = spaces.next()) {
5828 space->ReleaseAllUnusedPages();
5829 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005830}
5831
5832
Steve Block6ded16b2010-05-10 14:33:55 +01005833void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5834 ASSERT(callback != NULL);
5835 GCPrologueCallbackPair pair(callback, gc_type);
5836 ASSERT(!gc_prologue_callbacks_.Contains(pair));
5837 return gc_prologue_callbacks_.Add(pair);
5838}
5839
5840
5841void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5842 ASSERT(callback != NULL);
5843 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
5844 if (gc_prologue_callbacks_[i].callback == callback) {
5845 gc_prologue_callbacks_.Remove(i);
5846 return;
5847 }
5848 }
5849 UNREACHABLE();
5850}
5851
5852
5853void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5854 ASSERT(callback != NULL);
5855 GCEpilogueCallbackPair pair(callback, gc_type);
5856 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
5857 return gc_epilogue_callbacks_.Add(pair);
5858}
5859
5860
5861void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5862 ASSERT(callback != NULL);
5863 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
5864 if (gc_epilogue_callbacks_[i].callback == callback) {
5865 gc_epilogue_callbacks_.Remove(i);
5866 return;
5867 }
5868 }
5869 UNREACHABLE();
5870}
5871
5872
Steve Blocka7e24c12009-10-30 11:49:00 +00005873#ifdef DEBUG
5874
5875class PrintHandleVisitor: public ObjectVisitor {
5876 public:
5877 void VisitPointers(Object** start, Object** end) {
5878 for (Object** p = start; p < end; p++)
Ben Murdochf87a2032010-10-22 12:50:53 +01005879 PrintF(" handle %p to %p\n",
5880 reinterpret_cast<void*>(p),
5881 reinterpret_cast<void*>(*p));
Steve Blocka7e24c12009-10-30 11:49:00 +00005882 }
5883};
5884
5885void Heap::PrintHandles() {
5886 PrintF("Handles:\n");
5887 PrintHandleVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +01005888 isolate_->handle_scope_implementer()->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +00005889}
5890
5891#endif
5892
5893
5894Space* AllSpaces::next() {
5895 switch (counter_++) {
5896 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005897 return HEAP->new_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005898 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005899 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005900 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005901 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005902 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005903 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005904 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005905 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005906 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005907 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005908 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005909 return HEAP->lo_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005910 default:
5911 return NULL;
5912 }
5913}
5914
5915
5916PagedSpace* PagedSpaces::next() {
5917 switch (counter_++) {
5918 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005919 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005920 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005921 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005922 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005923 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005924 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005925 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005926 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005927 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005928 default:
5929 return NULL;
5930 }
5931}
5932
5933
5934
5935OldSpace* OldSpaces::next() {
5936 switch (counter_++) {
5937 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005938 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005939 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005940 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005941 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005942 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005943 default:
5944 return NULL;
5945 }
5946}
5947
5948
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005949SpaceIterator::SpaceIterator()
5950 : current_space_(FIRST_SPACE),
5951 iterator_(NULL),
5952 size_func_(NULL) {
5953}
5954
5955
5956SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
5957 : current_space_(FIRST_SPACE),
5958 iterator_(NULL),
5959 size_func_(size_func) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005960}
5961
5962
5963SpaceIterator::~SpaceIterator() {
5964 // Delete active iterator if any.
5965 delete iterator_;
5966}
5967
5968
5969bool SpaceIterator::has_next() {
5970 // Iterate until no more spaces.
5971 return current_space_ != LAST_SPACE;
5972}
5973
5974
5975ObjectIterator* SpaceIterator::next() {
5976 if (iterator_ != NULL) {
5977 delete iterator_;
5978 iterator_ = NULL;
5979 // Move to the next space
5980 current_space_++;
5981 if (current_space_ > LAST_SPACE) {
5982 return NULL;
5983 }
5984 }
5985
5986 // Return iterator for the new current space.
5987 return CreateIterator();
5988}
5989
5990
5991// Create an iterator for the space to iterate.
5992ObjectIterator* SpaceIterator::CreateIterator() {
5993 ASSERT(iterator_ == NULL);
5994
5995 switch (current_space_) {
5996 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005997 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005998 break;
5999 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006000 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006001 break;
6002 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006003 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006004 break;
6005 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006006 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006007 break;
6008 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006009 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006010 break;
6011 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006012 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006013 break;
6014 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006015 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006016 break;
6017 }
6018
6019 // Return the newly allocated iterator;
6020 ASSERT(iterator_ != NULL);
6021 return iterator_;
6022}
6023
6024
Ben Murdochb0fe1622011-05-05 13:52:32 +01006025class HeapObjectsFilter {
6026 public:
6027 virtual ~HeapObjectsFilter() {}
6028 virtual bool SkipObject(HeapObject* object) = 0;
6029};
6030
6031
Ben Murdochb0fe1622011-05-05 13:52:32 +01006032class UnreachableObjectsFilter : public HeapObjectsFilter {
6033 public:
6034 UnreachableObjectsFilter() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006035 MarkReachableObjects();
6036 }
6037
6038 ~UnreachableObjectsFilter() {
6039 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006040 }
6041
6042 bool SkipObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006043 MarkBit mark_bit = Marking::MarkBitFrom(object);
6044 return !mark_bit.Get();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006045 }
6046
6047 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006048 class MarkingVisitor : public ObjectVisitor {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006049 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006050 MarkingVisitor() : marking_stack_(10) {}
Ben Murdochb0fe1622011-05-05 13:52:32 +01006051
6052 void VisitPointers(Object** start, Object** end) {
6053 for (Object** p = start; p < end; p++) {
6054 if (!(*p)->IsHeapObject()) continue;
6055 HeapObject* obj = HeapObject::cast(*p);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006056 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6057 if (!mark_bit.Get()) {
6058 mark_bit.Set();
6059 marking_stack_.Add(obj);
Ben Murdochb0fe1622011-05-05 13:52:32 +01006060 }
6061 }
6062 }
6063
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006064 void TransitiveClosure() {
6065 while (!marking_stack_.is_empty()) {
6066 HeapObject* obj = marking_stack_.RemoveLast();
6067 obj->Iterate(this);
6068 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01006069 }
6070
6071 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006072 List<HeapObject*> marking_stack_;
Ben Murdochb0fe1622011-05-05 13:52:32 +01006073 };
6074
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006075 void MarkReachableObjects() {
6076 Heap* heap = Isolate::Current()->heap();
6077 MarkingVisitor visitor;
6078 heap->IterateRoots(&visitor, VISIT_ALL);
6079 visitor.TransitiveClosure();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006080 }
6081
6082 AssertNoAllocation no_alloc;
6083};
6084
6085
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006086HeapIterator::HeapIterator()
6087 : filtering_(HeapIterator::kNoFiltering),
6088 filter_(NULL) {
6089 Init();
6090}
6091
6092
Ben Murdochb0fe1622011-05-05 13:52:32 +01006093HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006094 : filtering_(filtering),
6095 filter_(NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006096 Init();
6097}
6098
6099
6100HeapIterator::~HeapIterator() {
6101 Shutdown();
6102}
6103
6104
6105void HeapIterator::Init() {
6106 // Start the iteration.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006107 space_iterator_ = new SpaceIterator;
Ben Murdochb0fe1622011-05-05 13:52:32 +01006108 switch (filtering_) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006109 case kFilterUnreachable:
6110 filter_ = new UnreachableObjectsFilter;
6111 break;
6112 default:
6113 break;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006114 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006115 object_iterator_ = space_iterator_->next();
6116}
6117
6118
6119void HeapIterator::Shutdown() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006120#ifdef DEBUG
Ben Murdochb0fe1622011-05-05 13:52:32 +01006121 // Assert that in filtering mode we have iterated through all
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006122 // objects. Otherwise, heap will be left in an inconsistent state.
Ben Murdochb0fe1622011-05-05 13:52:32 +01006123 if (filtering_ != kNoFiltering) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006124 ASSERT(object_iterator_ == NULL);
6125 }
6126#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006127 // Make sure the last iterator is deallocated.
6128 delete space_iterator_;
6129 space_iterator_ = NULL;
6130 object_iterator_ = NULL;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006131 delete filter_;
6132 filter_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006133}
6134
6135
Leon Clarked91b9f72010-01-27 17:25:45 +00006136HeapObject* HeapIterator::next() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006137 if (filter_ == NULL) return NextObject();
6138
6139 HeapObject* obj = NextObject();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006140 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006141 return obj;
6142}
6143
6144
6145HeapObject* HeapIterator::NextObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006146 // No iterator means we are done.
Leon Clarked91b9f72010-01-27 17:25:45 +00006147 if (object_iterator_ == NULL) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006148
Leon Clarked91b9f72010-01-27 17:25:45 +00006149 if (HeapObject* obj = object_iterator_->next_object()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006150 // If the current iterator has more objects we are fine.
Leon Clarked91b9f72010-01-27 17:25:45 +00006151 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006152 } else {
6153 // Go though the spaces looking for one that has objects.
6154 while (space_iterator_->has_next()) {
6155 object_iterator_ = space_iterator_->next();
Leon Clarked91b9f72010-01-27 17:25:45 +00006156 if (HeapObject* obj = object_iterator_->next_object()) {
6157 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006158 }
6159 }
6160 }
6161 // Done with the last space.
6162 object_iterator_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00006163 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006164}
6165
6166
6167void HeapIterator::reset() {
6168 // Restart the iterator.
6169 Shutdown();
6170 Init();
6171}
6172
6173
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006174#if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
Steve Blocka7e24c12009-10-30 11:49:00 +00006175
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006176Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00006177
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006178class PathTracer::MarkVisitor: public ObjectVisitor {
Steve Blocka7e24c12009-10-30 11:49:00 +00006179 public:
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006180 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00006181 void VisitPointers(Object** start, Object** end) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006182 // Scan all HeapObject pointers in [start, end)
6183 for (Object** p = start; !tracer_->found() && (p < end); p++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006184 if ((*p)->IsHeapObject())
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006185 tracer_->MarkRecursively(p, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006186 }
6187 }
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006188
6189 private:
6190 PathTracer* tracer_;
Steve Blocka7e24c12009-10-30 11:49:00 +00006191};
6192
Steve Blocka7e24c12009-10-30 11:49:00 +00006193
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006194class PathTracer::UnmarkVisitor: public ObjectVisitor {
6195 public:
6196 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6197 void VisitPointers(Object** start, Object** end) {
6198 // Scan all HeapObject pointers in [start, end)
6199 for (Object** p = start; p < end; p++) {
6200 if ((*p)->IsHeapObject())
6201 tracer_->UnmarkRecursively(p, this);
6202 }
6203 }
6204
6205 private:
6206 PathTracer* tracer_;
6207};
6208
6209
6210void PathTracer::VisitPointers(Object** start, Object** end) {
6211 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6212 // Visit all HeapObject pointers in [start, end)
6213 for (Object** p = start; !done && (p < end); p++) {
6214 if ((*p)->IsHeapObject()) {
6215 TracePathFrom(p);
6216 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6217 }
6218 }
6219}
6220
6221
6222void PathTracer::Reset() {
6223 found_target_ = false;
6224 object_stack_.Clear();
6225}
6226
6227
6228void PathTracer::TracePathFrom(Object** root) {
6229 ASSERT((search_target_ == kAnyGlobalObject) ||
6230 search_target_->IsHeapObject());
6231 found_target_in_trace_ = false;
6232 object_stack_.Clear();
6233
6234 MarkVisitor mark_visitor(this);
6235 MarkRecursively(root, &mark_visitor);
6236
6237 UnmarkVisitor unmark_visitor(this);
6238 UnmarkRecursively(root, &unmark_visitor);
6239
6240 ProcessResults();
6241}
6242
6243
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006244static bool SafeIsGlobalContext(HeapObject* obj) {
6245 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6246}
6247
6248
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006249void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006250 if (!(*p)->IsHeapObject()) return;
6251
6252 HeapObject* obj = HeapObject::cast(*p);
6253
6254 Object* map = obj->map();
6255
6256 if (!map->IsHeapObject()) return; // visited before
6257
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006258 if (found_target_in_trace_) return; // stop if target found
6259 object_stack_.Add(obj);
6260 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6261 (obj == search_target_)) {
6262 found_target_in_trace_ = true;
6263 found_target_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00006264 return;
6265 }
6266
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006267 bool is_global_context = SafeIsGlobalContext(obj);
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006268
Steve Blocka7e24c12009-10-30 11:49:00 +00006269 // not visited yet
6270 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6271
6272 Address map_addr = map_p->address();
6273
Ben Murdochc7cc0282012-03-05 14:35:55 +00006274 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
Steve Blocka7e24c12009-10-30 11:49:00 +00006275
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006276 // Scan the object body.
6277 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6278 // This is specialized to scan Context's properly.
6279 Object** start = reinterpret_cast<Object**>(obj->address() +
6280 Context::kHeaderSize);
6281 Object** end = reinterpret_cast<Object**>(obj->address() +
6282 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6283 mark_visitor->VisitPointers(start, end);
6284 } else {
6285 obj->IterateBody(map_p->instance_type(),
6286 obj->SizeFromMap(map_p),
6287 mark_visitor);
6288 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006289
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006290 // Scan the map after the body because the body is a lot more interesting
6291 // when doing leak detection.
6292 MarkRecursively(&map, mark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006293
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006294 if (!found_target_in_trace_) // don't pop if found the target
6295 object_stack_.RemoveLast();
Steve Blocka7e24c12009-10-30 11:49:00 +00006296}
6297
6298
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006299void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006300 if (!(*p)->IsHeapObject()) return;
6301
6302 HeapObject* obj = HeapObject::cast(*p);
6303
6304 Object* map = obj->map();
6305
6306 if (map->IsHeapObject()) return; // unmarked already
6307
6308 Address map_addr = reinterpret_cast<Address>(map);
6309
6310 map_addr -= kMarkTag;
6311
6312 ASSERT_TAG_ALIGNED(map_addr);
6313
6314 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6315
Ben Murdochc7cc0282012-03-05 14:35:55 +00006316 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
Steve Blocka7e24c12009-10-30 11:49:00 +00006317
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006318 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006319
6320 obj->IterateBody(Map::cast(map_p)->instance_type(),
6321 obj->SizeFromMap(Map::cast(map_p)),
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006322 unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006323}
6324
6325
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006326void PathTracer::ProcessResults() {
6327 if (found_target_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006328 PrintF("=====================================\n");
6329 PrintF("==== Path to object ====\n");
6330 PrintF("=====================================\n\n");
6331
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006332 ASSERT(!object_stack_.is_empty());
6333 for (int i = 0; i < object_stack_.length(); i++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006334 if (i > 0) PrintF("\n |\n |\n V\n\n");
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006335 Object* obj = object_stack_[i];
6336#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00006337 obj->Print();
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006338#else
6339 obj->ShortPrint();
6340#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006341 }
6342 PrintF("=====================================\n");
6343 }
6344}
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006345#endif // DEBUG || LIVE_OBJECT_LIST
Steve Blocka7e24c12009-10-30 11:49:00 +00006346
6347
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006348#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00006349// Triggers a depth-first traversal of reachable objects from roots
6350// and finds a path to a specific heap object and prints it.
Leon Clarkee46be812010-01-19 14:06:41 +00006351void Heap::TracePathToObject(Object* target) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006352 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6353 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006354}
6355
6356
6357// Triggers a depth-first traversal of reachable objects from roots
6358// and finds a path to any global object and prints it. Useful for
6359// determining the source for leaks of global objects.
6360void Heap::TracePathToGlobal() {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006361 PathTracer tracer(PathTracer::kAnyGlobalObject,
6362 PathTracer::FIND_ALL,
6363 VISIT_ALL);
6364 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006365}
6366#endif
6367
6368
Ben Murdochf87a2032010-10-22 12:50:53 +01006369static intptr_t CountTotalHolesSize() {
6370 intptr_t holes_size = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +01006371 OldSpaces spaces;
6372 for (OldSpace* space = spaces.next();
6373 space != NULL;
6374 space = spaces.next()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006375 holes_size += space->Waste() + space->Available();
Leon Clarkef7060e22010-06-03 12:02:55 +01006376 }
6377 return holes_size;
6378}
6379
6380
Steve Block44f0eee2011-05-26 01:26:41 +01006381GCTracer::GCTracer(Heap* heap)
Steve Blocka7e24c12009-10-30 11:49:00 +00006382 : start_time_(0.0),
Leon Clarkef7060e22010-06-03 12:02:55 +01006383 start_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +00006384 gc_count_(0),
6385 full_gc_count_(0),
Leon Clarkef7060e22010-06-03 12:02:55 +01006386 allocated_since_last_gc_(0),
6387 spent_in_mutator_(0),
Steve Block44f0eee2011-05-26 01:26:41 +01006388 promoted_objects_size_(0),
6389 heap_(heap) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006390 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00006391 start_time_ = OS::TimeCurrentMillis();
Steve Block44f0eee2011-05-26 01:26:41 +01006392 start_size_ = heap_->SizeOfObjects();
Leon Clarkef7060e22010-06-03 12:02:55 +01006393
6394 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6395 scopes_[i] = 0;
6396 }
6397
6398 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6399
Steve Block44f0eee2011-05-26 01:26:41 +01006400 allocated_since_last_gc_ =
6401 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
Leon Clarkef7060e22010-06-03 12:02:55 +01006402
Steve Block44f0eee2011-05-26 01:26:41 +01006403 if (heap_->last_gc_end_timestamp_ > 0) {
6404 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006405 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006406
6407 steps_count_ = heap_->incremental_marking()->steps_count();
6408 steps_took_ = heap_->incremental_marking()->steps_took();
6409 longest_step_ = heap_->incremental_marking()->longest_step();
6410 steps_count_since_last_gc_ =
6411 heap_->incremental_marking()->steps_count_since_last_gc();
6412 steps_took_since_last_gc_ =
6413 heap_->incremental_marking()->steps_took_since_last_gc();
Steve Blocka7e24c12009-10-30 11:49:00 +00006414}
6415
6416
6417GCTracer::~GCTracer() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006418 // Printf ONE line iff flag is set.
Leon Clarkef7060e22010-06-03 12:02:55 +01006419 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6420
Steve Block44f0eee2011-05-26 01:26:41 +01006421 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006422
Steve Block44f0eee2011-05-26 01:26:41 +01006423 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6424 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
Leon Clarkef7060e22010-06-03 12:02:55 +01006425
Steve Block44f0eee2011-05-26 01:26:41 +01006426 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006427
6428 // Update cumulative GC statistics if required.
6429 if (FLAG_print_cumulative_gc_stat) {
Steve Block44f0eee2011-05-26 01:26:41 +01006430 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6431 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6432 heap_->alive_after_last_gc_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006433 if (!first_gc) {
Steve Block44f0eee2011-05-26 01:26:41 +01006434 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6435 static_cast<int>(spent_in_mutator_));
Leon Clarkef7060e22010-06-03 12:02:55 +01006436 }
6437 }
6438
6439 if (!FLAG_trace_gc_nvp) {
6440 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6441
6442 PrintF("%s %.1f -> %.1f MB, ",
6443 CollectorString(),
6444 static_cast<double>(start_size_) / MB,
6445 SizeOfHeapObjects());
6446
6447 if (external_time > 0) PrintF("%d / ", external_time);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006448 PrintF("%d ms", time);
6449 if (steps_count_ > 0) {
6450 if (collector_ == SCAVENGER) {
6451 PrintF(" (+ %d ms in %d steps since last GC)",
6452 static_cast<int>(steps_took_since_last_gc_),
6453 steps_count_since_last_gc_);
6454 } else {
6455 PrintF(" (+ %d ms in %d steps since start of marking, "
6456 "biggest step %f ms)",
6457 static_cast<int>(steps_took_),
6458 steps_count_,
6459 longest_step_);
6460 }
6461 }
6462 PrintF(".\n");
Leon Clarkef7060e22010-06-03 12:02:55 +01006463 } else {
6464 PrintF("pause=%d ", time);
6465 PrintF("mutator=%d ",
6466 static_cast<int>(spent_in_mutator_));
6467
6468 PrintF("gc=");
6469 switch (collector_) {
6470 case SCAVENGER:
6471 PrintF("s");
6472 break;
6473 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006474 PrintF("ms");
Leon Clarkef7060e22010-06-03 12:02:55 +01006475 break;
6476 default:
6477 UNREACHABLE();
6478 }
6479 PrintF(" ");
6480
6481 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6482 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6483 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
Iain Merrick75681382010-08-19 15:07:18 +01006484 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006485 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6486 PrintF("new_new=%d ",
6487 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6488 PrintF("root_new=%d ",
6489 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6490 PrintF("old_new=%d ",
6491 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6492 PrintF("compaction_ptrs=%d ",
6493 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6494 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6495 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6496 PrintF("misc_compaction=%d ",
6497 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
Leon Clarkef7060e22010-06-03 12:02:55 +01006498
Ben Murdochf87a2032010-10-22 12:50:53 +01006499 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_size_);
Steve Block44f0eee2011-05-26 01:26:41 +01006500 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
Ben Murdochf87a2032010-10-22 12:50:53 +01006501 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6502 in_free_list_or_wasted_before_gc_);
6503 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
Leon Clarkef7060e22010-06-03 12:02:55 +01006504
Ben Murdochf87a2032010-10-22 12:50:53 +01006505 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6506 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006507
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006508 if (collector_ == SCAVENGER) {
6509 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6510 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6511 } else {
6512 PrintF("stepscount=%d ", steps_count_);
6513 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6514 }
6515
Leon Clarkef7060e22010-06-03 12:02:55 +01006516 PrintF("\n");
6517 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006518
Steve Block44f0eee2011-05-26 01:26:41 +01006519 heap_->PrintShortHeapStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00006520}
6521
6522
6523const char* GCTracer::CollectorString() {
6524 switch (collector_) {
6525 case SCAVENGER:
6526 return "Scavenge";
6527 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006528 return "Mark-sweep";
Steve Blocka7e24c12009-10-30 11:49:00 +00006529 }
6530 return "Unknown GC";
6531}
6532
6533
6534int KeyedLookupCache::Hash(Map* map, String* name) {
6535 // Uses only lower 32 bits if pointers are larger.
6536 uintptr_t addr_hash =
Leon Clarkee46be812010-01-19 14:06:41 +00006537 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
Andrei Popescu402d9372010-02-26 13:31:12 +00006538 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
Steve Blocka7e24c12009-10-30 11:49:00 +00006539}
6540
6541
6542int KeyedLookupCache::Lookup(Map* map, String* name) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00006543 int index = (Hash(map, name) & kHashMask);
6544 for (int i = 0; i < kEntriesPerBucket; i++) {
6545 Key& key = keys_[index + i];
6546 if ((key.map == map) && key.name->Equals(name)) {
6547 return field_offsets_[index + i];
6548 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006549 }
Steve Block44f0eee2011-05-26 01:26:41 +01006550 return kNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00006551}
6552
6553
6554void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6555 String* symbol;
Steve Block44f0eee2011-05-26 01:26:41 +01006556 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00006557 int index = (Hash(map, symbol) & kHashMask);
6558 // After a GC there will be free slots, so we use them in order (this may
6559 // help to get the most frequently used one in position 0).
6560 for (int i = 0; i< kEntriesPerBucket; i++) {
6561 Key& key = keys_[index];
6562 Object* free_entry_indicator = NULL;
6563 if (key.map == free_entry_indicator) {
6564 key.map = map;
6565 key.name = symbol;
6566 field_offsets_[index + i] = field_offset;
6567 return;
6568 }
6569 }
6570 // No free entry found in this bucket, so we move them all down one and
6571 // put the new entry at position zero.
6572 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6573 Key& key = keys_[index + i];
6574 Key& key2 = keys_[index + i - 1];
6575 key = key2;
6576 field_offsets_[index + i] = field_offsets_[index + i - 1];
6577 }
6578
6579 // Write the new first entry.
Steve Blocka7e24c12009-10-30 11:49:00 +00006580 Key& key = keys_[index];
6581 key.map = map;
6582 key.name = symbol;
6583 field_offsets_[index] = field_offset;
6584 }
6585}
6586
6587
6588void KeyedLookupCache::Clear() {
6589 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6590}
6591
6592
Steve Blocka7e24c12009-10-30 11:49:00 +00006593void DescriptorLookupCache::Clear() {
6594 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6595}
6596
6597
Steve Blocka7e24c12009-10-30 11:49:00 +00006598#ifdef DEBUG
Ben Murdochf87a2032010-10-22 12:50:53 +01006599void Heap::GarbageCollectionGreedyCheck() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006600 ASSERT(FLAG_gc_greedy);
Steve Block44f0eee2011-05-26 01:26:41 +01006601 if (isolate_->bootstrapper()->IsActive()) return;
Ben Murdochf87a2032010-10-22 12:50:53 +01006602 if (disallow_allocation_failure()) return;
6603 CollectGarbage(NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00006604}
6605#endif
6606
6607
Steve Block44f0eee2011-05-26 01:26:41 +01006608TranscendentalCache::SubCache::SubCache(Type t)
6609 : type_(t),
6610 isolate_(Isolate::Current()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006611 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6612 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6613 for (int i = 0; i < kCacheSize; i++) {
6614 elements_[i].in[0] = in0;
6615 elements_[i].in[1] = in1;
6616 elements_[i].output = NULL;
6617 }
6618}
6619
6620
Steve Blocka7e24c12009-10-30 11:49:00 +00006621void TranscendentalCache::Clear() {
6622 for (int i = 0; i < kNumberOfCaches; i++) {
6623 if (caches_[i] != NULL) {
6624 delete caches_[i];
6625 caches_[i] = NULL;
6626 }
6627 }
6628}
6629
6630
Leon Clarkee46be812010-01-19 14:06:41 +00006631void ExternalStringTable::CleanUp() {
6632 int last = 0;
6633 for (int i = 0; i < new_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006634 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6635 continue;
6636 }
Steve Block44f0eee2011-05-26 01:26:41 +01006637 if (heap_->InNewSpace(new_space_strings_[i])) {
Leon Clarkee46be812010-01-19 14:06:41 +00006638 new_space_strings_[last++] = new_space_strings_[i];
6639 } else {
6640 old_space_strings_.Add(new_space_strings_[i]);
6641 }
6642 }
6643 new_space_strings_.Rewind(last);
6644 last = 0;
6645 for (int i = 0; i < old_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006646 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6647 continue;
6648 }
Steve Block44f0eee2011-05-26 01:26:41 +01006649 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
Leon Clarkee46be812010-01-19 14:06:41 +00006650 old_space_strings_[last++] = old_space_strings_[i];
6651 }
6652 old_space_strings_.Rewind(last);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006653 if (FLAG_verify_heap) {
6654 Verify();
6655 }
Leon Clarkee46be812010-01-19 14:06:41 +00006656}
6657
6658
6659void ExternalStringTable::TearDown() {
6660 new_space_strings_.Free();
6661 old_space_strings_.Free();
6662}
6663
6664
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006665void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6666 chunk->set_next_chunk(chunks_queued_for_free_);
6667 chunks_queued_for_free_ = chunk;
6668}
6669
6670
6671void Heap::FreeQueuedChunks() {
6672 if (chunks_queued_for_free_ == NULL) return;
6673 MemoryChunk* next;
6674 MemoryChunk* chunk;
6675 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6676 next = chunk->next_chunk();
6677 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6678
6679 if (chunk->owner()->identity() == LO_SPACE) {
6680 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6681 // If FromAnyPointerAddress encounters a slot that belongs to a large
6682 // chunk queued for deletion it will fail to find the chunk because
6683 // it try to perform a search in the list of pages owned by of the large
6684 // object space and queued chunks were detached from that list.
6685 // To work around this we split large chunk into normal kPageSize aligned
6686 // pieces and initialize size, owner and flags field of every piece.
6687 // If FromAnyPointerAddress encounters a slot that belongs to one of
6688 // these smaller pieces it will treat it as a slot on a normal Page.
6689 MemoryChunk* inner = MemoryChunk::FromAddress(
6690 chunk->address() + Page::kPageSize);
6691 MemoryChunk* inner_last = MemoryChunk::FromAddress(
6692 chunk->address() + chunk->size() - 1);
6693 while (inner <= inner_last) {
6694 // Size of a large chunk is always a multiple of
6695 // OS::AllocateAlignment() so there is always
6696 // enough space for a fake MemoryChunk header.
6697 inner->set_size(Page::kPageSize);
6698 inner->set_owner(lo_space());
6699 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6700 inner = MemoryChunk::FromAddress(
6701 inner->address() + Page::kPageSize);
6702 }
6703 }
6704 }
6705 isolate_->heap()->store_buffer()->Compact();
6706 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6707 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6708 next = chunk->next_chunk();
6709 isolate_->memory_allocator()->Free(chunk);
6710 }
6711 chunks_queued_for_free_ = NULL;
6712}
6713
Steve Blocka7e24c12009-10-30 11:49:00 +00006714} } // namespace v8::internal