blob: a1cccf6f22ac4fa1bf9bdea95b7fc88facd99909 [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
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +010063static LazyMutex gc_initializer_mutex = LAZY_MUTEX_INITIALIZER;
Steve Blocka7e24c12009-10-30 11:49:00 +000064
Steve Blocka7e24c12009-10-30 11:49:00 +000065
Steve Block44f0eee2011-05-26 01:26:41 +010066Heap::Heap()
67 : isolate_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +000068// semispace_size_ should be a power of 2 and old_generation_size_ should be
69// a multiple of Page::kPageSize.
Ben Murdoch589d6972011-11-30 16:04:58 +000070#if defined(ANDROID)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000071#define LUMP_OF_MEMORY (128 * KB)
Steve Block44f0eee2011-05-26 01:26:41 +010072 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000073#elif defined(V8_TARGET_ARCH_X64)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000074#define LUMP_OF_MEMORY (2 * MB)
Steve Block44f0eee2011-05-26 01:26:41 +010075 code_range_size_(512*MB),
Steve Blocka7e24c12009-10-30 11:49:00 +000076#else
Ben Murdoch592a9fc2012-03-05 11:04:45 +000077#define LUMP_OF_MEMORY MB
Steve Block44f0eee2011-05-26 01:26:41 +010078 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000079#endif
Ben Murdoch592a9fc2012-03-05 11:04:45 +000080 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
81 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
Ben Murdochc7cc0282012-03-05 14:35:55 +000082 initial_semispace_size_(Page::kPageSize),
Ben Murdoch592a9fc2012-03-05 11:04:45 +000083 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +010084 max_executable_size_(256l * LUMP_OF_MEMORY),
Ben Murdoch592a9fc2012-03-05 11:04:45 +000085
Steve Blocka7e24c12009-10-30 11:49:00 +000086// Variables set based on semispace_size_ and old_generation_size_ in
Steve Block44f0eee2011-05-26 01:26:41 +010087// ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
Steve Block3ce2e202009-11-05 08:53:23 +000088// Will be 4 * reserved_semispace_size_ to ensure that young
89// generation can be aligned to its size.
Steve Block44f0eee2011-05-26 01:26:41 +010090 survived_since_last_expansion_(0),
Ben Murdoch257744e2011-11-30 15:57:28 +000091 sweep_generation_(0),
Steve Block44f0eee2011-05-26 01:26:41 +010092 always_allocate_scope_depth_(0),
93 linear_allocation_scope_depth_(0),
94 contexts_disposed_(0),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +010095 global_ic_age_(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),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100108 remembered_unmapped_pages_index_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100109 unflattened_strings_length_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000110#ifdef DEBUG
Steve Block44f0eee2011-05-26 01:26:41 +0100111 allocation_allowed_(true),
112 allocation_timeout_(0),
113 disallow_allocation_failure_(false),
114 debug_utils_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +0000115#endif // DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000116 new_space_high_promotion_mode_active_(false),
Steve Block44f0eee2011-05-26 01:26:41 +0100117 old_gen_promotion_limit_(kMinimumPromotionLimit),
118 old_gen_allocation_limit_(kMinimumAllocationLimit),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000119 old_gen_limit_factor_(1),
120 size_of_old_gen_at_last_old_space_gc_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100121 external_allocation_limit_(0),
122 amount_of_external_allocated_memory_(0),
123 amount_of_external_allocated_memory_at_last_global_gc_(0),
124 old_gen_exhausted_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000125 store_buffer_rebuilder_(store_buffer()),
Steve Block44f0eee2011-05-26 01:26:41 +0100126 hidden_symbol_(NULL),
127 global_gc_prologue_callback_(NULL),
128 global_gc_epilogue_callback_(NULL),
129 gc_safe_size_of_old_object_(NULL),
Steve Block053d10c2011-06-13 19:13:29 +0100130 total_regexp_code_generated_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100131 tracer_(NULL),
132 young_survivors_after_last_gc_(0),
133 high_survival_rate_period_length_(0),
134 survival_rate_(0),
135 previous_survival_rate_trend_(Heap::STABLE),
136 survival_rate_trend_(Heap::STABLE),
137 max_gc_pause_(0),
138 max_alive_after_gc_(0),
139 min_in_mutator_(kMaxInt),
140 alive_after_last_gc_(0),
141 last_gc_end_timestamp_(0.0),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000142 store_buffer_(this),
143 marking_(this),
144 incremental_marking_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100145 number_idle_notifications_(0),
146 last_idle_notification_gc_count_(0),
147 last_idle_notification_gc_count_init_(false),
Ben Murdochc7cc0282012-03-05 14:35:55 +0000148 idle_notification_will_schedule_next_gc_(false),
149 mark_sweeps_since_idle_round_started_(0),
150 ms_count_at_last_idle_notification_(0),
151 gc_count_at_last_idle_gc_(0),
152 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000153 promotion_queue_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100154 configured_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000155 chunks_queued_for_free_(NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +0100156 // Allow build-time customization of the max semispace size. Building
157 // V8 with snapshots and a non-default max semispace size is much
158 // easier if you can define it as part of the build environment.
159#if defined(V8_MAX_SEMISPACE_SIZE)
160 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
161#endif
Steve Blocka7e24c12009-10-30 11:49:00 +0000162
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000163 intptr_t max_virtual = OS::MaxVirtualMemory();
164
165 if (max_virtual > 0) {
166 if (code_range_size_ > 0) {
167 // Reserve no more than 1/8 of the memory for the code range.
168 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
169 }
170 }
171
Steve Block44f0eee2011-05-26 01:26:41 +0100172 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
173 global_contexts_list_ = NULL;
174 mark_compact_collector_.heap_ = this;
175 external_string_table_.heap_ = this;
176}
177
Steve Blocka7e24c12009-10-30 11:49:00 +0000178
Ben Murdochf87a2032010-10-22 12:50:53 +0100179intptr_t Heap::Capacity() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000180 if (!HasBeenSetUp()) return 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000181
182 return new_space_.Capacity() +
183 old_pointer_space_->Capacity() +
184 old_data_space_->Capacity() +
185 code_space_->Capacity() +
186 map_space_->Capacity() +
187 cell_space_->Capacity();
188}
189
190
Ben Murdochf87a2032010-10-22 12:50:53 +0100191intptr_t Heap::CommittedMemory() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000192 if (!HasBeenSetUp()) return 0;
Steve Block3ce2e202009-11-05 08:53:23 +0000193
194 return new_space_.CommittedMemory() +
195 old_pointer_space_->CommittedMemory() +
196 old_data_space_->CommittedMemory() +
197 code_space_->CommittedMemory() +
198 map_space_->CommittedMemory() +
199 cell_space_->CommittedMemory() +
200 lo_space_->Size();
201}
202
Russell Brenner90bac252010-11-18 13:33:46 -0800203intptr_t Heap::CommittedMemoryExecutable() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000204 if (!HasBeenSetUp()) return 0;
Russell Brenner90bac252010-11-18 13:33:46 -0800205
Steve Block44f0eee2011-05-26 01:26:41 +0100206 return isolate()->memory_allocator()->SizeExecutable();
Russell Brenner90bac252010-11-18 13:33:46 -0800207}
208
Steve Block3ce2e202009-11-05 08:53:23 +0000209
Ben Murdochf87a2032010-10-22 12:50:53 +0100210intptr_t Heap::Available() {
Ben Murdochc7cc0282012-03-05 14:35:55 +0000211 if (!HasBeenSetUp()) return 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000212
213 return new_space_.Available() +
214 old_pointer_space_->Available() +
215 old_data_space_->Available() +
216 code_space_->Available() +
217 map_space_->Available() +
218 cell_space_->Available();
219}
220
221
Ben Murdochc7cc0282012-03-05 14:35:55 +0000222bool Heap::HasBeenSetUp() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000223 return old_pointer_space_ != NULL &&
224 old_data_space_ != NULL &&
225 code_space_ != NULL &&
226 map_space_ != NULL &&
227 cell_space_ != NULL &&
228 lo_space_ != NULL;
229}
230
231
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100232int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000233 if (IntrusiveMarking::IsMarked(object)) {
234 return IntrusiveMarking::SizeOfMarkedObject(object);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100235 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000236 return object->SizeFromMap(object->map());
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100237}
238
239
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100240GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
241 const char** reason) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000242 // Is global GC requested?
243 if (space != NEW_SPACE || FLAG_gc_global) {
Steve Block44f0eee2011-05-26 01:26:41 +0100244 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100245 *reason = "GC in old space requested";
Steve Blocka7e24c12009-10-30 11:49:00 +0000246 return MARK_COMPACTOR;
247 }
248
249 // Is enough data promoted to justify a global GC?
250 if (OldGenerationPromotionLimitReached()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100251 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100252 *reason = "promotion limit reached";
Steve Blocka7e24c12009-10-30 11:49:00 +0000253 return MARK_COMPACTOR;
254 }
255
256 // Have allocation in OLD and LO failed?
257 if (old_gen_exhausted_) {
Steve Block44f0eee2011-05-26 01:26:41 +0100258 isolate_->counters()->
259 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100260 *reason = "old generations exhausted";
Steve Blocka7e24c12009-10-30 11:49:00 +0000261 return MARK_COMPACTOR;
262 }
263
264 // Is there enough space left in OLD to guarantee that a scavenge can
265 // succeed?
266 //
267 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
268 // for object promotion. It counts only the bytes that the memory
269 // allocator has not yet allocated from the OS and assigned to any space,
270 // and does not count available bytes already in the old space or code
271 // space. Undercounting is safe---we may get an unrequested full GC when
272 // a scavenge would have succeeded.
Steve Block44f0eee2011-05-26 01:26:41 +0100273 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
274 isolate_->counters()->
275 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100276 *reason = "scavenge might not succeed";
Steve Blocka7e24c12009-10-30 11:49:00 +0000277 return MARK_COMPACTOR;
278 }
279
280 // Default
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100281 *reason = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000282 return SCAVENGER;
283}
284
285
286// TODO(1238405): Combine the infrastructure for --heap-stats and
287// --log-gc to avoid the complicated preprocessor and flag testing.
Steve Blocka7e24c12009-10-30 11:49:00 +0000288void Heap::ReportStatisticsBeforeGC() {
289 // Heap::ReportHeapStatistics will also log NewSpace statistics when
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000290 // compiled --log-gc is set. The following logic is used to avoid
291 // double logging.
292#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000293 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
294 if (FLAG_heap_stats) {
295 ReportHeapStatistics("Before GC");
296 } else if (FLAG_log_gc) {
297 new_space_.ReportStatistics();
298 }
299 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000300#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000301 if (FLAG_log_gc) {
302 new_space_.CollectStatistics();
303 new_space_.ReportStatistics();
304 new_space_.ClearHistograms();
305 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000306#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000307}
308
309
Steve Blocka7e24c12009-10-30 11:49:00 +0000310void Heap::PrintShortHeapStatistics() {
311 if (!FLAG_trace_gc_verbose) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100312 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
313 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block44f0eee2011-05-26 01:26:41 +0100314 isolate_->memory_allocator()->Size(),
315 isolate_->memory_allocator()->Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100316 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
317 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000318 Heap::new_space_.Size(),
319 new_space_.Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100320 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
321 ", available: %8" V8_PTR_PREFIX "d"
322 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000323 old_pointer_space_->Size(),
324 old_pointer_space_->Available(),
325 old_pointer_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100326 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
327 ", available: %8" V8_PTR_PREFIX "d"
328 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000329 old_data_space_->Size(),
330 old_data_space_->Available(),
331 old_data_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100332 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
333 ", available: %8" V8_PTR_PREFIX "d"
334 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000335 code_space_->Size(),
336 code_space_->Available(),
337 code_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100338 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
339 ", available: %8" V8_PTR_PREFIX "d"
340 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000341 map_space_->Size(),
342 map_space_->Available(),
343 map_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100344 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
345 ", available: %8" V8_PTR_PREFIX "d"
346 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000347 cell_space_->Size(),
348 cell_space_->Available(),
349 cell_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100350 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
351 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000352 lo_space_->Size(),
353 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000354}
Steve Blocka7e24c12009-10-30 11:49:00 +0000355
356
357// TODO(1238405): Combine the infrastructure for --heap-stats and
358// --log-gc to avoid the complicated preprocessor and flag testing.
359void Heap::ReportStatisticsAfterGC() {
360 // Similar to the before GC, we use some complicated logic to ensure that
361 // NewSpace statistics are logged exactly once when --log-gc is turned on.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000362#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000363 if (FLAG_heap_stats) {
364 new_space_.CollectStatistics();
365 ReportHeapStatistics("After GC");
366 } else if (FLAG_log_gc) {
367 new_space_.ReportStatistics();
368 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000369#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000370 if (FLAG_log_gc) new_space_.ReportStatistics();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000371#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000372}
Steve Blocka7e24c12009-10-30 11:49:00 +0000373
374
375void Heap::GarbageCollectionPrologue() {
Steve Block44f0eee2011-05-26 01:26:41 +0100376 isolate_->transcendental_cache()->Clear();
Steve Block6ded16b2010-05-10 14:33:55 +0100377 ClearJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 gc_count_++;
Steve Block6ded16b2010-05-10 14:33:55 +0100379 unflattened_strings_length_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000380#ifdef DEBUG
381 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
382 allow_allocation(false);
383
384 if (FLAG_verify_heap) {
385 Verify();
386 }
387
388 if (FLAG_gc_verbose) Print();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000389#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000390
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000391#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 ReportStatisticsBeforeGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000393#endif // DEBUG
Steve Block1e0659c2011-05-24 12:43:12 +0100394
395 LiveObjectList::GCPrologue();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000396 store_buffer()->GCPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000397}
398
Ben Murdochf87a2032010-10-22 12:50:53 +0100399intptr_t Heap::SizeOfObjects() {
400 intptr_t total = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000401 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +0000402 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800403 total += space->SizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 }
405 return total;
406}
407
408void Heap::GarbageCollectionEpilogue() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000409 store_buffer()->GCEpilogue();
Steve Block1e0659c2011-05-24 12:43:12 +0100410 LiveObjectList::GCEpilogue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000411#ifdef DEBUG
412 allow_allocation(true);
413 ZapFromSpace();
414
415 if (FLAG_verify_heap) {
416 Verify();
417 }
418
Steve Block44f0eee2011-05-26 01:26:41 +0100419 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 if (FLAG_print_handles) PrintHandles();
421 if (FLAG_gc_verbose) Print();
422 if (FLAG_code_stats) ReportCodeStatistics("After GC");
423#endif
424
Steve Block44f0eee2011-05-26 01:26:41 +0100425 isolate_->counters()->alive_after_last_gc()->Set(
426 static_cast<int>(SizeOfObjects()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000427
Steve Block44f0eee2011-05-26 01:26:41 +0100428 isolate_->counters()->symbol_table_capacity()->Set(
429 symbol_table()->Capacity());
430 isolate_->counters()->number_of_symbols()->Set(
431 symbol_table()->NumberOfElements());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000432#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000433 ReportStatisticsAfterGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000434#endif // DEBUG
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000435#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +0100436 isolate_->debug()->AfterGarbageCollection();
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000437#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +0000438}
439
440
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100441void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000442 // Since we are ignoring the return value, the exact choice of space does
443 // not matter, so long as we do not specify NEW_SPACE, which would not
444 // cause a full GC.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000445 mark_compact_collector_.SetFlags(flags);
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100446 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000447 mark_compact_collector_.SetFlags(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000448}
449
450
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100451void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800452 // Since we are ignoring the return value, the exact choice of space does
453 // not matter, so long as we do not specify NEW_SPACE, which would not
454 // cause a full GC.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800455 // Major GC would invoke weak handle callbacks on weakly reachable
456 // handles, but won't collect weakly reachable objects until next
457 // major GC. Therefore if we collect aggressively and weak handle callback
458 // has been invoked, we rerun major GC to release objects which become
459 // garbage.
460 // Note: as weak callbacks can execute arbitrary code, we cannot
461 // hope that eventually there will be no weak callbacks invocations.
462 // Therefore stop recollecting after several attempts.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100463 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
464 kReduceMemoryFootprintMask);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000465 isolate_->compilation_cache()->Clear();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800466 const int kMaxNumberOfAttempts = 7;
467 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100468 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800469 break;
470 }
471 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000472 mark_compact_collector()->SetFlags(kNoGCFlags);
473 new_space_.Shrink();
Ben Murdochc7cc0282012-03-05 14:35:55 +0000474 UncommitFromSpace();
475 Shrink();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000476 incremental_marking()->UncommitMarkingDeque();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800477}
478
479
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100480bool Heap::CollectGarbage(AllocationSpace space,
481 GarbageCollector collector,
482 const char* gc_reason,
483 const char* collector_reason) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000484 // The VM is in the GC state until exiting this function.
Steve Block44f0eee2011-05-26 01:26:41 +0100485 VMState state(isolate_, GC);
Steve Blocka7e24c12009-10-30 11:49:00 +0000486
487#ifdef DEBUG
488 // Reset the allocation timeout to the GC interval, but make sure to
489 // allow at least a few allocations after a collection. The reason
490 // for this is that we have a lot of allocation sequences and we
491 // assume that a garbage collection will allow the subsequent
492 // allocation attempts to go through.
493 allocation_timeout_ = Max(6, FLAG_gc_interval);
494#endif
495
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000496 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
497 if (FLAG_trace_incremental_marking) {
498 PrintF("[IncrementalMarking] Scavenge during marking.\n");
499 }
500 }
501
502 if (collector == MARK_COMPACTOR &&
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100503 !mark_compact_collector()->abort_incremental_marking_ &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000504 !incremental_marking()->IsStopped() &&
505 !incremental_marking()->should_hurry() &&
506 FLAG_incremental_marking_steps) {
507 if (FLAG_trace_incremental_marking) {
508 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
509 }
510 collector = SCAVENGER;
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100511 collector_reason = "incremental marking delaying mark-sweep";
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000512 }
513
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800514 bool next_gc_likely_to_collect_more = false;
515
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100516 { GCTracer tracer(this, gc_reason, collector_reason);
Steve Blocka7e24c12009-10-30 11:49:00 +0000517 GarbageCollectionPrologue();
518 // The GC count was incremented in the prologue. Tell the tracer about
519 // it.
520 tracer.set_gc_count(gc_count_);
521
Steve Blocka7e24c12009-10-30 11:49:00 +0000522 // Tell the tracer which collector we've selected.
523 tracer.set_collector(collector);
524
525 HistogramTimer* rate = (collector == SCAVENGER)
Steve Block44f0eee2011-05-26 01:26:41 +0100526 ? isolate_->counters()->gc_scavenger()
527 : isolate_->counters()->gc_compactor();
Steve Blocka7e24c12009-10-30 11:49:00 +0000528 rate->Start();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800529 next_gc_likely_to_collect_more =
530 PerformGarbageCollection(collector, &tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000531 rate->Stop();
532
533 GarbageCollectionEpilogue();
534 }
535
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000536 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
537 if (incremental_marking()->IsStopped()) {
538 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
539 incremental_marking()->Start();
540 }
541 }
542
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800543 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000544}
545
546
547void Heap::PerformScavenge() {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100548 GCTracer tracer(this, NULL, NULL);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000549 if (incremental_marking()->IsStopped()) {
550 PerformGarbageCollection(SCAVENGER, &tracer);
551 } else {
552 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
553 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000554}
555
556
557#ifdef DEBUG
558// Helper class for verifying the symbol table.
559class SymbolTableVerifier : public ObjectVisitor {
560 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000561 void VisitPointers(Object** start, Object** end) {
562 // Visit all HeapObject pointers in [start, end).
563 for (Object** p = start; p < end; p++) {
564 if ((*p)->IsHeapObject()) {
565 // Check that the symbol is actually a symbol.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000566 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
Steve Blocka7e24c12009-10-30 11:49:00 +0000567 }
568 }
569 }
570};
571#endif // DEBUG
572
573
574static void VerifySymbolTable() {
575#ifdef DEBUG
576 SymbolTableVerifier verifier;
Steve Block44f0eee2011-05-26 01:26:41 +0100577 HEAP->symbol_table()->IterateElements(&verifier);
Steve Blocka7e24c12009-10-30 11:49:00 +0000578#endif // DEBUG
579}
580
581
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100582static bool AbortIncrementalMarkingAndCollectGarbage(
583 Heap* heap,
584 AllocationSpace space,
585 const char* gc_reason = NULL) {
586 heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
587 bool result = heap->CollectGarbage(space, gc_reason);
588 heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
589 return result;
590}
591
592
Leon Clarkee46be812010-01-19 14:06:41 +0000593void Heap::ReserveSpace(
594 int new_space_size,
595 int pointer_space_size,
596 int data_space_size,
597 int code_space_size,
598 int map_space_size,
599 int cell_space_size,
600 int large_object_size) {
601 NewSpace* new_space = Heap::new_space();
602 PagedSpace* old_pointer_space = Heap::old_pointer_space();
603 PagedSpace* old_data_space = Heap::old_data_space();
604 PagedSpace* code_space = Heap::code_space();
605 PagedSpace* map_space = Heap::map_space();
606 PagedSpace* cell_space = Heap::cell_space();
607 LargeObjectSpace* lo_space = Heap::lo_space();
608 bool gc_performed = true;
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000609 int counter = 0;
610 static const int kThreshold = 20;
611 while (gc_performed && counter++ < kThreshold) {
Leon Clarkee46be812010-01-19 14:06:41 +0000612 gc_performed = false;
613 if (!new_space->ReserveSpace(new_space_size)) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100614 Heap::CollectGarbage(NEW_SPACE,
615 "failed to reserve space in the new space");
Leon Clarkee46be812010-01-19 14:06:41 +0000616 gc_performed = true;
617 }
618 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100619 AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
620 "failed to reserve space in the old pointer space");
Leon Clarkee46be812010-01-19 14:06:41 +0000621 gc_performed = true;
622 }
623 if (!(old_data_space->ReserveSpace(data_space_size))) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100624 AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
625 "failed to reserve space in the old data space");
Leon Clarkee46be812010-01-19 14:06:41 +0000626 gc_performed = true;
627 }
628 if (!(code_space->ReserveSpace(code_space_size))) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100629 AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
630 "failed to reserve space in the code space");
Leon Clarkee46be812010-01-19 14:06:41 +0000631 gc_performed = true;
632 }
633 if (!(map_space->ReserveSpace(map_space_size))) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100634 AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
635 "failed to reserve space in the map space");
Leon Clarkee46be812010-01-19 14:06:41 +0000636 gc_performed = true;
637 }
638 if (!(cell_space->ReserveSpace(cell_space_size))) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100639 AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
640 "failed to reserve space in the cell space");
Leon Clarkee46be812010-01-19 14:06:41 +0000641 gc_performed = true;
642 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100643 // We add a slack-factor of 2 in order to have space for a series of
644 // large-object allocations that are only just larger than the page size.
Leon Clarkee46be812010-01-19 14:06:41 +0000645 large_object_size *= 2;
646 // The ReserveSpace method on the large object space checks how much
647 // we can expand the old generation. This includes expansion caused by
648 // allocation in the other spaces.
649 large_object_size += cell_space_size + map_space_size + code_space_size +
650 data_space_size + pointer_space_size;
651 if (!(lo_space->ReserveSpace(large_object_size))) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100652 AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
653 "failed to reserve space in the large object space");
Leon Clarkee46be812010-01-19 14:06:41 +0000654 gc_performed = true;
655 }
656 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000657
658 if (gc_performed) {
659 // Failed to reserve the space after several attempts.
660 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
661 }
Leon Clarkee46be812010-01-19 14:06:41 +0000662}
663
664
Steve Blocka7e24c12009-10-30 11:49:00 +0000665void Heap::EnsureFromSpaceIsCommitted() {
666 if (new_space_.CommitFromSpaceIfNeeded()) return;
667
668 // Committing memory to from space failed.
669 // Try shrinking and try again.
670 Shrink();
671 if (new_space_.CommitFromSpaceIfNeeded()) return;
672
673 // Committing memory to from space failed again.
674 // Memory is exhausted and we will die.
675 V8::FatalProcessOutOfMemory("Committing semi space failed.");
676}
677
678
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800679void Heap::ClearJSFunctionResultCaches() {
Steve Block44f0eee2011-05-26 01:26:41 +0100680 if (isolate_->bootstrapper()->IsActive()) return;
Steve Block6ded16b2010-05-10 14:33:55 +0100681
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800682 Object* context = global_contexts_list_;
683 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000684 // Get the caches for this context. GC can happen when the context
685 // is not fully initialized, so the caches can be undefined.
686 Object* caches_or_undefined =
687 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
688 if (!caches_or_undefined->IsUndefined()) {
689 FixedArray* caches = FixedArray::cast(caches_or_undefined);
690 // Clear the caches:
691 int length = caches->length();
692 for (int i = 0; i < length; i++) {
693 JSFunctionResultCache::cast(caches->get(i))->Clear();
694 }
Steve Block6ded16b2010-05-10 14:33:55 +0100695 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800696 // Get the next context:
697 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
Steve Block6ded16b2010-05-10 14:33:55 +0100698 }
Steve Block6ded16b2010-05-10 14:33:55 +0100699}
700
701
Steve Block44f0eee2011-05-26 01:26:41 +0100702
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100703void Heap::ClearNormalizedMapCaches() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000704 if (isolate_->bootstrapper()->IsActive() &&
705 !incremental_marking()->IsMarking()) {
706 return;
707 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100708
709 Object* context = global_contexts_list_;
710 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000711 // GC can happen when the context is not fully initialized,
712 // so the cache can be undefined.
713 Object* cache =
714 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
715 if (!cache->IsUndefined()) {
716 NormalizedMapCache::cast(cache)->Clear();
717 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100718 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
719 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100720}
721
722
Steve Block8defd9f2010-07-08 12:39:36 +0100723void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
724 double survival_rate =
725 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
726 start_new_space_size;
727
Ben Murdochc7cc0282012-03-05 14:35:55 +0000728 if (survival_rate > kYoungSurvivalRateHighThreshold) {
Steve Block8defd9f2010-07-08 12:39:36 +0100729 high_survival_rate_period_length_++;
730 } else {
731 high_survival_rate_period_length_ = 0;
732 }
733
Ben Murdochc7cc0282012-03-05 14:35:55 +0000734 if (survival_rate < kYoungSurvivalRateLowThreshold) {
735 low_survival_rate_period_length_++;
736 } else {
737 low_survival_rate_period_length_ = 0;
738 }
739
Steve Block8defd9f2010-07-08 12:39:36 +0100740 double survival_rate_diff = survival_rate_ - survival_rate;
741
742 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
743 set_survival_rate_trend(DECREASING);
744 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
745 set_survival_rate_trend(INCREASING);
746 } else {
747 set_survival_rate_trend(STABLE);
748 }
749
750 survival_rate_ = survival_rate;
751}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100752
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800753bool Heap::PerformGarbageCollection(GarbageCollector collector,
John Reck59135872010-11-02 12:39:01 -0700754 GCTracer* tracer) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800755 bool next_gc_likely_to_collect_more = false;
756
Ben Murdochf87a2032010-10-22 12:50:53 +0100757 if (collector != SCAVENGER) {
Steve Block44f0eee2011-05-26 01:26:41 +0100758 PROFILE(isolate_, CodeMovingGCEvent());
Ben Murdochf87a2032010-10-22 12:50:53 +0100759 }
760
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000761 if (FLAG_verify_heap) {
762 VerifySymbolTable();
763 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000764 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
765 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100766 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000767 global_gc_prologue_callback_();
768 }
Steve Block6ded16b2010-05-10 14:33:55 +0100769
770 GCType gc_type =
771 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
772
773 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
774 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
775 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
776 }
777 }
778
Steve Blocka7e24c12009-10-30 11:49:00 +0000779 EnsureFromSpaceIsCommitted();
Steve Block6ded16b2010-05-10 14:33:55 +0100780
Ben Murdochf87a2032010-10-22 12:50:53 +0100781 int start_new_space_size = Heap::new_space()->SizeAsInt();
Steve Block8defd9f2010-07-08 12:39:36 +0100782
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000783 if (IsHighSurvivalRate()) {
784 // We speed up the incremental marker if it is running so that it
785 // does not fall behind the rate of promotion, which would cause a
786 // constantly growing old space.
787 incremental_marking()->NotifyOfHighPromotionRate();
788 }
789
Steve Blocka7e24c12009-10-30 11:49:00 +0000790 if (collector == MARK_COMPACTOR) {
Steve Block6ded16b2010-05-10 14:33:55 +0100791 // Perform mark-sweep with optional compaction.
Steve Blocka7e24c12009-10-30 11:49:00 +0000792 MarkCompact(tracer);
Ben Murdoch257744e2011-11-30 15:57:28 +0000793 sweep_generation_++;
Steve Block8defd9f2010-07-08 12:39:36 +0100794 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
795 IsStableOrIncreasingSurvivalTrend();
796
797 UpdateSurvivalRateTrend(start_new_space_size);
798
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000799 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSize();
Steve Block8defd9f2010-07-08 12:39:36 +0100800
John Reck59135872010-11-02 12:39:01 -0700801 if (high_survival_rate_during_scavenges &&
802 IsStableOrIncreasingSurvivalTrend()) {
803 // Stable high survival rates of young objects both during partial and
804 // full collection indicate that mutator is either building or modifying
805 // a structure with a long lifetime.
806 // In this case we aggressively raise old generation memory limits to
807 // postpone subsequent mark-sweep collection and thus trade memory
808 // space for the mutation speed.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000809 old_gen_limit_factor_ = 2;
810 } else {
811 old_gen_limit_factor_ = 1;
Steve Block8defd9f2010-07-08 12:39:36 +0100812 }
813
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000814 old_gen_promotion_limit_ =
815 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
816 old_gen_allocation_limit_ =
817 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
818
John Reck59135872010-11-02 12:39:01 -0700819 old_gen_exhausted_ = false;
Steve Block6ded16b2010-05-10 14:33:55 +0100820 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +0100821 tracer_ = tracer;
Steve Block6ded16b2010-05-10 14:33:55 +0100822 Scavenge();
Leon Clarkef7060e22010-06-03 12:02:55 +0100823 tracer_ = NULL;
Steve Block8defd9f2010-07-08 12:39:36 +0100824
825 UpdateSurvivalRateTrend(start_new_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000826 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000827
Ben Murdochc7cc0282012-03-05 14:35:55 +0000828 if (!new_space_high_promotion_mode_active_ &&
829 new_space_.Capacity() == new_space_.MaximumCapacity() &&
830 IsStableOrIncreasingSurvivalTrend() &&
831 IsHighSurvivalRate()) {
832 // Stable high survival rates even though young generation is at
833 // maximum capacity indicates that most objects will be promoted.
834 // To decrease scavenger pauses and final mark-sweep pauses, we
835 // have to limit maximal capacity of the young generation.
836 new_space_high_promotion_mode_active_ = true;
837 if (FLAG_trace_gc) {
838 PrintF("Limited new space size due to high promotion rate: %d MB\n",
839 new_space_.InitialCapacity() / MB);
840 }
841 } else if (new_space_high_promotion_mode_active_ &&
842 IsStableOrDecreasingSurvivalTrend() &&
843 IsLowSurvivalRate()) {
844 // Decreasing low survival rates might indicate that the above high
845 // promotion mode is over and we should allow the young generation
846 // to grow again.
847 new_space_high_promotion_mode_active_ = false;
848 if (FLAG_trace_gc) {
849 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
850 new_space_.MaximumCapacity() / MB);
851 }
852 }
853
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000854 if (new_space_high_promotion_mode_active_ &&
855 new_space_.Capacity() > new_space_.InitialCapacity()) {
856 new_space_.Shrink();
857 }
858
Steve Block44f0eee2011-05-26 01:26:41 +0100859 isolate_->counters()->objs_since_last_young()->Set(0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000860
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000861 gc_post_processing_depth_++;
Ben Murdoch257744e2011-11-30 15:57:28 +0000862 { DisableAssertNoAllocation allow_allocation;
John Reck59135872010-11-02 12:39:01 -0700863 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800864 next_gc_likely_to_collect_more =
Ben Murdoch257744e2011-11-30 15:57:28 +0000865 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
John Reck59135872010-11-02 12:39:01 -0700866 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000867 gc_post_processing_depth_--;
John Reck59135872010-11-02 12:39:01 -0700868
Steve Block3ce2e202009-11-05 08:53:23 +0000869 // Update relocatables.
870 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000871
872 if (collector == MARK_COMPACTOR) {
873 // Register the amount of external allocated memory.
874 amount_of_external_allocated_memory_at_last_global_gc_ =
875 amount_of_external_allocated_memory_;
876 }
877
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000878 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
Steve Block6ded16b2010-05-10 14:33:55 +0100879 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
880 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
881 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
882 }
883 }
884
Steve Blocka7e24c12009-10-30 11:49:00 +0000885 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
886 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100887 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000888 global_gc_epilogue_callback_();
889 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000890 if (FLAG_verify_heap) {
891 VerifySymbolTable();
892 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800893
894 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000895}
896
897
Steve Blocka7e24c12009-10-30 11:49:00 +0000898void Heap::MarkCompact(GCTracer* tracer) {
899 gc_state_ = MARK_COMPACT;
Steve Block44f0eee2011-05-26 01:26:41 +0100900 LOG(isolate_, ResourceEvent("markcompact", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000901
Steve Block44f0eee2011-05-26 01:26:41 +0100902 mark_compact_collector_.Prepare(tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000903
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000904 ms_count_++;
905 tracer->set_full_gc_count(ms_count_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000906
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000907 MarkCompactPrologue();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100908
Steve Block44f0eee2011-05-26 01:26:41 +0100909 mark_compact_collector_.CollectGarbage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000910
Steve Block44f0eee2011-05-26 01:26:41 +0100911 LOG(isolate_, ResourceEvent("markcompact", "end"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000912
913 gc_state_ = NOT_IN_GC;
914
Steve Block44f0eee2011-05-26 01:26:41 +0100915 isolate_->counters()->objs_since_last_full()->Set(0);
Steve Block6ded16b2010-05-10 14:33:55 +0100916
917 contexts_disposed_ = 0;
Ben Murdochc7cc0282012-03-05 14:35:55 +0000918
919 isolate_->set_context_exit_happened(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000920}
921
922
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000923void Heap::MarkCompactPrologue() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000924 // At any old GC clear the keyed lookup cache to enable collection of unused
925 // maps.
Steve Block44f0eee2011-05-26 01:26:41 +0100926 isolate_->keyed_lookup_cache()->Clear();
927 isolate_->context_slot_cache()->Clear();
928 isolate_->descriptor_lookup_cache()->Clear();
Ben Murdoch589d6972011-11-30 16:04:58 +0000929 StringSplitCache::Clear(string_split_cache());
Steve Blocka7e24c12009-10-30 11:49:00 +0000930
Steve Block44f0eee2011-05-26 01:26:41 +0100931 isolate_->compilation_cache()->MarkCompactPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000932
Kristian Monsen25f61362010-05-21 11:50:48 +0100933 CompletelyClearInstanceofCache();
934
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +0100935 FlushNumberStringCache();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000936 if (FLAG_cleanup_code_caches_at_gc) {
937 polymorphic_code_cache()->set_cache(undefined_value());
938 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000939
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100940 ClearNormalizedMapCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000941}
942
943
944Object* Heap::FindCodeObject(Address a) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000945 return isolate()->inner_pointer_to_code_cache()->
946 GcSafeFindCodeForInnerPointer(a);
Steve Blocka7e24c12009-10-30 11:49:00 +0000947}
948
949
950// Helper class for copying HeapObjects
951class ScavengeVisitor: public ObjectVisitor {
952 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100953 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000954
955 void VisitPointer(Object** p) { ScavengePointer(p); }
956
957 void VisitPointers(Object** start, Object** end) {
958 // Copy all HeapObject pointers in [start, end)
959 for (Object** p = start; p < end; p++) ScavengePointer(p);
960 }
961
962 private:
963 void ScavengePointer(Object** p) {
964 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +0100965 if (!heap_->InNewSpace(object)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
967 reinterpret_cast<HeapObject*>(object));
968 }
Steve Block44f0eee2011-05-26 01:26:41 +0100969
970 Heap* heap_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000971};
972
973
Steve Blocka7e24c12009-10-30 11:49:00 +0000974#ifdef DEBUG
975// Visitor class to verify pointers in code or data space do not point into
976// new space.
977class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
978 public:
979 void VisitPointers(Object** start, Object**end) {
980 for (Object** current = start; current < end; current++) {
981 if ((*current)->IsHeapObject()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100982 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000983 }
984 }
985 }
986};
987
988
989static void VerifyNonPointerSpacePointers() {
990 // Verify that there are no pointers to new space in spaces where we
991 // do not expect them.
992 VerifyNonPointerSpacePointersVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +0100993 HeapObjectIterator code_it(HEAP->code_space());
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000994 for (HeapObject* object = code_it.Next();
995 object != NULL; object = code_it.Next())
Steve Blocka7e24c12009-10-30 11:49:00 +0000996 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000997
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000998 // The old data space was normally swept conservatively so that the iterator
999 // doesn't work, so we normally skip the next bit.
1000 if (!HEAP->old_data_space()->was_swept_conservatively()) {
1001 HeapObjectIterator data_it(HEAP->old_data_space());
1002 for (HeapObject* object = data_it.Next();
1003 object != NULL; object = data_it.Next())
1004 object->Iterate(&v);
1005 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001006}
1007#endif
1008
1009
Steve Block6ded16b2010-05-10 14:33:55 +01001010void Heap::CheckNewSpaceExpansionCriteria() {
1011 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001012 survived_since_last_expansion_ > new_space_.Capacity() &&
1013 !new_space_high_promotion_mode_active_) {
1014 // Grow the size of new space if there is room to grow, enough data
1015 // has survived scavenge since the last expansion and we are not in
1016 // high promotion mode.
Steve Block6ded16b2010-05-10 14:33:55 +01001017 new_space_.Grow();
1018 survived_since_last_expansion_ = 0;
1019 }
1020}
1021
1022
Ben Murdoch257744e2011-11-30 15:57:28 +00001023static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1024 return heap->InNewSpace(*p) &&
1025 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1026}
1027
1028
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001029void Heap::ScavengeStoreBufferCallback(
1030 Heap* heap,
1031 MemoryChunk* page,
1032 StoreBufferEvent event) {
1033 heap->store_buffer_rebuilder_.Callback(page, event);
1034}
1035
1036
1037void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1038 if (event == kStoreBufferStartScanningPagesEvent) {
1039 start_of_current_page_ = NULL;
1040 current_page_ = NULL;
1041 } else if (event == kStoreBufferScanningPageEvent) {
1042 if (current_page_ != NULL) {
1043 // If this page already overflowed the store buffer during this iteration.
1044 if (current_page_->scan_on_scavenge()) {
1045 // Then we should wipe out the entries that have been added for it.
1046 store_buffer_->SetTop(start_of_current_page_);
1047 } else if (store_buffer_->Top() - start_of_current_page_ >=
1048 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1049 // Did we find too many pointers in the previous page? The heuristic is
1050 // that no page can take more then 1/5 the remaining slots in the store
1051 // buffer.
1052 current_page_->set_scan_on_scavenge(true);
1053 store_buffer_->SetTop(start_of_current_page_);
1054 } else {
1055 // In this case the page we scanned took a reasonable number of slots in
1056 // the store buffer. It has now been rehabilitated and is no longer
1057 // marked scan_on_scavenge.
1058 ASSERT(!current_page_->scan_on_scavenge());
1059 }
1060 }
1061 start_of_current_page_ = store_buffer_->Top();
1062 current_page_ = page;
1063 } else if (event == kStoreBufferFullEvent) {
1064 // The current page overflowed the store buffer again. Wipe out its entries
1065 // in the store buffer and mark it scan-on-scavenge again. This may happen
1066 // several times while scanning.
1067 if (current_page_ == NULL) {
1068 // Store Buffer overflowed while scanning promoted objects. These are not
1069 // in any particular page, though they are likely to be clustered by the
1070 // allocation routines.
Ben Murdochc7cc0282012-03-05 14:35:55 +00001071 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001072 } else {
1073 // Store Buffer overflowed while scanning a particular old space page for
1074 // pointers to new space.
1075 ASSERT(current_page_ == page);
1076 ASSERT(page != NULL);
1077 current_page_->set_scan_on_scavenge(true);
1078 ASSERT(start_of_current_page_ != store_buffer_->Top());
1079 store_buffer_->SetTop(start_of_current_page_);
1080 }
1081 } else {
1082 UNREACHABLE();
1083 }
1084}
1085
1086
1087void PromotionQueue::Initialize() {
1088 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1089 // entries (where each is a pair of intptr_t). This allows us to simplify
1090 // the test fpr when to switch pages.
1091 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1092 == 0);
1093 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1094 front_ = rear_ =
1095 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1096 emergency_stack_ = NULL;
1097 guard_ = false;
1098}
1099
1100
1101void PromotionQueue::RelocateQueueHead() {
1102 ASSERT(emergency_stack_ == NULL);
1103
1104 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1105 intptr_t* head_start = rear_;
1106 intptr_t* head_end =
1107 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1108
1109 int entries_count =
1110 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1111
1112 emergency_stack_ = new List<Entry>(2 * entries_count);
1113
1114 while (head_start != head_end) {
1115 int size = static_cast<int>(*(head_start++));
1116 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1117 emergency_stack_->Add(Entry(obj, size));
1118 }
1119 rear_ = head_end;
1120}
1121
1122
Steve Blocka7e24c12009-10-30 11:49:00 +00001123void Heap::Scavenge() {
1124#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001125 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
Steve Blocka7e24c12009-10-30 11:49:00 +00001126#endif
1127
1128 gc_state_ = SCAVENGE;
1129
1130 // Implements Cheney's copying algorithm
Steve Block44f0eee2011-05-26 01:26:41 +01001131 LOG(isolate_, ResourceEvent("scavenge", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001132
1133 // Clear descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01001134 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00001135
1136 // Used for updating survived_since_last_expansion_ at function end.
Ben Murdochc7cc0282012-03-05 14:35:55 +00001137 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +00001138
Steve Block6ded16b2010-05-10 14:33:55 +01001139 CheckNewSpaceExpansionCriteria();
Steve Blocka7e24c12009-10-30 11:49:00 +00001140
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001141 SelectScavengingVisitorsTable();
1142
1143 incremental_marking()->PrepareForScavenge();
1144
Ben Murdochc7cc0282012-03-05 14:35:55 +00001145 AdvanceSweepers(static_cast<int>(new_space_.Size()));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001146
Steve Blocka7e24c12009-10-30 11:49:00 +00001147 // Flip the semispaces. After flipping, to space is empty, from space has
1148 // live objects.
1149 new_space_.Flip();
1150 new_space_.ResetAllocationInfo();
1151
1152 // We need to sweep newly copied objects which can be either in the
1153 // to space or promoted to the old generation. For to-space
1154 // objects, we treat the bottom of the to space as a queue. Newly
1155 // copied and unswept objects lie between a 'front' mark and the
1156 // allocation pointer.
1157 //
1158 // Promoted objects can go into various old-generation spaces, and
1159 // can be allocated internally in the spaces (from the free list).
1160 // We treat the top of the to space as a queue of addresses of
1161 // promoted objects. The addresses of newly promoted and unswept
1162 // objects lie between a 'front' mark and a 'rear' mark that is
1163 // updated as a side effect of promoting an object.
1164 //
1165 // There is guaranteed to be enough room at the top of the to space
1166 // for the addresses of promoted objects: every object promoted
1167 // frees up its size in bytes from the top of the new space, and
1168 // objects are at least one pointer in size.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001169 Address new_space_front = new_space_.ToSpaceStart();
1170 promotion_queue_.Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +00001171
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001172#ifdef DEBUG
1173 store_buffer()->Clean();
1174#endif
1175
Steve Block44f0eee2011-05-26 01:26:41 +01001176 ScavengeVisitor scavenge_visitor(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00001177 // Copy roots.
Leon Clarkee46be812010-01-19 14:06:41 +00001178 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001179
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001180 // Copy objects reachable from the old generation.
1181 {
1182 StoreBufferRebuildScope scope(this,
1183 store_buffer(),
1184 &ScavengeStoreBufferCallback);
1185 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1186 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001187
1188 // Copy objects reachable from cells by scavenging cell values directly.
1189 HeapObjectIterator cell_iterator(cell_space_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001190 for (HeapObject* cell = cell_iterator.Next();
1191 cell != NULL; cell = cell_iterator.Next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001192 if (cell->IsJSGlobalPropertyCell()) {
1193 Address value_address =
1194 reinterpret_cast<Address>(cell) +
1195 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1196 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1197 }
1198 }
1199
Ben Murdochf87a2032010-10-22 12:50:53 +01001200 // Scavenge object reachable from the global contexts list directly.
1201 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1202
Leon Clarkee46be812010-01-19 14:06:41 +00001203 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001204 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
Ben Murdoch257744e2011-11-30 15:57:28 +00001205 &IsUnscavengedHeapObject);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001206 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1207 &scavenge_visitor);
Ben Murdoch257744e2011-11-30 15:57:28 +00001208 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1209
Steve Block6ded16b2010-05-10 14:33:55 +01001210 UpdateNewSpaceReferencesInExternalStringTable(
1211 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1212
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001213 promotion_queue_.Destroy();
1214
Steve Block1e0659c2011-05-24 12:43:12 +01001215 LiveObjectList::UpdateReferencesForScavengeGC();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01001216 if (!FLAG_watch_ic_patching) {
1217 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1218 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001219 incremental_marking()->UpdateMarkingDequeAfterScavenge();
Steve Block1e0659c2011-05-24 12:43:12 +01001220
Leon Clarkee46be812010-01-19 14:06:41 +00001221 ASSERT(new_space_front == new_space_.top());
1222
1223 // Set age mark.
1224 new_space_.set_age_mark(new_space_.top());
1225
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001226 new_space_.LowerInlineAllocationLimit(
1227 new_space_.inline_allocation_limit_step());
1228
Leon Clarkee46be812010-01-19 14:06:41 +00001229 // Update how much has survived scavenge.
Ben Murdochf87a2032010-10-22 12:50:53 +01001230 IncrementYoungSurvivorsCounter(static_cast<int>(
Ben Murdochc7cc0282012-03-05 14:35:55 +00001231 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
Leon Clarkee46be812010-01-19 14:06:41 +00001232
Steve Block44f0eee2011-05-26 01:26:41 +01001233 LOG(isolate_, ResourceEvent("scavenge", "end"));
Leon Clarkee46be812010-01-19 14:06:41 +00001234
1235 gc_state_ = NOT_IN_GC;
Ben Murdochc7cc0282012-03-05 14:35:55 +00001236
1237 scavenges_since_last_idle_round_++;
Leon Clarkee46be812010-01-19 14:06:41 +00001238}
1239
1240
Steve Block44f0eee2011-05-26 01:26:41 +01001241String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1242 Object** p) {
Steve Block6ded16b2010-05-10 14:33:55 +01001243 MapWord first_word = HeapObject::cast(*p)->map_word();
1244
1245 if (!first_word.IsForwardingAddress()) {
1246 // Unreachable external string can be finalized.
Steve Block44f0eee2011-05-26 01:26:41 +01001247 heap->FinalizeExternalString(String::cast(*p));
Steve Block6ded16b2010-05-10 14:33:55 +01001248 return NULL;
1249 }
1250
1251 // String is still reachable.
1252 return String::cast(first_word.ToForwardingAddress());
1253}
1254
1255
1256void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1257 ExternalStringTableUpdaterCallback updater_func) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001258 if (FLAG_verify_heap) {
1259 external_string_table_.Verify();
1260 }
Leon Clarkee46be812010-01-19 14:06:41 +00001261
Steve Block44f0eee2011-05-26 01:26:41 +01001262 if (external_string_table_.new_space_strings_.is_empty()) return;
Leon Clarkee46be812010-01-19 14:06:41 +00001263
Steve Block44f0eee2011-05-26 01:26:41 +01001264 Object** start = &external_string_table_.new_space_strings_[0];
1265 Object** end = start + external_string_table_.new_space_strings_.length();
Leon Clarkee46be812010-01-19 14:06:41 +00001266 Object** last = start;
1267
1268 for (Object** p = start; p < end; ++p) {
Steve Block44f0eee2011-05-26 01:26:41 +01001269 ASSERT(InFromSpace(*p));
1270 String* target = updater_func(this, p);
Leon Clarkee46be812010-01-19 14:06:41 +00001271
Steve Block6ded16b2010-05-10 14:33:55 +01001272 if (target == NULL) continue;
Leon Clarkee46be812010-01-19 14:06:41 +00001273
Leon Clarkee46be812010-01-19 14:06:41 +00001274 ASSERT(target->IsExternalString());
1275
Steve Block44f0eee2011-05-26 01:26:41 +01001276 if (InNewSpace(target)) {
Leon Clarkee46be812010-01-19 14:06:41 +00001277 // String is still in new space. Update the table entry.
1278 *last = target;
1279 ++last;
1280 } else {
1281 // String got promoted. Move it to the old string list.
Steve Block44f0eee2011-05-26 01:26:41 +01001282 external_string_table_.AddOldString(target);
Leon Clarkee46be812010-01-19 14:06:41 +00001283 }
1284 }
1285
1286 ASSERT(last <= end);
Steve Block44f0eee2011-05-26 01:26:41 +01001287 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
Leon Clarkee46be812010-01-19 14:06:41 +00001288}
1289
1290
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001291void Heap::UpdateReferencesInExternalStringTable(
1292 ExternalStringTableUpdaterCallback updater_func) {
1293
1294 // Update old space string references.
1295 if (external_string_table_.old_space_strings_.length() > 0) {
1296 Object** start = &external_string_table_.old_space_strings_[0];
1297 Object** end = start + external_string_table_.old_space_strings_.length();
1298 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1299 }
1300
1301 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1302}
1303
1304
Steve Block44f0eee2011-05-26 01:26:41 +01001305static Object* ProcessFunctionWeakReferences(Heap* heap,
1306 Object* function,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001307 WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001308 Object* undefined = heap->undefined_value();
1309 Object* head = undefined;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001310 JSFunction* tail = NULL;
1311 Object* candidate = function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001312 while (candidate != undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001313 // Check whether to keep the candidate in the list.
1314 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1315 Object* retain = retainer->RetainAs(candidate);
1316 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001317 if (head == undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001318 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001319 head = retain;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001320 } else {
1321 // Subsequent elements in the list.
1322 ASSERT(tail != NULL);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001323 tail->set_next_function_link(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001324 }
1325 // Retained function is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001326 candidate_function = reinterpret_cast<JSFunction*>(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001327 tail = candidate_function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001328
1329 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1330
1331 if (retain == undefined) break;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001332 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001333
Ben Murdochb0fe1622011-05-05 13:52:32 +01001334 // Move to next element in the list.
1335 candidate = candidate_function->next_function_link();
1336 }
1337
1338 // Terminate the list if there is one or more elements.
1339 if (tail != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001340 tail->set_next_function_link(undefined);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001341 }
1342
1343 return head;
1344}
1345
1346
Ben Murdochf87a2032010-10-22 12:50:53 +01001347void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001348 Object* undefined = undefined_value();
1349 Object* head = undefined;
Ben Murdochf87a2032010-10-22 12:50:53 +01001350 Context* tail = NULL;
1351 Object* candidate = global_contexts_list_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001352 while (candidate != undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001353 // Check whether to keep the candidate in the list.
1354 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1355 Object* retain = retainer->RetainAs(candidate);
1356 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001357 if (head == undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001358 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001359 head = retain;
Ben Murdochf87a2032010-10-22 12:50:53 +01001360 } else {
1361 // Subsequent elements in the list.
1362 ASSERT(tail != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01001363 tail->set_unchecked(this,
1364 Context::NEXT_CONTEXT_LINK,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001365 retain,
Ben Murdochf87a2032010-10-22 12:50:53 +01001366 UPDATE_WRITE_BARRIER);
1367 }
1368 // Retained context is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001369 candidate_context = reinterpret_cast<Context*>(retain);
Ben Murdochf87a2032010-10-22 12:50:53 +01001370 tail = candidate_context;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001371
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001372 if (retain == undefined) break;
1373
Ben Murdochb0fe1622011-05-05 13:52:32 +01001374 // Process the weak list of optimized functions for the context.
1375 Object* function_list_head =
1376 ProcessFunctionWeakReferences(
Steve Block44f0eee2011-05-26 01:26:41 +01001377 this,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001378 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1379 retainer);
Steve Block44f0eee2011-05-26 01:26:41 +01001380 candidate_context->set_unchecked(this,
1381 Context::OPTIMIZED_FUNCTIONS_LIST,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001382 function_list_head,
1383 UPDATE_WRITE_BARRIER);
Ben Murdochf87a2032010-10-22 12:50:53 +01001384 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001385
Ben Murdochf87a2032010-10-22 12:50:53 +01001386 // Move to next element in the list.
1387 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1388 }
1389
1390 // Terminate the list if there is one or more elements.
1391 if (tail != NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01001392 tail->set_unchecked(this,
1393 Context::NEXT_CONTEXT_LINK,
Ben Murdochf87a2032010-10-22 12:50:53 +01001394 Heap::undefined_value(),
1395 UPDATE_WRITE_BARRIER);
1396 }
1397
1398 // Update the head of the list of contexts.
Steve Block44f0eee2011-05-26 01:26:41 +01001399 global_contexts_list_ = head;
Ben Murdochf87a2032010-10-22 12:50:53 +01001400}
1401
1402
Ben Murdochc7cc0282012-03-05 14:35:55 +00001403void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1404 AssertNoAllocation no_allocation;
1405
1406 class VisitorAdapter : public ObjectVisitor {
1407 public:
1408 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1409 : visitor_(visitor) {}
1410 virtual void VisitPointers(Object** start, Object** end) {
1411 for (Object** p = start; p < end; p++) {
1412 if ((*p)->IsExternalString()) {
1413 visitor_->VisitExternalString(Utils::ToLocal(
1414 Handle<String>(String::cast(*p))));
1415 }
1416 }
1417 }
1418 private:
1419 v8::ExternalResourceVisitor* visitor_;
1420 } visitor_adapter(visitor);
1421 external_string_table_.Iterate(&visitor_adapter);
1422}
1423
1424
Iain Merrick75681382010-08-19 15:07:18 +01001425class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1426 public:
Steve Block44f0eee2011-05-26 01:26:41 +01001427 static inline void VisitPointer(Heap* heap, Object** p) {
Iain Merrick75681382010-08-19 15:07:18 +01001428 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +01001429 if (!heap->InNewSpace(object)) return;
Iain Merrick75681382010-08-19 15:07:18 +01001430 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1431 reinterpret_cast<HeapObject*>(object));
1432 }
1433};
1434
1435
Leon Clarkee46be812010-01-19 14:06:41 +00001436Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1437 Address new_space_front) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001438 do {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001439 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001440 // The addresses new_space_front and new_space_.top() define a
1441 // queue of unprocessed copied objects. Process them until the
1442 // queue is empty.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001443 while (new_space_front != new_space_.top()) {
1444 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1445 HeapObject* object = HeapObject::FromAddress(new_space_front);
1446 new_space_front +=
1447 NewSpaceScavenger::IterateBody(object->map(), object);
1448 } else {
1449 new_space_front =
1450 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1451 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001452 }
1453
1454 // Promote and process all the to-be-promoted objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001455 {
1456 StoreBufferRebuildScope scope(this,
1457 store_buffer(),
1458 &ScavengeStoreBufferCallback);
1459 while (!promotion_queue()->is_empty()) {
1460 HeapObject* target;
1461 int size;
1462 promotion_queue()->remove(&target, &size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001463
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001464 // Promoted object might be already partially visited
1465 // during old space pointer iteration. Thus we search specificly
1466 // for pointers to from semispace instead of looking for pointers
1467 // to new space.
1468 ASSERT(!target->IsMap());
1469 IterateAndMarkPointersToFromSpace(target->address(),
1470 target->address() + size,
1471 &ScavengeObject);
1472 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001473 }
1474
1475 // Take another spin if there are now unswept objects in new space
1476 // (there are currently no more unswept promoted objects).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001477 } while (new_space_front != new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001478
Leon Clarkee46be812010-01-19 14:06:41 +00001479 return new_space_front;
Steve Blocka7e24c12009-10-30 11:49:00 +00001480}
1481
1482
Ben Murdoch8b112d22011-06-08 16:22:53 +01001483enum LoggingAndProfiling {
1484 LOGGING_AND_PROFILING_ENABLED,
1485 LOGGING_AND_PROFILING_DISABLED
1486};
1487
1488
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001489enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
Ben Murdoch8b112d22011-06-08 16:22:53 +01001490
1491
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001492template<MarksHandling marks_handling,
1493 LoggingAndProfiling logging_and_profiling_mode>
Iain Merrick75681382010-08-19 15:07:18 +01001494class ScavengingVisitor : public StaticVisitorBase {
1495 public:
1496 static void Initialize() {
1497 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1498 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1499 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1500 table_.Register(kVisitByteArray, &EvacuateByteArray);
1501 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001502 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001503
Ben Murdochf87a2032010-10-22 12:50:53 +01001504 table_.Register(kVisitGlobalContext,
1505 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001506 template VisitSpecialized<Context::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001507
1508 table_.Register(kVisitConsString,
1509 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001510 template VisitSpecialized<ConsString::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001511
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001512 table_.Register(kVisitSlicedString,
1513 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1514 template VisitSpecialized<SlicedString::kSize>);
1515
Iain Merrick75681382010-08-19 15:07:18 +01001516 table_.Register(kVisitSharedFunctionInfo,
1517 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001518 template VisitSpecialized<SharedFunctionInfo::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001519
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001520 table_.Register(kVisitJSWeakMap,
1521 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1522 Visit);
1523
Ben Murdoch257744e2011-11-30 15:57:28 +00001524 table_.Register(kVisitJSRegExp,
1525 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1526 Visit);
1527
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001528 if (marks_handling == IGNORE_MARKS) {
1529 table_.Register(kVisitJSFunction,
1530 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1531 template VisitSpecialized<JSFunction::kSize>);
1532 } else {
1533 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1534 }
Iain Merrick75681382010-08-19 15:07:18 +01001535
1536 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1537 kVisitDataObject,
1538 kVisitDataObjectGeneric>();
1539
1540 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1541 kVisitJSObject,
1542 kVisitJSObjectGeneric>();
1543
1544 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1545 kVisitStruct,
1546 kVisitStructGeneric>();
1547 }
1548
Ben Murdoch8b112d22011-06-08 16:22:53 +01001549 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1550 return &table_;
Iain Merrick75681382010-08-19 15:07:18 +01001551 }
1552
Iain Merrick75681382010-08-19 15:07:18 +01001553 private:
1554 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1555 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1556
Steve Block44f0eee2011-05-26 01:26:41 +01001557 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
Iain Merrick75681382010-08-19 15:07:18 +01001558 bool should_record = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001559#ifdef DEBUG
Iain Merrick75681382010-08-19 15:07:18 +01001560 should_record = FLAG_heap_stats;
Steve Blocka7e24c12009-10-30 11:49:00 +00001561#endif
Iain Merrick75681382010-08-19 15:07:18 +01001562 should_record = should_record || FLAG_log_gc;
Iain Merrick75681382010-08-19 15:07:18 +01001563 if (should_record) {
Steve Block44f0eee2011-05-26 01:26:41 +01001564 if (heap->new_space()->Contains(obj)) {
1565 heap->new_space()->RecordAllocation(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001566 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001567 heap->new_space()->RecordPromotion(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001568 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001569 }
1570 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001571
Iain Merrick75681382010-08-19 15:07:18 +01001572 // Helper function used by CopyObject to copy a source object to an
1573 // allocated target object and update the forwarding pointer in the source
1574 // object. Returns the target object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001575 INLINE(static void MigrateObject(Heap* heap,
1576 HeapObject* source,
1577 HeapObject* target,
1578 int size)) {
Iain Merrick75681382010-08-19 15:07:18 +01001579 // Copy the content of source to target.
Steve Block44f0eee2011-05-26 01:26:41 +01001580 heap->CopyBlock(target->address(), source->address(), size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001581
Iain Merrick75681382010-08-19 15:07:18 +01001582 // Set the forwarding address.
1583 source->set_map_word(MapWord::FromForwardingAddress(target));
Steve Blocka7e24c12009-10-30 11:49:00 +00001584
Ben Murdoch8b112d22011-06-08 16:22:53 +01001585 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001586 // Update NewSpace stats if necessary.
1587 RecordCopiedObject(heap, target);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001588 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
Ben Murdoch8b112d22011-06-08 16:22:53 +01001589 Isolate* isolate = heap->isolate();
1590 if (isolate->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001591 CpuProfiler::is_profiling(isolate)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001592 if (target->IsSharedFunctionInfo()) {
1593 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1594 source->address(), target->address()));
1595 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001596 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001597 }
1598
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001599 if (marks_handling == TRANSFER_MARKS) {
1600 if (Marking::TransferColor(source, target)) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00001601 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001602 }
1603 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001604 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001605
Iain Merrick75681382010-08-19 15:07:18 +01001606 template<ObjectContents object_contents, SizeRestriction size_restriction>
1607 static inline void EvacuateObject(Map* map,
1608 HeapObject** slot,
1609 HeapObject* object,
1610 int object_size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001611 SLOW_ASSERT((size_restriction != SMALL) ||
1612 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1613 SLOW_ASSERT(object->Size() == object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001614
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001615 Heap* heap = map->GetHeap();
Steve Block44f0eee2011-05-26 01:26:41 +01001616 if (heap->ShouldBePromoted(object->address(), object_size)) {
John Reck59135872010-11-02 12:39:01 -07001617 MaybeObject* maybe_result;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001618
Iain Merrick75681382010-08-19 15:07:18 +01001619 if ((size_restriction != SMALL) &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001620 (object_size > Page::kMaxNonCodeHeapObjectSize)) {
1621 maybe_result = heap->lo_space()->AllocateRaw(object_size,
1622 NOT_EXECUTABLE);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001623 } else {
Iain Merrick75681382010-08-19 15:07:18 +01001624 if (object_contents == DATA_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001625 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001626 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001627 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001628 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001629 }
1630
John Reck59135872010-11-02 12:39:01 -07001631 Object* result = NULL; // Initialization to please compiler.
1632 if (maybe_result->ToObject(&result)) {
Iain Merrick75681382010-08-19 15:07:18 +01001633 HeapObject* target = HeapObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001634
1635 // Order is important: slot might be inside of the target if target
1636 // was allocated over a dead object and slot comes from the store
1637 // buffer.
1638 *slot = target;
1639 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001640
Iain Merrick75681382010-08-19 15:07:18 +01001641 if (object_contents == POINTER_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001642 heap->promotion_queue()->insert(target, object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001643 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001644
Steve Block44f0eee2011-05-26 01:26:41 +01001645 heap->tracer()->increment_promoted_objects_size(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001646 return;
1647 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001648 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001649 MaybeObject* allocation = heap->new_space()->AllocateRaw(object_size);
1650 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1651 Object* result = allocation->ToObjectUnchecked();
1652 HeapObject* target = HeapObject::cast(result);
1653
1654 // Order is important: slot might be inside of the target if target
1655 // was allocated over a dead object and slot comes from the store
1656 // buffer.
1657 *slot = target;
1658 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001659 return;
1660 }
1661
Iain Merrick75681382010-08-19 15:07:18 +01001662
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001663 static inline void EvacuateJSFunction(Map* map,
1664 HeapObject** slot,
1665 HeapObject* object) {
1666 ObjectEvacuationStrategy<POINTER_OBJECT>::
1667 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1668
1669 HeapObject* target = *slot;
1670 MarkBit mark_bit = Marking::MarkBitFrom(target);
1671 if (Marking::IsBlack(mark_bit)) {
1672 // This object is black and it might not be rescanned by marker.
1673 // We should explicitly record code entry slot for compaction because
1674 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1675 // miss it as it is not HeapObject-tagged.
1676 Address code_entry_slot =
1677 target->address() + JSFunction::kCodeEntryOffset;
1678 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1679 map->GetHeap()->mark_compact_collector()->
1680 RecordCodeEntrySlot(code_entry_slot, code);
1681 }
1682 }
1683
1684
Iain Merrick75681382010-08-19 15:07:18 +01001685 static inline void EvacuateFixedArray(Map* map,
1686 HeapObject** slot,
1687 HeapObject* object) {
1688 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1689 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1690 slot,
1691 object,
1692 object_size);
1693 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001694
1695
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001696 static inline void EvacuateFixedDoubleArray(Map* map,
1697 HeapObject** slot,
1698 HeapObject* object) {
1699 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1700 int object_size = FixedDoubleArray::SizeFor(length);
1701 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1702 slot,
1703 object,
1704 object_size);
1705 }
1706
1707
Iain Merrick75681382010-08-19 15:07:18 +01001708 static inline void EvacuateByteArray(Map* map,
1709 HeapObject** slot,
1710 HeapObject* object) {
1711 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1712 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1713 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001714
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001715
Iain Merrick75681382010-08-19 15:07:18 +01001716 static inline void EvacuateSeqAsciiString(Map* map,
1717 HeapObject** slot,
1718 HeapObject* object) {
1719 int object_size = SeqAsciiString::cast(object)->
1720 SeqAsciiStringSize(map->instance_type());
1721 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1722 }
1723
1724
1725 static inline void EvacuateSeqTwoByteString(Map* map,
1726 HeapObject** slot,
1727 HeapObject* object) {
1728 int object_size = SeqTwoByteString::cast(object)->
1729 SeqTwoByteStringSize(map->instance_type());
1730 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1731 }
1732
1733
1734 static inline bool IsShortcutCandidate(int type) {
1735 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1736 }
1737
1738 static inline void EvacuateShortcutCandidate(Map* map,
1739 HeapObject** slot,
1740 HeapObject* object) {
1741 ASSERT(IsShortcutCandidate(map->instance_type()));
1742
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001743 Heap* heap = map->GetHeap();
1744
1745 if (marks_handling == IGNORE_MARKS &&
1746 ConsString::cast(object)->unchecked_second() ==
1747 heap->empty_string()) {
Iain Merrick75681382010-08-19 15:07:18 +01001748 HeapObject* first =
1749 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1750
1751 *slot = first;
1752
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001753 if (!heap->InNewSpace(first)) {
Iain Merrick75681382010-08-19 15:07:18 +01001754 object->set_map_word(MapWord::FromForwardingAddress(first));
1755 return;
1756 }
1757
1758 MapWord first_word = first->map_word();
1759 if (first_word.IsForwardingAddress()) {
1760 HeapObject* target = first_word.ToForwardingAddress();
1761
1762 *slot = target;
1763 object->set_map_word(MapWord::FromForwardingAddress(target));
1764 return;
1765 }
1766
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001767 heap->DoScavengeObject(first->map(), slot, first);
Iain Merrick75681382010-08-19 15:07:18 +01001768 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1769 return;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001770 }
Iain Merrick75681382010-08-19 15:07:18 +01001771
1772 int object_size = ConsString::kSize;
1773 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001774 }
1775
Iain Merrick75681382010-08-19 15:07:18 +01001776 template<ObjectContents object_contents>
1777 class ObjectEvacuationStrategy {
1778 public:
1779 template<int object_size>
1780 static inline void VisitSpecialized(Map* map,
1781 HeapObject** slot,
1782 HeapObject* object) {
1783 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1784 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001785
Iain Merrick75681382010-08-19 15:07:18 +01001786 static inline void Visit(Map* map,
1787 HeapObject** slot,
1788 HeapObject* object) {
1789 int object_size = map->instance_size();
1790 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1791 }
1792 };
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001793
Ben Murdoch8b112d22011-06-08 16:22:53 +01001794 static VisitorDispatchTable<ScavengingCallback> table_;
Iain Merrick75681382010-08-19 15:07:18 +01001795};
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001796
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001797
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001798template<MarksHandling marks_handling,
1799 LoggingAndProfiling logging_and_profiling_mode>
Ben Murdoch8b112d22011-06-08 16:22:53 +01001800VisitorDispatchTable<ScavengingCallback>
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001801 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001802
1803
1804static void InitializeScavengingVisitorsTables() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001805 ScavengingVisitor<TRANSFER_MARKS,
1806 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1807 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1808 ScavengingVisitor<TRANSFER_MARKS,
1809 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1810 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
Ben Murdoch8b112d22011-06-08 16:22:53 +01001811}
1812
1813
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001814void Heap::SelectScavengingVisitorsTable() {
1815 bool logging_and_profiling =
1816 isolate()->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001817 CpuProfiler::is_profiling(isolate()) ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01001818 (isolate()->heap_profiler() != NULL &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001819 isolate()->heap_profiler()->is_profiling());
Ben Murdoch8b112d22011-06-08 16:22:53 +01001820
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001821 if (!incremental_marking()->IsMarking()) {
1822 if (!logging_and_profiling) {
1823 scavenging_visitors_table_.CopyFrom(
1824 ScavengingVisitor<IGNORE_MARKS,
1825 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1826 } else {
1827 scavenging_visitors_table_.CopyFrom(
1828 ScavengingVisitor<IGNORE_MARKS,
1829 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1830 }
1831 } else {
1832 if (!logging_and_profiling) {
1833 scavenging_visitors_table_.CopyFrom(
1834 ScavengingVisitor<TRANSFER_MARKS,
1835 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1836 } else {
1837 scavenging_visitors_table_.CopyFrom(
1838 ScavengingVisitor<TRANSFER_MARKS,
1839 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1840 }
1841
1842 if (incremental_marking()->IsCompacting()) {
1843 // When compacting forbid short-circuiting of cons-strings.
1844 // Scavenging code relies on the fact that new space object
1845 // can't be evacuated into evacuation candidate but
1846 // short-circuiting violates this assumption.
1847 scavenging_visitors_table_.Register(
1848 StaticVisitorBase::kVisitShortcutCandidate,
1849 scavenging_visitors_table_.GetVisitorById(
1850 StaticVisitorBase::kVisitConsString));
1851 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001852 }
1853}
Steve Blocka7e24c12009-10-30 11:49:00 +00001854
1855
1856void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001857 SLOW_ASSERT(HEAP->InFromSpace(object));
Steve Blocka7e24c12009-10-30 11:49:00 +00001858 MapWord first_word = object->map_word();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001859 SLOW_ASSERT(!first_word.IsForwardingAddress());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001860 Map* map = first_word.ToMap();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001861 map->GetHeap()->DoScavengeObject(map, p, object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001862}
1863
1864
John Reck59135872010-11-02 12:39:01 -07001865MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1866 int instance_size) {
1867 Object* result;
1868 { MaybeObject* maybe_result = AllocateRawMap();
1869 if (!maybe_result->ToObject(&result)) return maybe_result;
1870 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001871
1872 // Map::cast cannot be used due to uninitialized map field.
1873 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1874 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1875 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
Steve Block44f0eee2011-05-26 01:26:41 +01001876 reinterpret_cast<Map*>(result)->set_visitor_id(
1877 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Steve Blocka7e24c12009-10-30 11:49:00 +00001878 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001879 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001880 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001881 reinterpret_cast<Map*>(result)->set_bit_field(0);
1882 reinterpret_cast<Map*>(result)->set_bit_field2(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001883 return result;
1884}
1885
1886
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001887MaybeObject* Heap::AllocateMap(InstanceType instance_type,
1888 int instance_size,
1889 ElementsKind elements_kind) {
John Reck59135872010-11-02 12:39:01 -07001890 Object* result;
1891 { MaybeObject* maybe_result = AllocateRawMap();
1892 if (!maybe_result->ToObject(&result)) return maybe_result;
1893 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001894
1895 Map* map = reinterpret_cast<Map*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00001896 map->set_map_no_write_barrier(meta_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00001897 map->set_instance_type(instance_type);
Iain Merrick75681382010-08-19 15:07:18 +01001898 map->set_visitor_id(
1899 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001900 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
1901 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001902 map->set_instance_size(instance_size);
1903 map->set_inobject_properties(0);
1904 map->set_pre_allocated_property_fields(0);
Ben Murdoch257744e2011-11-30 15:57:28 +00001905 map->init_instance_descriptors();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001906 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1907 map->set_prototype_transitions(empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001908 map->set_unused_property_fields(0);
1909 map->set_bit_field(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001910 map->set_bit_field2(1 << Map::kIsExtensible);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001911 map->set_elements_kind(elements_kind);
Leon Clarkee46be812010-01-19 14:06:41 +00001912
1913 // If the map object is aligned fill the padding area with Smi 0 objects.
1914 if (Map::kPadStart < Map::kSize) {
1915 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1916 0,
1917 Map::kSize - Map::kPadStart);
1918 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001919 return map;
1920}
1921
1922
John Reck59135872010-11-02 12:39:01 -07001923MaybeObject* Heap::AllocateCodeCache() {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01001924 CodeCache* code_cache;
1925 { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
1926 if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
John Reck59135872010-11-02 12:39:01 -07001927 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001928 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1929 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
Steve Block6ded16b2010-05-10 14:33:55 +01001930 return code_cache;
1931}
1932
1933
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001934MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1935 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1936}
1937
1938
Ben Murdochc7cc0282012-03-05 14:35:55 +00001939MaybeObject* Heap::AllocateAccessorPair() {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01001940 AccessorPair* accessors;
1941 { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
1942 if (!maybe_accessors->To(&accessors)) return maybe_accessors;
Ben Murdochc7cc0282012-03-05 14:35:55 +00001943 }
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01001944 accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
1945 accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
Ben Murdochc7cc0282012-03-05 14:35:55 +00001946 return accessors;
1947}
1948
1949
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01001950MaybeObject* Heap::AllocateTypeFeedbackInfo() {
1951 TypeFeedbackInfo* info;
1952 { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
1953 if (!maybe_info->To(&info)) return maybe_info;
1954 }
1955 info->set_ic_total_count(0);
1956 info->set_ic_with_typeinfo_count(0);
1957 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
1958 SKIP_WRITE_BARRIER);
1959 return info;
1960}
1961
1962
1963MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
1964 AliasedArgumentsEntry* entry;
1965 { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
1966 if (!maybe_entry->To(&entry)) return maybe_entry;
1967 }
1968 entry->set_aliased_context_slot(aliased_context_slot);
1969 return entry;
1970}
1971
1972
Steve Blocka7e24c12009-10-30 11:49:00 +00001973const Heap::StringTypeTable Heap::string_type_table[] = {
1974#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1975 {type, size, k##camel_name##MapRootIndex},
1976 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1977#undef STRING_TYPE_ELEMENT
1978};
1979
1980
1981const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1982#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1983 {contents, k##name##RootIndex},
1984 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1985#undef CONSTANT_SYMBOL_ELEMENT
1986};
1987
1988
1989const Heap::StructTable Heap::struct_table[] = {
1990#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1991 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1992 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1993#undef STRUCT_TABLE_ELEMENT
1994};
1995
1996
1997bool Heap::CreateInitialMaps() {
John Reck59135872010-11-02 12:39:01 -07001998 Object* obj;
1999 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2000 if (!maybe_obj->ToObject(&obj)) return false;
2001 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002002 // Map::cast cannot be used due to uninitialized map field.
2003 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2004 set_meta_map(new_meta_map);
2005 new_meta_map->set_map(new_meta_map);
2006
John Reck59135872010-11-02 12:39:01 -07002007 { MaybeObject* maybe_obj =
2008 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2009 if (!maybe_obj->ToObject(&obj)) return false;
2010 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002011 set_fixed_array_map(Map::cast(obj));
2012
John Reck59135872010-11-02 12:39:01 -07002013 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2014 if (!maybe_obj->ToObject(&obj)) return false;
2015 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002016 set_oddball_map(Map::cast(obj));
2017
Steve Block6ded16b2010-05-10 14:33:55 +01002018 // Allocate the empty array.
John Reck59135872010-11-02 12:39:01 -07002019 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2020 if (!maybe_obj->ToObject(&obj)) return false;
2021 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002022 set_empty_fixed_array(FixedArray::cast(obj));
2023
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002024 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07002025 if (!maybe_obj->ToObject(&obj)) return false;
2026 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002027 set_null_value(Oddball::cast(obj));
Steve Block44f0eee2011-05-26 01:26:41 +01002028 Oddball::cast(obj)->set_kind(Oddball::kNull);
Steve Blocka7e24c12009-10-30 11:49:00 +00002029
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002030 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2031 if (!maybe_obj->ToObject(&obj)) return false;
2032 }
2033 set_undefined_value(Oddball::cast(obj));
2034 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2035 ASSERT(!InNewSpace(undefined_value()));
2036
Steve Blocka7e24c12009-10-30 11:49:00 +00002037 // Allocate the empty descriptor array.
John Reck59135872010-11-02 12:39:01 -07002038 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2039 if (!maybe_obj->ToObject(&obj)) return false;
2040 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002041 set_empty_descriptor_array(DescriptorArray::cast(obj));
2042
2043 // Fix the instance_descriptors for the existing maps.
Ben Murdoch257744e2011-11-30 15:57:28 +00002044 meta_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00002045 meta_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01002046 meta_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002047
Ben Murdoch257744e2011-11-30 15:57:28 +00002048 fixed_array_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00002049 fixed_array_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01002050 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002051
Ben Murdoch257744e2011-11-30 15:57:28 +00002052 oddball_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00002053 oddball_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01002054 oddball_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002055
2056 // Fix prototype object for existing maps.
2057 meta_map()->set_prototype(null_value());
2058 meta_map()->set_constructor(null_value());
2059
2060 fixed_array_map()->set_prototype(null_value());
2061 fixed_array_map()->set_constructor(null_value());
2062
2063 oddball_map()->set_prototype(null_value());
2064 oddball_map()->set_constructor(null_value());
2065
John Reck59135872010-11-02 12:39:01 -07002066 { MaybeObject* maybe_obj =
2067 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2068 if (!maybe_obj->ToObject(&obj)) return false;
2069 }
Iain Merrick75681382010-08-19 15:07:18 +01002070 set_fixed_cow_array_map(Map::cast(obj));
2071 ASSERT(fixed_array_map() != fixed_cow_array_map());
2072
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002073 { MaybeObject* maybe_obj =
2074 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2075 if (!maybe_obj->ToObject(&obj)) return false;
2076 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002077 set_scope_info_map(Map::cast(obj));
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002078
John Reck59135872010-11-02 12:39:01 -07002079 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2080 if (!maybe_obj->ToObject(&obj)) return false;
2081 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002082 set_heap_number_map(Map::cast(obj));
2083
Ben Murdoch257744e2011-11-30 15:57:28 +00002084 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
John Reck59135872010-11-02 12:39:01 -07002085 if (!maybe_obj->ToObject(&obj)) return false;
2086 }
Ben Murdoch257744e2011-11-30 15:57:28 +00002087 set_foreign_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002088
2089 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2090 const StringTypeTable& entry = string_type_table[i];
John Reck59135872010-11-02 12:39:01 -07002091 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2092 if (!maybe_obj->ToObject(&obj)) return false;
2093 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002094 roots_[entry.index] = Map::cast(obj);
2095 }
2096
John Reck59135872010-11-02 12:39:01 -07002097 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2098 if (!maybe_obj->ToObject(&obj)) return false;
2099 }
Steve Blockd0582a62009-12-15 09:54:21 +00002100 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002101 Map::cast(obj)->set_is_undetectable();
2102
John Reck59135872010-11-02 12:39:01 -07002103 { MaybeObject* maybe_obj =
2104 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2105 if (!maybe_obj->ToObject(&obj)) return false;
2106 }
Steve Blockd0582a62009-12-15 09:54:21 +00002107 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002108 Map::cast(obj)->set_is_undetectable();
2109
John Reck59135872010-11-02 12:39:01 -07002110 { MaybeObject* maybe_obj =
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002111 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2112 if (!maybe_obj->ToObject(&obj)) return false;
2113 }
2114 set_fixed_double_array_map(Map::cast(obj));
2115
2116 { MaybeObject* maybe_obj =
John Reck59135872010-11-02 12:39:01 -07002117 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2118 if (!maybe_obj->ToObject(&obj)) return false;
2119 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002120 set_byte_array_map(Map::cast(obj));
2121
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002122 { MaybeObject* maybe_obj =
2123 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2124 if (!maybe_obj->ToObject(&obj)) return false;
2125 }
2126 set_free_space_map(Map::cast(obj));
2127
Ben Murdochb0fe1622011-05-05 13:52:32 +01002128 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2129 if (!maybe_obj->ToObject(&obj)) return false;
2130 }
2131 set_empty_byte_array(ByteArray::cast(obj));
2132
John Reck59135872010-11-02 12:39:01 -07002133 { MaybeObject* maybe_obj =
Steve Block44f0eee2011-05-26 01:26:41 +01002134 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
John Reck59135872010-11-02 12:39:01 -07002135 if (!maybe_obj->ToObject(&obj)) return false;
2136 }
Steve Block44f0eee2011-05-26 01:26:41 +01002137 set_external_pixel_array_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002138
John Reck59135872010-11-02 12:39:01 -07002139 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2140 ExternalArray::kAlignedSize);
2141 if (!maybe_obj->ToObject(&obj)) return false;
2142 }
Steve Block3ce2e202009-11-05 08:53:23 +00002143 set_external_byte_array_map(Map::cast(obj));
2144
John Reck59135872010-11-02 12:39:01 -07002145 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2146 ExternalArray::kAlignedSize);
2147 if (!maybe_obj->ToObject(&obj)) return false;
2148 }
Steve Block3ce2e202009-11-05 08:53:23 +00002149 set_external_unsigned_byte_array_map(Map::cast(obj));
2150
John Reck59135872010-11-02 12:39:01 -07002151 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2152 ExternalArray::kAlignedSize);
2153 if (!maybe_obj->ToObject(&obj)) return false;
2154 }
Steve Block3ce2e202009-11-05 08:53:23 +00002155 set_external_short_array_map(Map::cast(obj));
2156
John Reck59135872010-11-02 12:39:01 -07002157 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2158 ExternalArray::kAlignedSize);
2159 if (!maybe_obj->ToObject(&obj)) return false;
2160 }
Steve Block3ce2e202009-11-05 08:53:23 +00002161 set_external_unsigned_short_array_map(Map::cast(obj));
2162
John Reck59135872010-11-02 12:39:01 -07002163 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2164 ExternalArray::kAlignedSize);
2165 if (!maybe_obj->ToObject(&obj)) return false;
2166 }
Steve Block3ce2e202009-11-05 08:53:23 +00002167 set_external_int_array_map(Map::cast(obj));
2168
John Reck59135872010-11-02 12:39:01 -07002169 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2170 ExternalArray::kAlignedSize);
2171 if (!maybe_obj->ToObject(&obj)) return false;
2172 }
Steve Block3ce2e202009-11-05 08:53:23 +00002173 set_external_unsigned_int_array_map(Map::cast(obj));
2174
John Reck59135872010-11-02 12:39:01 -07002175 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2176 ExternalArray::kAlignedSize);
2177 if (!maybe_obj->ToObject(&obj)) return false;
2178 }
Steve Block3ce2e202009-11-05 08:53:23 +00002179 set_external_float_array_map(Map::cast(obj));
2180
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002181 { MaybeObject* maybe_obj =
2182 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2183 if (!maybe_obj->ToObject(&obj)) return false;
2184 }
2185 set_non_strict_arguments_elements_map(Map::cast(obj));
2186
Ben Murdoch257744e2011-11-30 15:57:28 +00002187 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2188 ExternalArray::kAlignedSize);
2189 if (!maybe_obj->ToObject(&obj)) return false;
2190 }
2191 set_external_double_array_map(Map::cast(obj));
2192
John Reck59135872010-11-02 12:39:01 -07002193 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2194 if (!maybe_obj->ToObject(&obj)) return false;
2195 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002196 set_code_map(Map::cast(obj));
2197
John Reck59135872010-11-02 12:39:01 -07002198 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2199 JSGlobalPropertyCell::kSize);
2200 if (!maybe_obj->ToObject(&obj)) return false;
2201 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002202 set_global_property_cell_map(Map::cast(obj));
2203
John Reck59135872010-11-02 12:39:01 -07002204 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2205 if (!maybe_obj->ToObject(&obj)) return false;
2206 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002207 set_one_pointer_filler_map(Map::cast(obj));
2208
John Reck59135872010-11-02 12:39:01 -07002209 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2210 if (!maybe_obj->ToObject(&obj)) return false;
2211 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002212 set_two_pointer_filler_map(Map::cast(obj));
2213
2214 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2215 const StructTable& entry = struct_table[i];
John Reck59135872010-11-02 12:39:01 -07002216 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2217 if (!maybe_obj->ToObject(&obj)) return false;
2218 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002219 roots_[entry.index] = Map::cast(obj);
2220 }
2221
John Reck59135872010-11-02 12:39:01 -07002222 { MaybeObject* maybe_obj =
2223 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2224 if (!maybe_obj->ToObject(&obj)) return false;
2225 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002226 set_hash_table_map(Map::cast(obj));
2227
John Reck59135872010-11-02 12:39:01 -07002228 { MaybeObject* maybe_obj =
2229 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2230 if (!maybe_obj->ToObject(&obj)) return false;
2231 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002232 set_function_context_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002233
John Reck59135872010-11-02 12:39:01 -07002234 { MaybeObject* maybe_obj =
2235 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2236 if (!maybe_obj->ToObject(&obj)) return false;
2237 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002238 set_catch_context_map(Map::cast(obj));
2239
John Reck59135872010-11-02 12:39:01 -07002240 { MaybeObject* maybe_obj =
2241 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2242 if (!maybe_obj->ToObject(&obj)) return false;
2243 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002244 set_with_context_map(Map::cast(obj));
2245
2246 { MaybeObject* maybe_obj =
2247 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2248 if (!maybe_obj->ToObject(&obj)) return false;
2249 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002250 set_block_context_map(Map::cast(obj));
2251
2252 { MaybeObject* maybe_obj =
2253 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2254 if (!maybe_obj->ToObject(&obj)) return false;
2255 }
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002256 set_module_context_map(Map::cast(obj));
2257
2258 { MaybeObject* maybe_obj =
2259 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2260 if (!maybe_obj->ToObject(&obj)) return false;
2261 }
Ben Murdochf87a2032010-10-22 12:50:53 +01002262 Map* global_context_map = Map::cast(obj);
2263 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2264 set_global_context_map(global_context_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002265
John Reck59135872010-11-02 12:39:01 -07002266 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2267 SharedFunctionInfo::kAlignedSize);
2268 if (!maybe_obj->ToObject(&obj)) return false;
2269 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002270 set_shared_function_info_map(Map::cast(obj));
2271
Steve Block1e0659c2011-05-24 12:43:12 +01002272 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2273 JSMessageObject::kSize);
2274 if (!maybe_obj->ToObject(&obj)) return false;
2275 }
2276 set_message_object_map(Map::cast(obj));
2277
Steve Block44f0eee2011-05-26 01:26:41 +01002278 ASSERT(!InNewSpace(empty_fixed_array()));
Steve Blocka7e24c12009-10-30 11:49:00 +00002279 return true;
2280}
2281
2282
John Reck59135872010-11-02 12:39:01 -07002283MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002284 // Statically ensure that it is safe to allocate heap numbers in paged
2285 // spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002286 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002287 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2288
John Reck59135872010-11-02 12:39:01 -07002289 Object* result;
2290 { MaybeObject* maybe_result =
2291 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2292 if (!maybe_result->ToObject(&result)) return maybe_result;
2293 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002294
Ben Murdochc7cc0282012-03-05 14:35:55 +00002295 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002296 HeapNumber::cast(result)->set_value(value);
2297 return result;
2298}
2299
2300
John Reck59135872010-11-02 12:39:01 -07002301MaybeObject* Heap::AllocateHeapNumber(double value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002302 // Use general version, if we're forced to always allocate.
2303 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2304
2305 // This version of AllocateHeapNumber is optimized for
2306 // allocation in new space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002307 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002308 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
John Reck59135872010-11-02 12:39:01 -07002309 Object* result;
2310 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2311 if (!maybe_result->ToObject(&result)) return maybe_result;
2312 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002313 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002314 HeapNumber::cast(result)->set_value(value);
2315 return result;
2316}
2317
2318
John Reck59135872010-11-02 12:39:01 -07002319MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2320 Object* result;
2321 { MaybeObject* maybe_result = AllocateRawCell();
2322 if (!maybe_result->ToObject(&result)) return maybe_result;
2323 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002324 HeapObject::cast(result)->set_map_no_write_barrier(
2325 global_property_cell_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002326 JSGlobalPropertyCell::cast(result)->set_value(value);
2327 return result;
2328}
2329
2330
John Reck59135872010-11-02 12:39:01 -07002331MaybeObject* Heap::CreateOddball(const char* to_string,
Steve Block44f0eee2011-05-26 01:26:41 +01002332 Object* to_number,
2333 byte kind) {
John Reck59135872010-11-02 12:39:01 -07002334 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002335 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07002336 if (!maybe_result->ToObject(&result)) return maybe_result;
2337 }
Steve Block44f0eee2011-05-26 01:26:41 +01002338 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
Steve Blocka7e24c12009-10-30 11:49:00 +00002339}
2340
2341
2342bool Heap::CreateApiObjects() {
2343 Object* obj;
2344
John Reck59135872010-11-02 12:39:01 -07002345 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2346 if (!maybe_obj->ToObject(&obj)) return false;
2347 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002348 // Don't use Smi-only elements optimizations for objects with the neander
2349 // map. There are too many cases where element values are set directly with a
2350 // bottleneck to trap the Smi-only -> fast elements transition, and there
2351 // appears to be no benefit for optimize this case.
2352 Map* new_neander_map = Map::cast(obj);
2353 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2354 set_neander_map(new_neander_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002355
Steve Block44f0eee2011-05-26 01:26:41 +01002356 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
John Reck59135872010-11-02 12:39:01 -07002357 if (!maybe_obj->ToObject(&obj)) return false;
2358 }
2359 Object* elements;
2360 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2361 if (!maybe_elements->ToObject(&elements)) return false;
2362 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002363 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2364 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2365 set_message_listeners(JSObject::cast(obj));
2366
2367 return true;
2368}
2369
2370
Steve Blocka7e24c12009-10-30 11:49:00 +00002371void Heap::CreateJSEntryStub() {
2372 JSEntryStub stub;
2373 set_js_entry_code(*stub.GetCode());
2374}
2375
2376
2377void Heap::CreateJSConstructEntryStub() {
2378 JSConstructEntryStub stub;
2379 set_js_construct_entry_code(*stub.GetCode());
2380}
2381
2382
2383void Heap::CreateFixedStubs() {
2384 // Here we create roots for fixed stubs. They are needed at GC
2385 // for cooking and uncooking (check out frames.cc).
2386 // The eliminates the need for doing dictionary lookup in the
2387 // stub cache for these stubs.
2388 HandleScope scope;
2389 // gcc-4.4 has problem generating correct code of following snippet:
Steve Block44f0eee2011-05-26 01:26:41 +01002390 // { JSEntryStub stub;
2391 // js_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002392 // }
Steve Block44f0eee2011-05-26 01:26:41 +01002393 // { JSConstructEntryStub stub;
2394 // js_construct_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002395 // }
2396 // To workaround the problem, make separate functions without inlining.
Steve Blocka7e24c12009-10-30 11:49:00 +00002397 Heap::CreateJSEntryStub();
2398 Heap::CreateJSConstructEntryStub();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002399
2400 // Create stubs that should be there, so we don't unexpectedly have to
2401 // create them if we need them during the creation of another stub.
2402 // Stub creation mixes raw pointers and handles in an unsafe manner so
2403 // we cannot create stubs while we are creating stubs.
2404 CodeStub::GenerateStubsAheadOfTime();
Steve Blocka7e24c12009-10-30 11:49:00 +00002405}
2406
2407
2408bool Heap::CreateInitialObjects() {
2409 Object* obj;
2410
2411 // The -0 value must be set before NumberFromDouble works.
John Reck59135872010-11-02 12:39:01 -07002412 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2413 if (!maybe_obj->ToObject(&obj)) return false;
2414 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002415 set_minus_zero_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002416 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2417
John Reck59135872010-11-02 12:39:01 -07002418 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2419 if (!maybe_obj->ToObject(&obj)) return false;
2420 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002421 set_nan_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002422
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002423 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
John Reck59135872010-11-02 12:39:01 -07002424 if (!maybe_obj->ToObject(&obj)) return false;
2425 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002426 set_infinity_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002427
Ben Murdochc7cc0282012-03-05 14:35:55 +00002428 // The hole has not been created yet, but we want to put something
2429 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2430 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2431
Steve Blocka7e24c12009-10-30 11:49:00 +00002432 // Allocate initial symbol table.
John Reck59135872010-11-02 12:39:01 -07002433 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2434 if (!maybe_obj->ToObject(&obj)) return false;
2435 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002436 // Don't use set_symbol_table() due to asserts.
2437 roots_[kSymbolTableRootIndex] = obj;
2438
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002439 // Finish initializing oddballs after creating symboltable.
John Reck59135872010-11-02 12:39:01 -07002440 { MaybeObject* maybe_obj =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002441 undefined_value()->Initialize("undefined",
2442 nan_value(),
2443 Oddball::kUndefined);
2444 if (!maybe_obj->ToObject(&obj)) return false;
2445 }
2446
2447 // Initialize the null_value.
2448 { MaybeObject* maybe_obj =
2449 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
John Reck59135872010-11-02 12:39:01 -07002450 if (!maybe_obj->ToObject(&obj)) return false;
2451 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002452
Steve Block44f0eee2011-05-26 01:26:41 +01002453 { MaybeObject* maybe_obj = CreateOddball("true",
2454 Smi::FromInt(1),
2455 Oddball::kTrue);
John Reck59135872010-11-02 12:39:01 -07002456 if (!maybe_obj->ToObject(&obj)) return false;
2457 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002458 set_true_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002459
Steve Block44f0eee2011-05-26 01:26:41 +01002460 { MaybeObject* maybe_obj = CreateOddball("false",
2461 Smi::FromInt(0),
2462 Oddball::kFalse);
John Reck59135872010-11-02 12:39:01 -07002463 if (!maybe_obj->ToObject(&obj)) return false;
2464 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002465 set_false_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002466
Steve Block44f0eee2011-05-26 01:26:41 +01002467 { MaybeObject* maybe_obj = CreateOddball("hole",
2468 Smi::FromInt(-1),
2469 Oddball::kTheHole);
John Reck59135872010-11-02 12:39:01 -07002470 if (!maybe_obj->ToObject(&obj)) return false;
2471 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002472 set_the_hole_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002473
Ben Murdoch086aeea2011-05-13 15:57:08 +01002474 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002475 Smi::FromInt(-4),
Steve Block44f0eee2011-05-26 01:26:41 +01002476 Oddball::kArgumentMarker);
Ben Murdoch086aeea2011-05-13 15:57:08 +01002477 if (!maybe_obj->ToObject(&obj)) return false;
2478 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002479 set_arguments_marker(Oddball::cast(obj));
Ben Murdoch086aeea2011-05-13 15:57:08 +01002480
Steve Block44f0eee2011-05-26 01:26:41 +01002481 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002482 Smi::FromInt(-2),
Steve Block44f0eee2011-05-26 01:26:41 +01002483 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002484 if (!maybe_obj->ToObject(&obj)) return false;
2485 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002486 set_no_interceptor_result_sentinel(obj);
2487
Steve Block44f0eee2011-05-26 01:26:41 +01002488 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002489 Smi::FromInt(-3),
Steve Block44f0eee2011-05-26 01:26:41 +01002490 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002491 if (!maybe_obj->ToObject(&obj)) return false;
2492 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002493 set_termination_exception(obj);
2494
2495 // Allocate the empty string.
John Reck59135872010-11-02 12:39:01 -07002496 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2497 if (!maybe_obj->ToObject(&obj)) return false;
2498 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002499 set_empty_string(String::cast(obj));
2500
2501 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
John Reck59135872010-11-02 12:39:01 -07002502 { MaybeObject* maybe_obj =
2503 LookupAsciiSymbol(constant_symbol_table[i].contents);
2504 if (!maybe_obj->ToObject(&obj)) return false;
2505 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002506 roots_[constant_symbol_table[i].index] = String::cast(obj);
2507 }
2508
2509 // Allocate the hidden symbol which is used to identify the hidden properties
2510 // in JSObjects. The hash code has a special value so that it will not match
2511 // the empty string when searching for the property. It cannot be part of the
2512 // loop above because it needs to be allocated manually with the special
2513 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2514 // that it will always be at the first entry in property descriptors.
John Reck59135872010-11-02 12:39:01 -07002515 { MaybeObject* maybe_obj =
2516 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2517 if (!maybe_obj->ToObject(&obj)) return false;
2518 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002519 hidden_symbol_ = String::cast(obj);
2520
Ben Murdoch257744e2011-11-30 15:57:28 +00002521 // Allocate the foreign for __proto__.
John Reck59135872010-11-02 12:39:01 -07002522 { MaybeObject* maybe_obj =
Ben Murdoch257744e2011-11-30 15:57:28 +00002523 AllocateForeign((Address) &Accessors::ObjectPrototype);
John Reck59135872010-11-02 12:39:01 -07002524 if (!maybe_obj->ToObject(&obj)) return false;
2525 }
Ben Murdoch257744e2011-11-30 15:57:28 +00002526 set_prototype_accessors(Foreign::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002527
2528 // Allocate the code_stubs dictionary. The initial size is set to avoid
2529 // expanding the dictionary during bootstrapping.
Ben Murdochc7cc0282012-03-05 14:35:55 +00002530 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
John Reck59135872010-11-02 12:39:01 -07002531 if (!maybe_obj->ToObject(&obj)) return false;
2532 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002533 set_code_stubs(UnseededNumberDictionary::cast(obj));
2534
Steve Blocka7e24c12009-10-30 11:49:00 +00002535
2536 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2537 // is set to avoid expanding the dictionary during bootstrapping.
Ben Murdochc7cc0282012-03-05 14:35:55 +00002538 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
John Reck59135872010-11-02 12:39:01 -07002539 if (!maybe_obj->ToObject(&obj)) return false;
2540 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002541 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002542
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002543 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2544 if (!maybe_obj->ToObject(&obj)) return false;
2545 }
2546 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2547
Kristian Monsen25f61362010-05-21 11:50:48 +01002548 set_instanceof_cache_function(Smi::FromInt(0));
2549 set_instanceof_cache_map(Smi::FromInt(0));
2550 set_instanceof_cache_answer(Smi::FromInt(0));
2551
Steve Blocka7e24c12009-10-30 11:49:00 +00002552 CreateFixedStubs();
2553
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002554 // Allocate the dictionary of intrinsic function names.
John Reck59135872010-11-02 12:39:01 -07002555 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2556 if (!maybe_obj->ToObject(&obj)) return false;
2557 }
Steve Block44f0eee2011-05-26 01:26:41 +01002558 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2559 obj);
John Reck59135872010-11-02 12:39:01 -07002560 if (!maybe_obj->ToObject(&obj)) return false;
2561 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002562 set_intrinsic_function_names(StringDictionary::cast(obj));
2563
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002564 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2565 if (!maybe_obj->ToObject(&obj)) return false;
2566 }
2567 set_number_string_cache(FixedArray::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002568
Steve Block6ded16b2010-05-10 14:33:55 +01002569 // Allocate cache for single character ASCII strings.
John Reck59135872010-11-02 12:39:01 -07002570 { MaybeObject* maybe_obj =
2571 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2572 if (!maybe_obj->ToObject(&obj)) return false;
2573 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002574 set_single_character_string_cache(FixedArray::cast(obj));
2575
Ben Murdoch589d6972011-11-30 16:04:58 +00002576 // Allocate cache for string split.
2577 { MaybeObject* maybe_obj =
2578 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2579 if (!maybe_obj->ToObject(&obj)) return false;
2580 }
2581 set_string_split_cache(FixedArray::cast(obj));
2582
Steve Blocka7e24c12009-10-30 11:49:00 +00002583 // Allocate cache for external strings pointing to native source code.
John Reck59135872010-11-02 12:39:01 -07002584 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2585 if (!maybe_obj->ToObject(&obj)) return false;
2586 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002587 set_natives_source_cache(FixedArray::cast(obj));
2588
Steve Block44f0eee2011-05-26 01:26:41 +01002589 // Handling of script id generation is in FACTORY->NewScript.
Steve Blocka7e24c12009-10-30 11:49:00 +00002590 set_last_script_id(undefined_value());
2591
2592 // Initialize keyed lookup cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002593 isolate_->keyed_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002594
2595 // Initialize context slot cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002596 isolate_->context_slot_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002597
2598 // Initialize descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002599 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002600
2601 // Initialize compilation cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002602 isolate_->compilation_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002603
2604 return true;
2605}
2606
2607
Ben Murdoch589d6972011-11-30 16:04:58 +00002608Object* StringSplitCache::Lookup(
2609 FixedArray* cache, String* string, String* pattern) {
2610 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2611 uint32_t hash = string->Hash();
2612 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2613 ~(kArrayEntriesPerCacheEntry - 1));
2614 if (cache->get(index + kStringOffset) == string &&
2615 cache->get(index + kPatternOffset) == pattern) {
2616 return cache->get(index + kArrayOffset);
2617 }
2618 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2619 if (cache->get(index + kStringOffset) == string &&
2620 cache->get(index + kPatternOffset) == pattern) {
2621 return cache->get(index + kArrayOffset);
2622 }
2623 return Smi::FromInt(0);
2624}
2625
2626
2627void StringSplitCache::Enter(Heap* heap,
2628 FixedArray* cache,
2629 String* string,
2630 String* pattern,
2631 FixedArray* array) {
2632 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2633 uint32_t hash = string->Hash();
2634 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2635 ~(kArrayEntriesPerCacheEntry - 1));
2636 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2637 cache->set(index + kStringOffset, string);
2638 cache->set(index + kPatternOffset, pattern);
2639 cache->set(index + kArrayOffset, array);
2640 } else {
2641 uint32_t index2 =
2642 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2643 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2644 cache->set(index2 + kStringOffset, string);
2645 cache->set(index2 + kPatternOffset, pattern);
2646 cache->set(index2 + kArrayOffset, array);
2647 } else {
2648 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2649 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2650 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2651 cache->set(index + kStringOffset, string);
2652 cache->set(index + kPatternOffset, pattern);
2653 cache->set(index + kArrayOffset, array);
2654 }
2655 }
2656 if (array->length() < 100) { // Limit how many new symbols we want to make.
2657 for (int i = 0; i < array->length(); i++) {
2658 String* str = String::cast(array->get(i));
2659 Object* symbol;
2660 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2661 if (maybe_symbol->ToObject(&symbol)) {
2662 array->set(i, symbol);
2663 }
2664 }
2665 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00002666 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
Ben Murdoch589d6972011-11-30 16:04:58 +00002667}
2668
2669
2670void StringSplitCache::Clear(FixedArray* cache) {
2671 for (int i = 0; i < kStringSplitCacheSize; i++) {
2672 cache->set(i, Smi::FromInt(0));
2673 }
2674}
2675
2676
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002677MaybeObject* Heap::AllocateInitialNumberStringCache() {
John Reck59135872010-11-02 12:39:01 -07002678 MaybeObject* maybe_obj =
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002679 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
John Reck59135872010-11-02 12:39:01 -07002680 return maybe_obj;
Leon Clarkee46be812010-01-19 14:06:41 +00002681}
2682
2683
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002684int Heap::FullSizeNumberStringCacheLength() {
2685 // Compute the size of the number string cache based on the max newspace size.
2686 // The number string cache has a minimum size based on twice the initial cache
2687 // size to ensure that it is bigger after being made 'full size'.
2688 int number_string_cache_size = max_semispace_size_ / 512;
2689 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2690 Min(0x4000, number_string_cache_size));
2691 // There is a string and a number per entry so the length is twice the number
2692 // of entries.
2693 return number_string_cache_size * 2;
2694}
2695
2696
2697void Heap::AllocateFullSizeNumberStringCache() {
2698 // The idea is to have a small number string cache in the snapshot to keep
2699 // boot-time memory usage down. If we expand the number string cache already
2700 // while creating the snapshot then that didn't work out.
2701 ASSERT(!Serializer::enabled());
2702 MaybeObject* maybe_obj =
2703 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2704 Object* new_cache;
2705 if (maybe_obj->ToObject(&new_cache)) {
2706 // We don't bother to repopulate the cache with entries from the old cache.
2707 // It will be repopulated soon enough with new strings.
2708 set_number_string_cache(FixedArray::cast(new_cache));
2709 }
2710 // If allocation fails then we just return without doing anything. It is only
2711 // a cache, so best effort is OK here.
2712}
2713
2714
Leon Clarkee46be812010-01-19 14:06:41 +00002715void Heap::FlushNumberStringCache() {
2716 // Flush the number to string cache.
2717 int len = number_string_cache()->length();
2718 for (int i = 0; i < len; i++) {
Steve Block44f0eee2011-05-26 01:26:41 +01002719 number_string_cache()->set_undefined(this, i);
Leon Clarkee46be812010-01-19 14:06:41 +00002720 }
2721}
2722
2723
Steve Blocka7e24c12009-10-30 11:49:00 +00002724static inline int double_get_hash(double d) {
2725 DoubleRepresentation rep(d);
Leon Clarkee46be812010-01-19 14:06:41 +00002726 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
Steve Blocka7e24c12009-10-30 11:49:00 +00002727}
2728
2729
2730static inline int smi_get_hash(Smi* smi) {
Leon Clarkee46be812010-01-19 14:06:41 +00002731 return smi->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002732}
2733
2734
Steve Blocka7e24c12009-10-30 11:49:00 +00002735Object* Heap::GetNumberStringCache(Object* number) {
2736 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002737 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002738 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002739 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002740 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002741 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002742 }
2743 Object* key = number_string_cache()->get(hash * 2);
2744 if (key == number) {
2745 return String::cast(number_string_cache()->get(hash * 2 + 1));
2746 } else if (key->IsHeapNumber() &&
2747 number->IsHeapNumber() &&
2748 key->Number() == number->Number()) {
2749 return String::cast(number_string_cache()->get(hash * 2 + 1));
2750 }
2751 return undefined_value();
2752}
2753
2754
2755void Heap::SetNumberStringCache(Object* number, String* string) {
2756 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002757 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002758 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002759 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002760 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002761 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002762 }
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002763 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2764 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2765 // The first time we have a hash collision, we move to the full sized
2766 // number string cache.
2767 AllocateFullSizeNumberStringCache();
2768 return;
2769 }
2770 number_string_cache()->set(hash * 2, number);
Steve Blocka7e24c12009-10-30 11:49:00 +00002771 number_string_cache()->set(hash * 2 + 1, string);
2772}
2773
2774
John Reck59135872010-11-02 12:39:01 -07002775MaybeObject* Heap::NumberToString(Object* number,
2776 bool check_number_string_cache) {
Steve Block44f0eee2011-05-26 01:26:41 +01002777 isolate_->counters()->number_to_string_runtime()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002778 if (check_number_string_cache) {
2779 Object* cached = GetNumberStringCache(number);
2780 if (cached != undefined_value()) {
2781 return cached;
2782 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002783 }
2784
2785 char arr[100];
2786 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2787 const char* str;
2788 if (number->IsSmi()) {
2789 int num = Smi::cast(number)->value();
2790 str = IntToCString(num, buffer);
2791 } else {
2792 double num = HeapNumber::cast(number)->value();
2793 str = DoubleToCString(num, buffer);
2794 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002795
John Reck59135872010-11-02 12:39:01 -07002796 Object* js_string;
2797 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2798 if (maybe_js_string->ToObject(&js_string)) {
2799 SetNumberStringCache(number, String::cast(js_string));
Steve Blocka7e24c12009-10-30 11:49:00 +00002800 }
John Reck59135872010-11-02 12:39:01 -07002801 return maybe_js_string;
Steve Blocka7e24c12009-10-30 11:49:00 +00002802}
2803
2804
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002805MaybeObject* Heap::Uint32ToString(uint32_t value,
2806 bool check_number_string_cache) {
2807 Object* number;
2808 MaybeObject* maybe = NumberFromUint32(value);
2809 if (!maybe->To<Object>(&number)) return maybe;
2810 return NumberToString(number, check_number_string_cache);
2811}
2812
2813
Steve Block3ce2e202009-11-05 08:53:23 +00002814Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2815 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2816}
2817
2818
2819Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2820 ExternalArrayType array_type) {
2821 switch (array_type) {
2822 case kExternalByteArray:
2823 return kExternalByteArrayMapRootIndex;
2824 case kExternalUnsignedByteArray:
2825 return kExternalUnsignedByteArrayMapRootIndex;
2826 case kExternalShortArray:
2827 return kExternalShortArrayMapRootIndex;
2828 case kExternalUnsignedShortArray:
2829 return kExternalUnsignedShortArrayMapRootIndex;
2830 case kExternalIntArray:
2831 return kExternalIntArrayMapRootIndex;
2832 case kExternalUnsignedIntArray:
2833 return kExternalUnsignedIntArrayMapRootIndex;
2834 case kExternalFloatArray:
2835 return kExternalFloatArrayMapRootIndex;
Ben Murdoch257744e2011-11-30 15:57:28 +00002836 case kExternalDoubleArray:
2837 return kExternalDoubleArrayMapRootIndex;
Steve Block44f0eee2011-05-26 01:26:41 +01002838 case kExternalPixelArray:
2839 return kExternalPixelArrayMapRootIndex;
Steve Block3ce2e202009-11-05 08:53:23 +00002840 default:
2841 UNREACHABLE();
2842 return kUndefinedValueRootIndex;
2843 }
2844}
2845
2846
John Reck59135872010-11-02 12:39:01 -07002847MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01002848 // We need to distinguish the minus zero value and this cannot be
2849 // done after conversion to int. Doing this by comparing bit
2850 // patterns is faster than using fpclassify() et al.
2851 static const DoubleRepresentation minus_zero(-0.0);
2852
2853 DoubleRepresentation rep(value);
2854 if (rep.bits == minus_zero.bits) {
2855 return AllocateHeapNumber(-0.0, pretenure);
2856 }
2857
2858 int int_value = FastD2I(value);
2859 if (value == int_value && Smi::IsValid(int_value)) {
2860 return Smi::FromInt(int_value);
2861 }
2862
2863 // Materialize the value in the heap.
2864 return AllocateHeapNumber(value, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00002865}
2866
2867
Ben Murdoch257744e2011-11-30 15:57:28 +00002868MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2869 // Statically ensure that it is safe to allocate foreigns in paged spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002870 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002871 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002872 Foreign* result;
2873 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2874 if (!maybe_result->To(&result)) return maybe_result;
2875 result->set_foreign_address(address);
Steve Blocka7e24c12009-10-30 11:49:00 +00002876 return result;
2877}
2878
2879
John Reck59135872010-11-02 12:39:01 -07002880MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002881 SharedFunctionInfo* share;
2882 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2883 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
Steve Blocka7e24c12009-10-30 11:49:00 +00002884
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002885 // Set pointer fields.
Steve Blocka7e24c12009-10-30 11:49:00 +00002886 share->set_name(name);
Steve Block44f0eee2011-05-26 01:26:41 +01002887 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
Steve Blocka7e24c12009-10-30 11:49:00 +00002888 share->set_code(illegal);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002889 share->set_scope_info(ScopeInfo::Empty());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002890 Code* construct_stub =
2891 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
Steve Blocka7e24c12009-10-30 11:49:00 +00002892 share->set_construct_stub(construct_stub);
Steve Blocka7e24c12009-10-30 11:49:00 +00002893 share->set_instance_class_name(Object_symbol());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002894 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
2895 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
2896 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
2897 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
2898 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
2899 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01002900 share->set_deopt_counter(FLAG_deopt_every_n_times);
2901 share->set_profiler_ticks(0);
2902 share->set_ast_node_count(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002903
2904 // Set integer fields (smi or int, depending on the architecture).
2905 share->set_length(0);
2906 share->set_formal_parameter_count(0);
2907 share->set_expected_nof_properties(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002908 share->set_num_literals(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002909 share->set_start_position_and_type(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002910 share->set_end_position(0);
2911 share->set_function_token_position(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002912 // All compiler hints default to false or 0.
2913 share->set_compiler_hints(0);
2914 share->set_this_property_assignments_count(0);
2915 share->set_opt_count(0);
2916
2917 return share;
Steve Blocka7e24c12009-10-30 11:49:00 +00002918}
2919
2920
Steve Block1e0659c2011-05-24 12:43:12 +01002921MaybeObject* Heap::AllocateJSMessageObject(String* type,
2922 JSArray* arguments,
2923 int start_position,
2924 int end_position,
2925 Object* script,
2926 Object* stack_trace,
2927 Object* stack_frames) {
2928 Object* result;
2929 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2930 if (!maybe_result->ToObject(&result)) return maybe_result;
2931 }
2932 JSMessageObject* message = JSMessageObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002933 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2934 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Block1e0659c2011-05-24 12:43:12 +01002935 message->set_type(type);
2936 message->set_arguments(arguments);
2937 message->set_start_position(start_position);
2938 message->set_end_position(end_position);
2939 message->set_script(script);
2940 message->set_stack_trace(stack_trace);
2941 message->set_stack_frames(stack_frames);
2942 return result;
2943}
2944
2945
2946
Steve Blockd0582a62009-12-15 09:54:21 +00002947// Returns true for a character in a range. Both limits are inclusive.
2948static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2949 // This makes uses of the the unsigned wraparound.
2950 return character - from <= to - from;
2951}
2952
2953
John Reck59135872010-11-02 12:39:01 -07002954MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
Steve Block44f0eee2011-05-26 01:26:41 +01002955 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07002956 uint32_t c1,
2957 uint32_t c2) {
Steve Blockd0582a62009-12-15 09:54:21 +00002958 String* symbol;
2959 // Numeric strings have a different hash algorithm not known by
2960 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2961 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
Steve Block44f0eee2011-05-26 01:26:41 +01002962 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
Steve Blockd0582a62009-12-15 09:54:21 +00002963 return symbol;
2964 // Now we know the length is 2, we might as well make use of that fact
2965 // when building the new string.
2966 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2967 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
John Reck59135872010-11-02 12:39:01 -07002968 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002969 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
John Reck59135872010-11-02 12:39:01 -07002970 if (!maybe_result->ToObject(&result)) return maybe_result;
2971 }
Steve Blockd0582a62009-12-15 09:54:21 +00002972 char* dest = SeqAsciiString::cast(result)->GetChars();
2973 dest[0] = c1;
2974 dest[1] = c2;
2975 return result;
2976 } else {
John Reck59135872010-11-02 12:39:01 -07002977 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002978 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
John Reck59135872010-11-02 12:39:01 -07002979 if (!maybe_result->ToObject(&result)) return maybe_result;
2980 }
Steve Blockd0582a62009-12-15 09:54:21 +00002981 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2982 dest[0] = c1;
2983 dest[1] = c2;
2984 return result;
2985 }
2986}
2987
2988
John Reck59135872010-11-02 12:39:01 -07002989MaybeObject* Heap::AllocateConsString(String* first, String* second) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002990 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002991 if (first_length == 0) {
2992 return second;
2993 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002994
2995 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002996 if (second_length == 0) {
2997 return first;
2998 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002999
3000 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00003001
3002 // Optimization for 2-byte strings often used as keys in a decompression
3003 // dictionary. Check whether we already have the string in the symbol
3004 // table to prevent creation of many unneccesary strings.
3005 if (length == 2) {
3006 unsigned c1 = first->Get(0);
3007 unsigned c2 = second->Get(0);
Steve Block44f0eee2011-05-26 01:26:41 +01003008 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blockd0582a62009-12-15 09:54:21 +00003009 }
3010
Steve Block6ded16b2010-05-10 14:33:55 +01003011 bool first_is_ascii = first->IsAsciiRepresentation();
3012 bool second_is_ascii = second->IsAsciiRepresentation();
3013 bool is_ascii = first_is_ascii && second_is_ascii;
Steve Blocka7e24c12009-10-30 11:49:00 +00003014
3015 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00003016 // of the new cons string is too large.
3017 if (length > String::kMaxLength || length < 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01003018 isolate()->context()->mark_out_of_memory();
Steve Blocka7e24c12009-10-30 11:49:00 +00003019 return Failure::OutOfMemoryException();
3020 }
3021
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003022 bool is_ascii_data_in_two_byte_string = false;
3023 if (!is_ascii) {
3024 // At least one of the strings uses two-byte representation so we
Ben Murdochc7cc0282012-03-05 14:35:55 +00003025 // can't use the fast case code for short ASCII strings below, but
3026 // we can try to save memory if all chars actually fit in ASCII.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003027 is_ascii_data_in_two_byte_string =
3028 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3029 if (is_ascii_data_in_two_byte_string) {
Steve Block44f0eee2011-05-26 01:26:41 +01003030 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003031 }
3032 }
3033
Steve Blocka7e24c12009-10-30 11:49:00 +00003034 // If the resulting string is small make a flat string.
Ben Murdochc7cc0282012-03-05 14:35:55 +00003035 if (length < ConsString::kMinLength) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003036 // Note that neither of the two inputs can be a slice because:
Ben Murdochc7cc0282012-03-05 14:35:55 +00003037 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
Steve Blocka7e24c12009-10-30 11:49:00 +00003038 ASSERT(first->IsFlat());
3039 ASSERT(second->IsFlat());
3040 if (is_ascii) {
John Reck59135872010-11-02 12:39:01 -07003041 Object* result;
3042 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3043 if (!maybe_result->ToObject(&result)) return maybe_result;
3044 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003045 // Copy the characters into the new object.
3046 char* dest = SeqAsciiString::cast(result)->GetChars();
3047 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00003048 const char* src;
3049 if (first->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003050 src = ExternalAsciiString::cast(first)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00003051 } else {
3052 src = SeqAsciiString::cast(first)->GetChars();
3053 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003054 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3055 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00003056 if (second->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003057 src = ExternalAsciiString::cast(second)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00003058 } else {
3059 src = SeqAsciiString::cast(second)->GetChars();
3060 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003061 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3062 return result;
3063 } else {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003064 if (is_ascii_data_in_two_byte_string) {
John Reck59135872010-11-02 12:39:01 -07003065 Object* result;
3066 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3067 if (!maybe_result->ToObject(&result)) return maybe_result;
3068 }
Steve Block6ded16b2010-05-10 14:33:55 +01003069 // Copy the characters into the new object.
3070 char* dest = SeqAsciiString::cast(result)->GetChars();
3071 String::WriteToFlat(first, dest, 0, first_length);
3072 String::WriteToFlat(second, dest + first_length, 0, second_length);
Steve Block44f0eee2011-05-26 01:26:41 +01003073 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01003074 return result;
3075 }
3076
John Reck59135872010-11-02 12:39:01 -07003077 Object* result;
3078 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3079 if (!maybe_result->ToObject(&result)) return maybe_result;
3080 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003081 // Copy the characters into the new object.
3082 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3083 String::WriteToFlat(first, dest, 0, first_length);
3084 String::WriteToFlat(second, dest + first_length, 0, second_length);
3085 return result;
3086 }
3087 }
3088
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003089 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3090 cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00003091
John Reck59135872010-11-02 12:39:01 -07003092 Object* result;
3093 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3094 if (!maybe_result->ToObject(&result)) return maybe_result;
3095 }
Leon Clarke4515c472010-02-03 11:58:03 +00003096
3097 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003098 ConsString* cons_string = ConsString::cast(result);
Leon Clarke4515c472010-02-03 11:58:03 +00003099 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003100 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00003101 cons_string->set_hash_field(String::kEmptyHashField);
3102 cons_string->set_first(first, mode);
3103 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003104 return result;
3105}
3106
3107
John Reck59135872010-11-02 12:39:01 -07003108MaybeObject* Heap::AllocateSubString(String* buffer,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003109 int start,
3110 int end,
3111 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003112 int length = end - start;
Ben Murdochc7cc0282012-03-05 14:35:55 +00003113 if (length <= 0) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003114 return empty_string();
3115 } else if (length == 1) {
Steve Block44f0eee2011-05-26 01:26:41 +01003116 return LookupSingleCharacterStringFromCode(buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00003117 } else if (length == 2) {
3118 // Optimization for 2-byte strings often used as keys in a decompression
3119 // dictionary. Check whether we already have the string in the symbol
3120 // table to prevent creation of many unneccesary strings.
3121 unsigned c1 = buffer->Get(start);
3122 unsigned c2 = buffer->Get(start + 1);
Steve Block44f0eee2011-05-26 01:26:41 +01003123 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00003124 }
3125
3126 // Make an attempt to flatten the buffer to reduce access time.
Leon Clarkef7060e22010-06-03 12:02:55 +01003127 buffer = buffer->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00003128
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003129 if (!FLAG_string_slices ||
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003130 !buffer->IsFlat() ||
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003131 length < SlicedString::kMinLength ||
3132 pretenure == TENURED) {
3133 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003134 // WriteToFlat takes care of the case when an indirect string has a
3135 // different encoding from its underlying string. These encodings may
3136 // differ because of externalization.
3137 bool is_ascii = buffer->IsAsciiRepresentation();
3138 { MaybeObject* maybe_result = is_ascii
3139 ? AllocateRawAsciiString(length, pretenure)
3140 : AllocateRawTwoByteString(length, pretenure);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003141 if (!maybe_result->ToObject(&result)) return maybe_result;
3142 }
3143 String* string_result = String::cast(result);
3144 // Copy the characters into the new object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003145 if (is_ascii) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003146 ASSERT(string_result->IsAsciiRepresentation());
3147 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3148 String::WriteToFlat(buffer, dest, start, end);
3149 } else {
3150 ASSERT(string_result->IsTwoByteRepresentation());
3151 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3152 String::WriteToFlat(buffer, dest, start, end);
3153 }
3154 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003155 }
Steve Blockd0582a62009-12-15 09:54:21 +00003156
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003157 ASSERT(buffer->IsFlat());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003158#if DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003159 if (FLAG_verify_heap) {
3160 buffer->StringVerify();
3161 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003162#endif
3163
3164 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003165 // When slicing an indirect string we use its encoding for a newly created
3166 // slice and don't check the encoding of the underlying string. This is safe
3167 // even if the encodings are different because of externalization. If an
3168 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3169 // codes of the underlying string must still fit into ASCII (because
3170 // externalization must not change char codes).
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003171 { Map* map = buffer->IsAsciiRepresentation()
3172 ? sliced_ascii_string_map()
3173 : sliced_string_map();
3174 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3175 if (!maybe_result->ToObject(&result)) return maybe_result;
3176 }
3177
3178 AssertNoAllocation no_gc;
3179 SlicedString* sliced_string = SlicedString::cast(result);
3180 sliced_string->set_length(length);
3181 sliced_string->set_hash_field(String::kEmptyHashField);
3182 if (buffer->IsConsString()) {
3183 ConsString* cons = ConsString::cast(buffer);
3184 ASSERT(cons->second()->length() == 0);
3185 sliced_string->set_parent(cons->first());
3186 sliced_string->set_offset(start);
3187 } else if (buffer->IsSlicedString()) {
3188 // Prevent nesting sliced strings.
3189 SlicedString* parent_slice = SlicedString::cast(buffer);
3190 sliced_string->set_parent(parent_slice->parent());
3191 sliced_string->set_offset(start + parent_slice->offset());
3192 } else {
3193 sliced_string->set_parent(buffer);
3194 sliced_string->set_offset(start);
3195 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003196 ASSERT(sliced_string->parent()->IsSeqString() ||
3197 sliced_string->parent()->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +00003198 return result;
3199}
3200
3201
John Reck59135872010-11-02 12:39:01 -07003202MaybeObject* Heap::AllocateExternalStringFromAscii(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003203 const ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003204 size_t length = resource->length();
3205 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003206 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003207 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00003208 }
3209
Steve Blockd0582a62009-12-15 09:54:21 +00003210 Map* map = external_ascii_string_map();
John Reck59135872010-11-02 12:39:01 -07003211 Object* result;
3212 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3213 if (!maybe_result->ToObject(&result)) return maybe_result;
3214 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003215
3216 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003217 external_string->set_length(static_cast<int>(length));
3218 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003219 external_string->set_resource(resource);
3220
3221 return result;
3222}
3223
3224
John Reck59135872010-11-02 12:39:01 -07003225MaybeObject* Heap::AllocateExternalStringFromTwoByte(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003226 const ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003227 size_t length = resource->length();
3228 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003229 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003230 return Failure::OutOfMemoryException();
3231 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003232
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003233 // For small strings we check whether the resource contains only
Steve Block9fac8402011-05-12 15:51:54 +01003234 // ASCII characters. If yes, we use a different string map.
3235 static const size_t kAsciiCheckLengthLimit = 32;
3236 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3237 String::IsAscii(resource->data(), static_cast<int>(length));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003238 Map* map = is_ascii ?
Steve Block44f0eee2011-05-26 01:26:41 +01003239 external_string_with_ascii_data_map() : external_string_map();
John Reck59135872010-11-02 12:39:01 -07003240 Object* result;
3241 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3242 if (!maybe_result->ToObject(&result)) return maybe_result;
3243 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003244
3245 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003246 external_string->set_length(static_cast<int>(length));
3247 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003248 external_string->set_resource(resource);
3249
3250 return result;
3251}
3252
3253
John Reck59135872010-11-02 12:39:01 -07003254MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003255 if (code <= String::kMaxAsciiCharCode) {
Steve Block44f0eee2011-05-26 01:26:41 +01003256 Object* value = single_character_string_cache()->get(code);
3257 if (value != undefined_value()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00003258
3259 char buffer[1];
3260 buffer[0] = static_cast<char>(code);
John Reck59135872010-11-02 12:39:01 -07003261 Object* result;
3262 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00003263
John Reck59135872010-11-02 12:39:01 -07003264 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003265 single_character_string_cache()->set(code, result);
Steve Blocka7e24c12009-10-30 11:49:00 +00003266 return result;
3267 }
3268
John Reck59135872010-11-02 12:39:01 -07003269 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01003270 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
John Reck59135872010-11-02 12:39:01 -07003271 if (!maybe_result->ToObject(&result)) return maybe_result;
3272 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003273 String* answer = String::cast(result);
3274 answer->Set(0, code);
3275 return answer;
3276}
3277
3278
John Reck59135872010-11-02 12:39:01 -07003279MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003280 if (length < 0 || length > ByteArray::kMaxLength) {
3281 return Failure::OutOfMemoryException();
3282 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003283 if (pretenure == NOT_TENURED) {
3284 return AllocateByteArray(length);
3285 }
3286 int size = ByteArray::SizeFor(length);
John Reck59135872010-11-02 12:39:01 -07003287 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003288 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
John Reck59135872010-11-02 12:39:01 -07003289 ? old_data_space_->AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003290 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
John Reck59135872010-11-02 12:39:01 -07003291 if (!maybe_result->ToObject(&result)) return maybe_result;
3292 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003293
Ben Murdochc7cc0282012-03-05 14:35:55 +00003294 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3295 byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003296 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003297 return result;
3298}
3299
3300
John Reck59135872010-11-02 12:39:01 -07003301MaybeObject* Heap::AllocateByteArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00003302 if (length < 0 || length > ByteArray::kMaxLength) {
3303 return Failure::OutOfMemoryException();
3304 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003305 int size = ByteArray::SizeFor(length);
3306 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003307 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003308 Object* result;
3309 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3310 if (!maybe_result->ToObject(&result)) return maybe_result;
3311 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003312
Ben Murdochc7cc0282012-03-05 14:35:55 +00003313 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3314 byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003315 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003316 return result;
3317}
3318
3319
3320void Heap::CreateFillerObjectAt(Address addr, int size) {
3321 if (size == 0) return;
3322 HeapObject* filler = HeapObject::FromAddress(addr);
3323 if (size == kPointerSize) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003324 filler->set_map_no_write_barrier(one_pointer_filler_map());
Steve Block6ded16b2010-05-10 14:33:55 +01003325 } else if (size == 2 * kPointerSize) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003326 filler->set_map_no_write_barrier(two_pointer_filler_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003327 } else {
Ben Murdochc7cc0282012-03-05 14:35:55 +00003328 filler->set_map_no_write_barrier(free_space_map());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003329 FreeSpace::cast(filler)->set_size(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003330 }
3331}
3332
3333
John Reck59135872010-11-02 12:39:01 -07003334MaybeObject* Heap::AllocateExternalArray(int length,
3335 ExternalArrayType array_type,
3336 void* external_pointer,
3337 PretenureFlag pretenure) {
Steve Block3ce2e202009-11-05 08:53:23 +00003338 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003339 Object* result;
3340 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3341 space,
3342 OLD_DATA_SPACE);
3343 if (!maybe_result->ToObject(&result)) return maybe_result;
3344 }
Steve Block3ce2e202009-11-05 08:53:23 +00003345
Ben Murdochc7cc0282012-03-05 14:35:55 +00003346 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
Steve Block3ce2e202009-11-05 08:53:23 +00003347 MapForExternalArrayType(array_type));
3348 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3349 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3350 external_pointer);
3351
3352 return result;
3353}
3354
3355
John Reck59135872010-11-02 12:39:01 -07003356MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3357 Code::Flags flags,
Steve Block44f0eee2011-05-26 01:26:41 +01003358 Handle<Object> self_reference,
3359 bool immovable) {
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).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003362 ByteArray* reloc_info;
3363 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3364 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
Leon Clarkeac952652010-07-15 11:15:24 +01003365
Steve Block44f0eee2011-05-26 01:26:41 +01003366 // Compute size.
Leon Clarkeac952652010-07-15 11:15:24 +01003367 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003368 int obj_size = Code::SizeFor(body_size);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003369 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
John Reck59135872010-11-02 12:39:01 -07003370 MaybeObject* maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003371 // Large code objects and code objects which should stay at a fixed address
3372 // are allocated in large object space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003373 if (obj_size > code_space()->AreaSize() || immovable) {
3374 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003375 } else {
John Reck59135872010-11-02 12:39:01 -07003376 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003377 }
3378
John Reck59135872010-11-02 12:39:01 -07003379 Object* result;
3380 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003381
3382 // Initialize the object
Ben Murdochc7cc0282012-03-05 14:35:55 +00003383 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003384 Code* code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003385 ASSERT(!isolate_->code_range()->exists() ||
3386 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003387 code->set_instruction_size(desc.instr_size);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003388 code->set_relocation_info(reloc_info);
Steve Blocka7e24c12009-10-30 11:49:00 +00003389 code->set_flags(flags);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003390 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3391 code->set_check_type(RECEIVER_MAP_CHECK);
3392 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003393 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01003394 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003395 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
Ben Murdochc7cc0282012-03-05 14:35:55 +00003396 code->set_gc_metadata(Smi::FromInt(0));
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01003397 code->set_ic_age(global_ic_age_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003398 // Allow self references to created code object by patching the handle to
3399 // point to the newly allocated Code object.
3400 if (!self_reference.is_null()) {
3401 *(self_reference.location()) = code;
3402 }
3403 // Migrate generated code.
3404 // The generated code can contain Object** values (typically from handles)
3405 // that are dereferenced during the copy to point directly to the actual heap
3406 // objects. These pointers can include references to the code object itself,
3407 // through the self_reference parameter.
3408 code->CopyFrom(desc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003409
3410#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003411 if (FLAG_verify_heap) {
3412 code->Verify();
3413 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003414#endif
3415 return code;
3416}
3417
3418
John Reck59135872010-11-02 12:39:01 -07003419MaybeObject* Heap::CopyCode(Code* code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003420 // Allocate an object the same size as the code object.
3421 int obj_size = code->Size();
John Reck59135872010-11-02 12:39:01 -07003422 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003423 if (obj_size > code_space()->AreaSize()) {
3424 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003425 } else {
John Reck59135872010-11-02 12:39:01 -07003426 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003427 }
3428
John Reck59135872010-11-02 12:39:01 -07003429 Object* result;
3430 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003431
3432 // Copy code object.
3433 Address old_addr = code->address();
3434 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003435 CopyBlock(new_addr, old_addr, obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003436 // Relocate the copy.
3437 Code* new_code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003438 ASSERT(!isolate_->code_range()->exists() ||
3439 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003440 new_code->Relocate(new_addr - old_addr);
3441 return new_code;
3442}
3443
3444
John Reck59135872010-11-02 12:39:01 -07003445MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
Leon Clarkeac952652010-07-15 11:15:24 +01003446 // Allocate ByteArray before the Code object, so that we do not risk
3447 // leaving uninitialized Code object (and breaking the heap).
John Reck59135872010-11-02 12:39:01 -07003448 Object* reloc_info_array;
3449 { MaybeObject* maybe_reloc_info_array =
3450 AllocateByteArray(reloc_info.length(), TENURED);
3451 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3452 return maybe_reloc_info_array;
3453 }
3454 }
Leon Clarkeac952652010-07-15 11:15:24 +01003455
3456 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
Steve Block6ded16b2010-05-10 14:33:55 +01003457
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003458 int new_obj_size = Code::SizeFor(new_body_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003459
3460 Address old_addr = code->address();
3461
3462 size_t relocation_offset =
Leon Clarkeac952652010-07-15 11:15:24 +01003463 static_cast<size_t>(code->instruction_end() - old_addr);
Steve Block6ded16b2010-05-10 14:33:55 +01003464
John Reck59135872010-11-02 12:39:01 -07003465 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003466 if (new_obj_size > code_space()->AreaSize()) {
3467 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
Steve Block6ded16b2010-05-10 14:33:55 +01003468 } else {
John Reck59135872010-11-02 12:39:01 -07003469 maybe_result = code_space_->AllocateRaw(new_obj_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003470 }
3471
John Reck59135872010-11-02 12:39:01 -07003472 Object* result;
3473 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block6ded16b2010-05-10 14:33:55 +01003474
3475 // Copy code object.
3476 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3477
3478 // Copy header and instructions.
3479 memcpy(new_addr, old_addr, relocation_offset);
3480
Steve Block6ded16b2010-05-10 14:33:55 +01003481 Code* new_code = Code::cast(result);
Leon Clarkeac952652010-07-15 11:15:24 +01003482 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
Steve Block6ded16b2010-05-10 14:33:55 +01003483
Leon Clarkeac952652010-07-15 11:15:24 +01003484 // Copy patched rinfo.
3485 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
Steve Block6ded16b2010-05-10 14:33:55 +01003486
3487 // Relocate the copy.
Steve Block44f0eee2011-05-26 01:26:41 +01003488 ASSERT(!isolate_->code_range()->exists() ||
3489 isolate_->code_range()->contains(code->address()));
Steve Block6ded16b2010-05-10 14:33:55 +01003490 new_code->Relocate(new_addr - old_addr);
3491
3492#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003493 if (FLAG_verify_heap) {
3494 code->Verify();
3495 }
Steve Block6ded16b2010-05-10 14:33:55 +01003496#endif
3497 return new_code;
3498}
3499
3500
John Reck59135872010-11-02 12:39:01 -07003501MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003502 ASSERT(gc_state_ == NOT_IN_GC);
3503 ASSERT(map->instance_type() != MAP_TYPE);
Leon Clarkee46be812010-01-19 14:06:41 +00003504 // If allocation failures are disallowed, we may allocate in a different
3505 // space when new space is full and the object is not a large object.
3506 AllocationSpace retry_space =
3507 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
John Reck59135872010-11-02 12:39:01 -07003508 Object* result;
3509 { MaybeObject* maybe_result =
3510 AllocateRaw(map->instance_size(), space, retry_space);
3511 if (!maybe_result->ToObject(&result)) return maybe_result;
3512 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003513 // No need for write barrier since object is white and map is in old space.
Ben Murdochc7cc0282012-03-05 14:35:55 +00003514 HeapObject::cast(result)->set_map_no_write_barrier(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00003515 return result;
3516}
3517
3518
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003519void Heap::InitializeFunction(JSFunction* function,
3520 SharedFunctionInfo* shared,
3521 Object* prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003522 ASSERT(!prototype->IsMap());
3523 function->initialize_properties();
3524 function->initialize_elements();
3525 function->set_shared(shared);
Iain Merrick75681382010-08-19 15:07:18 +01003526 function->set_code(shared->code());
Steve Blocka7e24c12009-10-30 11:49:00 +00003527 function->set_prototype_or_initial_map(prototype);
3528 function->set_context(undefined_value());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003529 function->set_literals_or_bindings(empty_fixed_array());
Ben Murdochb0fe1622011-05-05 13:52:32 +01003530 function->set_next_function_link(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00003531}
3532
3533
John Reck59135872010-11-02 12:39:01 -07003534MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003535 // Allocate the prototype. Make sure to use the object function
3536 // from the function's context, since the function can be from a
3537 // different context.
3538 JSFunction* object_function =
3539 function->context()->global_context()->object_function();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003540
3541 // Each function prototype gets a copy of the object function map.
3542 // This avoid unwanted sharing of maps between prototypes of different
3543 // constructors.
3544 Map* new_map;
3545 ASSERT(object_function->has_initial_map());
3546 { MaybeObject* maybe_map =
3547 object_function->initial_map()->CopyDropTransitions();
3548 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3549 }
John Reck59135872010-11-02 12:39:01 -07003550 Object* prototype;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003551 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
John Reck59135872010-11-02 12:39:01 -07003552 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3553 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003554 // When creating the prototype for the function we must set its
3555 // constructor to the function.
John Reck59135872010-11-02 12:39:01 -07003556 Object* result;
3557 { MaybeObject* maybe_result =
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003558 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3559 constructor_symbol(), function, DONT_ENUM);
John Reck59135872010-11-02 12:39:01 -07003560 if (!maybe_result->ToObject(&result)) return maybe_result;
3561 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003562 return prototype;
3563}
3564
3565
John Reck59135872010-11-02 12:39:01 -07003566MaybeObject* Heap::AllocateFunction(Map* function_map,
3567 SharedFunctionInfo* shared,
3568 Object* prototype,
3569 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003570 AllocationSpace space =
3571 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003572 Object* result;
3573 { MaybeObject* maybe_result = Allocate(function_map, space);
3574 if (!maybe_result->ToObject(&result)) return maybe_result;
3575 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003576 InitializeFunction(JSFunction::cast(result), shared, prototype);
3577 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003578}
3579
3580
John Reck59135872010-11-02 12:39:01 -07003581MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003582 // To get fast allocation and map sharing for arguments objects we
3583 // allocate them based on an arguments boilerplate.
3584
Steve Block44f0eee2011-05-26 01:26:41 +01003585 JSObject* boilerplate;
3586 int arguments_object_size;
3587 bool strict_mode_callee = callee->IsJSFunction() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003588 !JSFunction::cast(callee)->shared()->is_classic_mode();
Steve Block44f0eee2011-05-26 01:26:41 +01003589 if (strict_mode_callee) {
3590 boilerplate =
3591 isolate()->context()->global_context()->
3592 strict_mode_arguments_boilerplate();
3593 arguments_object_size = kArgumentsObjectSizeStrict;
3594 } else {
3595 boilerplate =
3596 isolate()->context()->global_context()->arguments_boilerplate();
3597 arguments_object_size = kArgumentsObjectSize;
3598 }
3599
Steve Blocka7e24c12009-10-30 11:49:00 +00003600 // This calls Copy directly rather than using Heap::AllocateRaw so we
3601 // duplicate the check here.
3602 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3603
Leon Clarkee46be812010-01-19 14:06:41 +00003604 // Check that the size of the boilerplate matches our
3605 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3606 // on the size being a known constant.
Steve Block44f0eee2011-05-26 01:26:41 +01003607 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
Leon Clarkee46be812010-01-19 14:06:41 +00003608
3609 // Do the allocation.
John Reck59135872010-11-02 12:39:01 -07003610 Object* result;
3611 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01003612 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07003613 if (!maybe_result->ToObject(&result)) return maybe_result;
3614 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003615
3616 // Copy the content. The arguments boilerplate doesn't have any
3617 // fields that point to new space so it's safe to skip the write
3618 // barrier here.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003619 CopyBlock(HeapObject::cast(result)->address(),
3620 boilerplate->address(),
Steve Block44f0eee2011-05-26 01:26:41 +01003621 JSObject::kHeaderSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003622
Steve Block44f0eee2011-05-26 01:26:41 +01003623 // Set the length property.
3624 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
Steve Blocka7e24c12009-10-30 11:49:00 +00003625 Smi::FromInt(length),
3626 SKIP_WRITE_BARRIER);
Steve Block44f0eee2011-05-26 01:26:41 +01003627 // Set the callee property for non-strict mode arguments object only.
3628 if (!strict_mode_callee) {
3629 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3630 callee);
3631 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003632
3633 // Check the state of the object
3634 ASSERT(JSObject::cast(result)->HasFastProperties());
3635 ASSERT(JSObject::cast(result)->HasFastElements());
3636
3637 return result;
3638}
3639
3640
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003641static bool HasDuplicates(DescriptorArray* descriptors) {
3642 int count = descriptors->number_of_descriptors();
3643 if (count > 1) {
3644 String* prev_key = descriptors->GetKey(0);
3645 for (int i = 1; i != count; i++) {
3646 String* current_key = descriptors->GetKey(i);
3647 if (prev_key == current_key) return true;
3648 prev_key = current_key;
3649 }
3650 }
3651 return false;
3652}
3653
3654
John Reck59135872010-11-02 12:39:01 -07003655MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003656 ASSERT(!fun->has_initial_map());
3657
3658 // First create a new map with the size and number of in-object properties
3659 // suggested by the function.
3660 int instance_size = fun->shared()->CalculateInstanceSize();
3661 int in_object_properties = fun->shared()->CalculateInObjectProperties();
John Reck59135872010-11-02 12:39:01 -07003662 Object* map_obj;
Steve Block44f0eee2011-05-26 01:26:41 +01003663 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
John Reck59135872010-11-02 12:39:01 -07003664 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3665 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003666
3667 // Fetch or allocate prototype.
3668 Object* prototype;
3669 if (fun->has_instance_prototype()) {
3670 prototype = fun->instance_prototype();
3671 } else {
John Reck59135872010-11-02 12:39:01 -07003672 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3673 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3674 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003675 }
3676 Map* map = Map::cast(map_obj);
3677 map->set_inobject_properties(in_object_properties);
3678 map->set_unused_property_fields(in_object_properties);
3679 map->set_prototype(prototype);
Steve Block8defd9f2010-07-08 12:39:36 +01003680 ASSERT(map->has_fast_elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003681
Andrei Popescu402d9372010-02-26 13:31:12 +00003682 // If the function has only simple this property assignments add
3683 // field descriptors for these to the initial map as the object
3684 // cannot be constructed without having these properties. Guard by
3685 // the inline_new flag so we only change the map if we generate a
3686 // specialized construct stub.
Steve Blocka7e24c12009-10-30 11:49:00 +00003687 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Andrei Popescu402d9372010-02-26 13:31:12 +00003688 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003689 int count = fun->shared()->this_property_assignments_count();
3690 if (count > in_object_properties) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003691 // Inline constructor can only handle inobject properties.
3692 fun->shared()->ForbidInlineConstructor();
3693 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003694 DescriptorArray* descriptors;
John Reck59135872010-11-02 12:39:01 -07003695 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003696 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
John Reck59135872010-11-02 12:39:01 -07003697 return maybe_descriptors_obj;
3698 }
3699 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003700 DescriptorArray::WhitenessWitness witness(descriptors);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003701 for (int i = 0; i < count; i++) {
3702 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3703 ASSERT(name->IsSymbol());
3704 FieldDescriptor field(name, i, NONE);
3705 field.SetEnumerationIndex(i);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003706 descriptors->Set(i, &field, witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003707 }
3708 descriptors->SetNextEnumerationIndex(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003709 descriptors->SortUnchecked(witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003710
3711 // The descriptors may contain duplicates because the compiler does not
3712 // guarantee the uniqueness of property names (it would have required
3713 // quadratic time). Once the descriptors are sorted we can check for
3714 // duplicates in linear time.
3715 if (HasDuplicates(descriptors)) {
3716 fun->shared()->ForbidInlineConstructor();
3717 } else {
3718 map->set_instance_descriptors(descriptors);
3719 map->set_pre_allocated_property_fields(count);
3720 map->set_unused_property_fields(in_object_properties - count);
3721 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003722 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003723 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003724
3725 fun->shared()->StartInobjectSlackTracking(map);
3726
Steve Blocka7e24c12009-10-30 11:49:00 +00003727 return map;
3728}
3729
3730
3731void Heap::InitializeJSObjectFromMap(JSObject* obj,
3732 FixedArray* properties,
3733 Map* map) {
3734 obj->set_properties(properties);
3735 obj->initialize_elements();
3736 // TODO(1240798): Initialize the object's body using valid initial values
3737 // according to the object's initial map. For example, if the map's
3738 // instance type is JS_ARRAY_TYPE, the length field should be initialized
Ben Murdochc7cc0282012-03-05 14:35:55 +00003739 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3740 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
Steve Blocka7e24c12009-10-30 11:49:00 +00003741 // verification code has to cope with (temporarily) invalid objects. See
3742 // for example, JSArray::JSArrayVerify).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003743 Object* filler;
3744 // We cannot always fill with one_pointer_filler_map because objects
3745 // created from API functions expect their internal fields to be initialized
3746 // with undefined_value.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003747 // Pre-allocated fields need to be initialized with undefined_value as well
3748 // so that object accesses before the constructor completes (e.g. in the
3749 // debugger) will not cause a crash.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003750 if (map->constructor()->IsJSFunction() &&
3751 JSFunction::cast(map->constructor())->shared()->
3752 IsInobjectSlackTrackingInProgress()) {
3753 // We might want to shrink the object later.
3754 ASSERT(obj->GetInternalFieldCount() == 0);
3755 filler = Heap::one_pointer_filler_map();
3756 } else {
3757 filler = Heap::undefined_value();
3758 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003759 obj->InitializeBody(map, Heap::undefined_value(), filler);
Steve Blocka7e24c12009-10-30 11:49:00 +00003760}
3761
3762
John Reck59135872010-11-02 12:39:01 -07003763MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003764 // JSFunctions should be allocated using AllocateFunction to be
3765 // properly initialized.
3766 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3767
Steve Block8defd9f2010-07-08 12:39:36 +01003768 // Both types of global objects should be allocated using
3769 // AllocateGlobalObject to be properly initialized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003770 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3771 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3772
3773 // Allocate the backing storage for the properties.
3774 int prop_size =
3775 map->pre_allocated_property_fields() +
3776 map->unused_property_fields() -
3777 map->inobject_properties();
3778 ASSERT(prop_size >= 0);
John Reck59135872010-11-02 12:39:01 -07003779 Object* properties;
3780 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3781 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3782 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003783
3784 // Allocate the JSObject.
3785 AllocationSpace space =
3786 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003787 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
John Reck59135872010-11-02 12:39:01 -07003788 Object* obj;
3789 { MaybeObject* maybe_obj = Allocate(map, space);
3790 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3791 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003792
3793 // Initialize the JSObject.
3794 InitializeJSObjectFromMap(JSObject::cast(obj),
3795 FixedArray::cast(properties),
3796 map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003797 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3798 JSObject::cast(obj)->HasFastElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003799 return obj;
3800}
3801
3802
John Reck59135872010-11-02 12:39:01 -07003803MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3804 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003805 // Allocate the initial map if absent.
3806 if (!constructor->has_initial_map()) {
John Reck59135872010-11-02 12:39:01 -07003807 Object* initial_map;
3808 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3809 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3810 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003811 constructor->set_initial_map(Map::cast(initial_map));
3812 Map::cast(initial_map)->set_constructor(constructor);
3813 }
3814 // Allocate the object based on the constructors initial map.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01003815 MaybeObject* result = AllocateJSObjectFromMap(
3816 constructor->initial_map(), pretenure);
John Reck59135872010-11-02 12:39:01 -07003817#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00003818 // Make sure result is NOT a global object if valid.
John Reck59135872010-11-02 12:39:01 -07003819 Object* non_failure;
3820 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3821#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003822 return result;
3823}
3824
3825
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01003826MaybeObject* Heap::AllocateJSArrayAndStorage(
3827 ElementsKind elements_kind,
3828 int length,
3829 int capacity,
3830 ArrayStorageAllocationMode mode,
3831 PretenureFlag pretenure) {
3832 ASSERT(capacity >= length);
3833 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3834 JSArray* array;
3835 if (!maybe_array->To(&array)) return maybe_array;
3836
3837 if (capacity == 0) {
3838 array->set_length(Smi::FromInt(0));
3839 array->set_elements(empty_fixed_array());
3840 return array;
3841 }
3842
3843 FixedArrayBase* elms;
3844 MaybeObject* maybe_elms = NULL;
3845 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3846 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3847 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3848 } else {
3849 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3850 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3851 }
3852 } else {
3853 ASSERT(elements_kind == FAST_ELEMENTS ||
3854 elements_kind == FAST_SMI_ONLY_ELEMENTS);
3855 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3856 maybe_elms = AllocateUninitializedFixedArray(capacity);
3857 } else {
3858 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3859 maybe_elms = AllocateFixedArrayWithHoles(capacity);
3860 }
3861 }
3862 if (!maybe_elms->To(&elms)) return maybe_elms;
3863
3864 array->set_elements(elms);
3865 array->set_length(Smi::FromInt(length));
3866 return array;
3867}
3868
3869
3870MaybeObject* Heap::AllocateJSArrayWithElements(
3871 FixedArrayBase* elements,
3872 ElementsKind elements_kind,
3873 PretenureFlag pretenure) {
3874 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3875 JSArray* array;
3876 if (!maybe_array->To(&array)) return maybe_array;
3877
3878 array->set_elements(elements);
3879 array->set_length(Smi::FromInt(elements->length()));
3880 return array;
3881}
3882
3883
Ben Murdoch257744e2011-11-30 15:57:28 +00003884MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3885 // Allocate map.
3886 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3887 // maps. Will probably depend on the identity of the handler object, too.
3888 Map* map;
3889 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3890 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3891 map->set_prototype(prototype);
Ben Murdoch257744e2011-11-30 15:57:28 +00003892
3893 // Allocate the proxy object.
Ben Murdoch589d6972011-11-30 16:04:58 +00003894 JSProxy* result;
Ben Murdoch257744e2011-11-30 15:57:28 +00003895 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
Ben Murdoch589d6972011-11-30 16:04:58 +00003896 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3897 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3898 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003899 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003900 return result;
3901}
3902
3903
3904MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3905 Object* call_trap,
3906 Object* construct_trap,
3907 Object* prototype) {
3908 // Allocate map.
3909 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3910 // maps. Will probably depend on the identity of the handler object, too.
3911 Map* map;
3912 MaybeObject* maybe_map_obj =
3913 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3914 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3915 map->set_prototype(prototype);
3916
3917 // Allocate the proxy object.
3918 JSFunctionProxy* result;
3919 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3920 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3921 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3922 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003923 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003924 result->set_call_trap(call_trap);
3925 result->set_construct_trap(construct_trap);
Ben Murdoch257744e2011-11-30 15:57:28 +00003926 return result;
3927}
3928
3929
John Reck59135872010-11-02 12:39:01 -07003930MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003931 ASSERT(constructor->has_initial_map());
3932 Map* map = constructor->initial_map();
3933
3934 // Make sure no field properties are described in the initial map.
3935 // This guarantees us that normalizing the properties does not
3936 // require us to change property values to JSGlobalPropertyCells.
3937 ASSERT(map->NextFreePropertyIndex() == 0);
3938
3939 // Make sure we don't have a ton of pre-allocated slots in the
3940 // global objects. They will be unused once we normalize the object.
3941 ASSERT(map->unused_property_fields() == 0);
3942 ASSERT(map->inobject_properties() == 0);
3943
3944 // Initial size of the backing store to avoid resize of the storage during
3945 // bootstrapping. The size differs between the JS global object ad the
3946 // builtins object.
3947 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3948
3949 // Allocate a dictionary object for backing storage.
John Reck59135872010-11-02 12:39:01 -07003950 Object* obj;
3951 { MaybeObject* maybe_obj =
3952 StringDictionary::Allocate(
3953 map->NumberOfDescribedProperties() * 2 + initial_size);
3954 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3955 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003956 StringDictionary* dictionary = StringDictionary::cast(obj);
3957
3958 // The global object might be created from an object template with accessors.
3959 // Fill these accessors into the dictionary.
3960 DescriptorArray* descs = map->instance_descriptors();
3961 for (int i = 0; i < descs->number_of_descriptors(); i++) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01003962 PropertyDetails details(descs->GetDetails(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00003963 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3964 PropertyDetails d =
3965 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3966 Object* value = descs->GetCallbacksObject(i);
Steve Block44f0eee2011-05-26 01:26:41 +01003967 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
John Reck59135872010-11-02 12:39:01 -07003968 if (!maybe_value->ToObject(&value)) return maybe_value;
3969 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003970
John Reck59135872010-11-02 12:39:01 -07003971 Object* result;
3972 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3973 if (!maybe_result->ToObject(&result)) return maybe_result;
3974 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003975 dictionary = StringDictionary::cast(result);
3976 }
3977
3978 // Allocate the global object and initialize it with the backing store.
John Reck59135872010-11-02 12:39:01 -07003979 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3980 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3981 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003982 JSObject* global = JSObject::cast(obj);
3983 InitializeJSObjectFromMap(global, dictionary, map);
3984
3985 // Create a new map for the global object.
John Reck59135872010-11-02 12:39:01 -07003986 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3987 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3988 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003989 Map* new_map = Map::cast(obj);
3990
Ben Murdochc7cc0282012-03-05 14:35:55 +00003991 // Set up the global object as a normalized object.
Steve Blocka7e24c12009-10-30 11:49:00 +00003992 global->set_map(new_map);
Ben Murdoch257744e2011-11-30 15:57:28 +00003993 global->map()->clear_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00003994 global->set_properties(dictionary);
3995
3996 // Make sure result is a global object with properties in dictionary.
3997 ASSERT(global->IsGlobalObject());
3998 ASSERT(!global->HasFastProperties());
3999 return global;
4000}
4001
4002
John Reck59135872010-11-02 12:39:01 -07004003MaybeObject* Heap::CopyJSObject(JSObject* source) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004004 // Never used to copy functions. If functions need to be copied we
4005 // have to be careful to clear the literals array.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004006 SLOW_ASSERT(!source->IsJSFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00004007
4008 // Make the clone.
4009 Map* map = source->map();
4010 int object_size = map->instance_size();
4011 Object* clone;
4012
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004013 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4014
Steve Blocka7e24c12009-10-30 11:49:00 +00004015 // If we're forced to always allocate, we use the general allocation
4016 // functions which may leave us with an object in old space.
4017 if (always_allocate()) {
John Reck59135872010-11-02 12:39:01 -07004018 { MaybeObject* maybe_clone =
4019 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4020 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4021 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004022 Address clone_address = HeapObject::cast(clone)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004023 CopyBlock(clone_address,
4024 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004025 object_size);
4026 // Update write barrier for all fields that lie beyond the header.
Steve Block6ded16b2010-05-10 14:33:55 +01004027 RecordWrites(clone_address,
4028 JSObject::kHeaderSize,
4029 (object_size - JSObject::kHeaderSize) / kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004030 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004031 wb_mode = SKIP_WRITE_BARRIER;
John Reck59135872010-11-02 12:39:01 -07004032 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4033 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4034 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004035 SLOW_ASSERT(InNewSpace(clone));
Steve Blocka7e24c12009-10-30 11:49:00 +00004036 // Since we know the clone is allocated in new space, we can copy
4037 // the contents without worrying about updating the write barrier.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004038 CopyBlock(HeapObject::cast(clone)->address(),
4039 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004040 object_size);
4041 }
4042
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004043 SLOW_ASSERT(
4044 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004045 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00004046 FixedArray* properties = FixedArray::cast(source->properties());
4047 // Update elements if necessary.
Steve Block6ded16b2010-05-10 14:33:55 +01004048 if (elements->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07004049 Object* elem;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004050 { MaybeObject* maybe_elem;
4051 if (elements->map() == fixed_cow_array_map()) {
4052 maybe_elem = FixedArray::cast(elements);
4053 } else if (source->HasFastDoubleElements()) {
4054 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4055 } else {
4056 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4057 }
John Reck59135872010-11-02 12:39:01 -07004058 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4059 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004060 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00004061 }
4062 // Update properties if necessary.
4063 if (properties->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07004064 Object* prop;
4065 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4066 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4067 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004068 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00004069 }
4070 // Return the new clone.
4071 return clone;
4072}
4073
4074
Ben Murdoch589d6972011-11-30 16:04:58 +00004075MaybeObject* Heap::ReinitializeJSReceiver(
4076 JSReceiver* object, InstanceType type, int size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004077 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
Ben Murdoch589d6972011-11-30 16:04:58 +00004078
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004079 // Allocate fresh map.
4080 // TODO(rossberg): Once we optimize proxies, cache these maps.
4081 Map* map;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004082 MaybeObject* maybe = AllocateMap(type, size);
4083 if (!maybe->To<Map>(&map)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004084
Ben Murdoch589d6972011-11-30 16:04:58 +00004085 // Check that the receiver has at least the size of the fresh object.
4086 int size_difference = object->map()->instance_size() - map->instance_size();
4087 ASSERT(size_difference >= 0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004088
4089 map->set_prototype(object->map()->prototype());
4090
4091 // Allocate the backing storage for the properties.
4092 int prop_size = map->unused_property_fields() - map->inobject_properties();
4093 Object* properties;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004094 maybe = AllocateFixedArray(prop_size, TENURED);
4095 if (!maybe->ToObject(&properties)) return maybe;
4096
4097 // Functions require some allocation, which might fail here.
4098 SharedFunctionInfo* shared = NULL;
4099 if (type == JS_FUNCTION_TYPE) {
4100 String* name;
4101 maybe = LookupAsciiSymbol("<freezing call trap>");
4102 if (!maybe->To<String>(&name)) return maybe;
4103 maybe = AllocateSharedFunctionInfo(name);
4104 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004105 }
4106
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004107 // Because of possible retries of this function after failure,
4108 // we must NOT fail after this point, where we have changed the type!
4109
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004110 // Reset the map for the object.
4111 object->set_map(map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004112 JSObject* jsobj = JSObject::cast(object);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004113
4114 // Reinitialize the object from the constructor map.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004115 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
Ben Murdoch589d6972011-11-30 16:04:58 +00004116
4117 // Functions require some minimal initialization.
4118 if (type == JS_FUNCTION_TYPE) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004119 map->set_function_with_prototype(true);
4120 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4121 JSFunction::cast(object)->set_context(
4122 isolate()->context()->global_context());
Ben Murdoch589d6972011-11-30 16:04:58 +00004123 }
4124
4125 // Put in filler if the new object is smaller than the old.
4126 if (size_difference > 0) {
4127 CreateFillerObjectAt(
4128 object->address() + map->instance_size(), size_difference);
4129 }
4130
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004131 return object;
4132}
4133
4134
John Reck59135872010-11-02 12:39:01 -07004135MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4136 JSGlobalProxy* object) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004137 ASSERT(constructor->has_initial_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004138 Map* map = constructor->initial_map();
4139
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004140 // Check that the already allocated object has the same size and type as
Steve Blocka7e24c12009-10-30 11:49:00 +00004141 // objects allocated using the constructor.
4142 ASSERT(map->instance_size() == object->map()->instance_size());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004143 ASSERT(map->instance_type() == object->map()->instance_type());
Steve Blocka7e24c12009-10-30 11:49:00 +00004144
4145 // Allocate the backing storage for the properties.
4146 int prop_size = map->unused_property_fields() - map->inobject_properties();
John Reck59135872010-11-02 12:39:01 -07004147 Object* properties;
4148 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4149 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4150 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004151
4152 // Reset the map for the object.
4153 object->set_map(constructor->initial_map());
4154
4155 // Reinitialize the object from the constructor map.
4156 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4157 return object;
4158}
4159
4160
John Reck59135872010-11-02 12:39:01 -07004161MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4162 PretenureFlag pretenure) {
Ben Murdoch589d6972011-11-30 16:04:58 +00004163 if (string.length() == 1) {
4164 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4165 }
John Reck59135872010-11-02 12:39:01 -07004166 Object* result;
4167 { MaybeObject* maybe_result =
4168 AllocateRawAsciiString(string.length(), pretenure);
4169 if (!maybe_result->ToObject(&result)) return maybe_result;
4170 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004171
4172 // Copy the characters into the new object.
4173 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4174 for (int i = 0; i < string.length(); i++) {
4175 string_result->SeqAsciiStringSet(i, string[i]);
4176 }
4177 return result;
4178}
4179
4180
Steve Block9fac8402011-05-12 15:51:54 +01004181MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4182 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004183 // Count the number of characters in the UTF-8 string and check if
4184 // it is an ASCII string.
Ben Murdoch8b112d22011-06-08 16:22:53 +01004185 Access<UnicodeCache::Utf8Decoder>
4186 decoder(isolate_->unicode_cache()->utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00004187 decoder->Reset(string.start(), string.length());
4188 int chars = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00004189 while (decoder->has_more()) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004190 uint32_t r = decoder->GetNext();
4191 if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4192 chars++;
4193 } else {
4194 chars += 2;
4195 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004196 }
4197
John Reck59135872010-11-02 12:39:01 -07004198 Object* result;
4199 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4200 if (!maybe_result->ToObject(&result)) return maybe_result;
4201 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004202
4203 // Convert and copy the characters into the new object.
4204 String* string_result = String::cast(result);
4205 decoder->Reset(string.start(), string.length());
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004206 int i = 0;
4207 while (i < chars) {
4208 uint32_t r = decoder->GetNext();
4209 if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4210 string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4211 string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4212 } else {
4213 string_result->Set(i++, r);
4214 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004215 }
4216 return result;
4217}
4218
4219
John Reck59135872010-11-02 12:39:01 -07004220MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4221 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004222 // Check if the string is an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004223 MaybeObject* maybe_result;
Steve Block9fac8402011-05-12 15:51:54 +01004224 if (String::IsAscii(string.start(), string.length())) {
John Reck59135872010-11-02 12:39:01 -07004225 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004226 } else { // It's not an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004227 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004228 }
John Reck59135872010-11-02 12:39:01 -07004229 Object* result;
4230 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004231
4232 // Copy the characters into the new object, which may be either ASCII or
4233 // UTF-16.
4234 String* string_result = String::cast(result);
4235 for (int i = 0; i < string.length(); i++) {
4236 string_result->Set(i, string[i]);
4237 }
4238 return result;
4239}
4240
4241
4242Map* Heap::SymbolMapForString(String* string) {
4243 // If the string is in new space it cannot be used as a symbol.
4244 if (InNewSpace(string)) return NULL;
4245
4246 // Find the corresponding symbol map for strings.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004247 switch (string->map()->instance_type()) {
4248 case STRING_TYPE: return symbol_map();
4249 case ASCII_STRING_TYPE: return ascii_symbol_map();
4250 case CONS_STRING_TYPE: return cons_symbol_map();
4251 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4252 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4253 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4254 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4255 return external_symbol_with_ascii_data_map();
4256 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4257 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4258 return short_external_ascii_symbol_map();
4259 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4260 return short_external_symbol_with_ascii_data_map();
4261 default: return NULL; // No match found.
Steve Block44f0eee2011-05-26 01:26:41 +01004262 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004263}
4264
4265
John Reck59135872010-11-02 12:39:01 -07004266MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4267 int chars,
4268 uint32_t hash_field) {
Leon Clarkee46be812010-01-19 14:06:41 +00004269 ASSERT(chars >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004270 // Ensure the chars matches the number of characters in the buffer.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004271 ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
Ben Murdochc7cc0282012-03-05 14:35:55 +00004272 // Determine whether the string is ASCII.
Steve Blocka7e24c12009-10-30 11:49:00 +00004273 bool is_ascii = true;
Leon Clarkee46be812010-01-19 14:06:41 +00004274 while (buffer->has_more()) {
4275 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4276 is_ascii = false;
4277 break;
4278 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004279 }
4280 buffer->Rewind();
4281
4282 // Compute map and object size.
4283 int size;
4284 Map* map;
4285
4286 if (is_ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +00004287 if (chars > SeqAsciiString::kMaxLength) {
4288 return Failure::OutOfMemoryException();
4289 }
Steve Blockd0582a62009-12-15 09:54:21 +00004290 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004291 size = SeqAsciiString::SizeFor(chars);
4292 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00004293 if (chars > SeqTwoByteString::kMaxLength) {
4294 return Failure::OutOfMemoryException();
4295 }
Steve Blockd0582a62009-12-15 09:54:21 +00004296 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004297 size = SeqTwoByteString::SizeFor(chars);
4298 }
4299
4300 // Allocate string.
John Reck59135872010-11-02 12:39:01 -07004301 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004302 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4303 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
John Reck59135872010-11-02 12:39:01 -07004304 : old_data_space_->AllocateRaw(size);
4305 if (!maybe_result->ToObject(&result)) return maybe_result;
4306 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004307
Ben Murdochc7cc0282012-03-05 14:35:55 +00004308 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
Steve Blockd0582a62009-12-15 09:54:21 +00004309 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00004310 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00004311 answer->set_length(chars);
4312 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004313
4314 ASSERT_EQ(size, answer->Size());
4315
4316 // Fill in the characters.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004317 int i = 0;
4318 while (i < chars) {
4319 uint32_t character = buffer->GetNext();
4320 if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4321 answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4322 answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4323 } else {
4324 answer->Set(i++, character);
4325 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004326 }
4327 return answer;
4328}
4329
4330
John Reck59135872010-11-02 12:39:01 -07004331MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004332 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4333 return Failure::OutOfMemoryException();
4334 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004335
4336 int size = SeqAsciiString::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004337 ASSERT(size <= SeqAsciiString::kMaxSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004338
Leon Clarkee46be812010-01-19 14:06:41 +00004339 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4340 AllocationSpace retry_space = OLD_DATA_SPACE;
4341
Steve Blocka7e24c12009-10-30 11:49:00 +00004342 if (space == NEW_SPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00004343 if (size > kMaxObjectSizeInNewSpace) {
4344 // Allocate in large object space, retry space will be ignored.
4345 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004346 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004347 // Allocate in new space, retry in large object space.
4348 retry_space = LO_SPACE;
4349 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004350 } else if (space == OLD_DATA_SPACE &&
4351 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004352 space = LO_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004353 }
John Reck59135872010-11-02 12:39:01 -07004354 Object* result;
4355 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4356 if (!maybe_result->ToObject(&result)) return maybe_result;
4357 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004358
Steve Blocka7e24c12009-10-30 11:49:00 +00004359 // Partially initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004360 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004361 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004362 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004363 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4364 return result;
4365}
4366
4367
John Reck59135872010-11-02 12:39:01 -07004368MaybeObject* Heap::AllocateRawTwoByteString(int length,
4369 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004370 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4371 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00004372 }
Leon Clarkee46be812010-01-19 14:06:41 +00004373 int size = SeqTwoByteString::SizeFor(length);
4374 ASSERT(size <= SeqTwoByteString::kMaxSize);
4375 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4376 AllocationSpace retry_space = OLD_DATA_SPACE;
4377
4378 if (space == NEW_SPACE) {
4379 if (size > kMaxObjectSizeInNewSpace) {
4380 // Allocate in large object space, retry space will be ignored.
4381 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004382 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004383 // Allocate in new space, retry in large object space.
4384 retry_space = LO_SPACE;
4385 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004386 } else if (space == OLD_DATA_SPACE &&
4387 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004388 space = LO_SPACE;
4389 }
John Reck59135872010-11-02 12:39:01 -07004390 Object* result;
4391 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4392 if (!maybe_result->ToObject(&result)) return maybe_result;
4393 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004394
Steve Blocka7e24c12009-10-30 11:49:00 +00004395 // Partially initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004396 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004397 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004398 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004399 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4400 return result;
4401}
4402
4403
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004404MaybeObject* Heap::AllocateJSArray(
4405 ElementsKind elements_kind,
4406 PretenureFlag pretenure) {
4407 Context* global_context = isolate()->context()->global_context();
4408 JSFunction* array_function = global_context->array_function();
4409 Map* map = array_function->initial_map();
4410 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4411 map = Map::cast(global_context->double_js_array_map());
4412 } else if (elements_kind == FAST_ELEMENTS || !FLAG_smi_only_arrays) {
4413 map = Map::cast(global_context->object_js_array_map());
4414 } else {
4415 ASSERT(elements_kind == FAST_SMI_ONLY_ELEMENTS);
4416 ASSERT(map == global_context->smi_js_array_map());
4417 }
4418
4419 return AllocateJSObjectFromMap(map, pretenure);
4420}
4421
4422
John Reck59135872010-11-02 12:39:01 -07004423MaybeObject* Heap::AllocateEmptyFixedArray() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004424 int size = FixedArray::SizeFor(0);
John Reck59135872010-11-02 12:39:01 -07004425 Object* result;
4426 { MaybeObject* maybe_result =
4427 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4428 if (!maybe_result->ToObject(&result)) return maybe_result;
4429 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004430 // Initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004431 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4432 fixed_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004433 reinterpret_cast<FixedArray*>(result)->set_length(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004434 return result;
4435}
4436
4437
John Reck59135872010-11-02 12:39:01 -07004438MaybeObject* Heap::AllocateRawFixedArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00004439 if (length < 0 || length > FixedArray::kMaxLength) {
4440 return Failure::OutOfMemoryException();
4441 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004442 ASSERT(length > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004443 // Use the general function if we're forced to always allocate.
4444 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4445 // Allocate the raw data for a fixed array.
4446 int size = FixedArray::SizeFor(length);
4447 return size <= kMaxObjectSizeInNewSpace
4448 ? new_space_.AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004449 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004450}
4451
4452
John Reck59135872010-11-02 12:39:01 -07004453MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004454 int len = src->length();
John Reck59135872010-11-02 12:39:01 -07004455 Object* obj;
4456 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4457 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4458 }
Steve Block44f0eee2011-05-26 01:26:41 +01004459 if (InNewSpace(obj)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004460 HeapObject* dst = HeapObject::cast(obj);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004461 dst->set_map_no_write_barrier(map);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004462 CopyBlock(dst->address() + kPointerSize,
4463 src->address() + kPointerSize,
4464 FixedArray::SizeFor(len) - kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004465 return obj;
4466 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00004467 HeapObject::cast(obj)->set_map_no_write_barrier(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00004468 FixedArray* result = FixedArray::cast(obj);
4469 result->set_length(len);
Leon Clarke4515c472010-02-03 11:58:03 +00004470
Steve Blocka7e24c12009-10-30 11:49:00 +00004471 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00004472 AssertNoAllocation no_gc;
4473 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00004474 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4475 return result;
4476}
4477
4478
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004479MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4480 Map* map) {
4481 int len = src->length();
4482 Object* obj;
4483 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4484 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4485 }
4486 HeapObject* dst = HeapObject::cast(obj);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004487 dst->set_map_no_write_barrier(map);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004488 CopyBlock(
4489 dst->address() + FixedDoubleArray::kLengthOffset,
4490 src->address() + FixedDoubleArray::kLengthOffset,
4491 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4492 return obj;
4493}
4494
4495
John Reck59135872010-11-02 12:39:01 -07004496MaybeObject* Heap::AllocateFixedArray(int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004497 ASSERT(length >= 0);
4498 if (length == 0) return empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07004499 Object* result;
4500 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4501 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004502 }
John Reck59135872010-11-02 12:39:01 -07004503 // Initialize header.
4504 FixedArray* array = reinterpret_cast<FixedArray*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004505 array->set_map_no_write_barrier(fixed_array_map());
John Reck59135872010-11-02 12:39:01 -07004506 array->set_length(length);
4507 // Initialize body.
Steve Block44f0eee2011-05-26 01:26:41 +01004508 ASSERT(!InNewSpace(undefined_value()));
John Reck59135872010-11-02 12:39:01 -07004509 MemsetPointer(array->data_start(), undefined_value(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00004510 return result;
4511}
4512
4513
John Reck59135872010-11-02 12:39:01 -07004514MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004515 if (length < 0 || length > FixedArray::kMaxLength) {
4516 return Failure::OutOfMemoryException();
4517 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004518
Leon Clarkee46be812010-01-19 14:06:41 +00004519 AllocationSpace space =
4520 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004521 int size = FixedArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004522 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4523 // Too big for new space.
4524 space = LO_SPACE;
4525 } else if (space == OLD_POINTER_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004526 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004527 // Too big for old pointer space.
4528 space = LO_SPACE;
4529 }
4530
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004531 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004532 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004533
4534 return AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00004535}
4536
4537
John Reck59135872010-11-02 12:39:01 -07004538MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
Steve Block44f0eee2011-05-26 01:26:41 +01004539 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07004540 int length,
4541 PretenureFlag pretenure,
4542 Object* filler) {
Steve Block6ded16b2010-05-10 14:33:55 +01004543 ASSERT(length >= 0);
Steve Block44f0eee2011-05-26 01:26:41 +01004544 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4545 if (length == 0) return heap->empty_fixed_array();
Steve Block6ded16b2010-05-10 14:33:55 +01004546
Steve Block44f0eee2011-05-26 01:26:41 +01004547 ASSERT(!heap->InNewSpace(filler));
John Reck59135872010-11-02 12:39:01 -07004548 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004549 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004550 if (!maybe_result->ToObject(&result)) return maybe_result;
4551 }
Steve Block6ded16b2010-05-10 14:33:55 +01004552
Ben Murdochc7cc0282012-03-05 14:35:55 +00004553 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004554 FixedArray* array = FixedArray::cast(result);
4555 array->set_length(length);
4556 MemsetPointer(array->data_start(), filler, length);
4557 return array;
4558}
4559
4560
John Reck59135872010-11-02 12:39:01 -07004561MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004562 return AllocateFixedArrayWithFiller(this,
4563 length,
4564 pretenure,
4565 undefined_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004566}
4567
4568
John Reck59135872010-11-02 12:39:01 -07004569MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4570 PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004571 return AllocateFixedArrayWithFiller(this,
4572 length,
4573 pretenure,
4574 the_hole_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004575}
4576
4577
John Reck59135872010-11-02 12:39:01 -07004578MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
Steve Block6ded16b2010-05-10 14:33:55 +01004579 if (length == 0) return empty_fixed_array();
4580
John Reck59135872010-11-02 12:39:01 -07004581 Object* obj;
4582 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4583 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4584 }
Steve Block6ded16b2010-05-10 14:33:55 +01004585
Ben Murdochc7cc0282012-03-05 14:35:55 +00004586 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4587 fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004588 FixedArray::cast(obj)->set_length(length);
4589 return obj;
4590}
4591
4592
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004593MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4594 int size = FixedDoubleArray::SizeFor(0);
4595 Object* result;
4596 { MaybeObject* maybe_result =
4597 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4598 if (!maybe_result->ToObject(&result)) return maybe_result;
4599 }
4600 // Initialize the object.
Ben Murdochc7cc0282012-03-05 14:35:55 +00004601 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004602 fixed_double_array_map());
4603 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4604 return result;
4605}
4606
4607
4608MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4609 int length,
4610 PretenureFlag pretenure) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004611 if (length == 0) return empty_fixed_array();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004612
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004613 Object* elements_object;
4614 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4615 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4616 FixedDoubleArray* elements =
4617 reinterpret_cast<FixedDoubleArray*>(elements_object);
4618
4619 elements->set_map_no_write_barrier(fixed_double_array_map());
4620 elements->set_length(length);
4621 return elements;
4622}
4623
4624
4625MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4626 int length,
4627 PretenureFlag pretenure) {
4628 if (length == 0) return empty_fixed_array();
4629
4630 Object* elements_object;
4631 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4632 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4633 FixedDoubleArray* elements =
4634 reinterpret_cast<FixedDoubleArray*>(elements_object);
4635
4636 for (int i = 0; i < length; ++i) {
4637 elements->set_the_hole(i);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004638 }
4639
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004640 elements->set_map_no_write_barrier(fixed_double_array_map());
4641 elements->set_length(length);
4642 return elements;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004643}
4644
4645
4646MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4647 PretenureFlag pretenure) {
4648 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4649 return Failure::OutOfMemoryException();
4650 }
4651
4652 AllocationSpace space =
4653 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4654 int size = FixedDoubleArray::SizeFor(length);
4655 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4656 // Too big for new space.
4657 space = LO_SPACE;
4658 } else if (space == OLD_DATA_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004659 size > Page::kMaxNonCodeHeapObjectSize) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004660 // Too big for old data space.
4661 space = LO_SPACE;
4662 }
4663
4664 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004665 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004666
4667 return AllocateRaw(size, space, retry_space);
4668}
4669
4670
John Reck59135872010-11-02 12:39:01 -07004671MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4672 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004673 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004674 if (!maybe_result->ToObject(&result)) return maybe_result;
4675 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00004676 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4677 hash_table_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004678 ASSERT(result->IsHashTable());
4679 return result;
4680}
4681
4682
John Reck59135872010-11-02 12:39:01 -07004683MaybeObject* Heap::AllocateGlobalContext() {
4684 Object* result;
4685 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01004686 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004687 if (!maybe_result->ToObject(&result)) return maybe_result;
4688 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004689 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004690 context->set_map_no_write_barrier(global_context_map());
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004691 context->set_smi_js_array_map(undefined_value());
4692 context->set_double_js_array_map(undefined_value());
4693 context->set_object_js_array_map(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00004694 ASSERT(context->IsGlobalContext());
4695 ASSERT(result->IsContext());
4696 return result;
4697}
4698
4699
John Reck59135872010-11-02 12:39:01 -07004700MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004701 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004702 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004703 { MaybeObject* maybe_result = AllocateFixedArray(length);
John Reck59135872010-11-02 12:39:01 -07004704 if (!maybe_result->ToObject(&result)) return maybe_result;
4705 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004706 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004707 context->set_map_no_write_barrier(function_context_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004708 context->set_closure(function);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004709 context->set_previous(function->context());
Steve Blocka7e24c12009-10-30 11:49:00 +00004710 context->set_extension(NULL);
4711 context->set_global(function->context()->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004712 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004713}
4714
4715
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004716MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4717 Context* previous,
4718 String* name,
4719 Object* thrown_object) {
4720 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4721 Object* result;
4722 { MaybeObject* maybe_result =
4723 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4724 if (!maybe_result->ToObject(&result)) return maybe_result;
4725 }
4726 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004727 context->set_map_no_write_barrier(catch_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004728 context->set_closure(function);
4729 context->set_previous(previous);
4730 context->set_extension(name);
4731 context->set_global(previous->global());
4732 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4733 return context;
4734}
4735
4736
4737MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4738 Context* previous,
4739 JSObject* extension) {
John Reck59135872010-11-02 12:39:01 -07004740 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004741 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004742 if (!maybe_result->ToObject(&result)) return maybe_result;
4743 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004744 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004745 context->set_map_no_write_barrier(with_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004746 context->set_closure(function);
Steve Blocka7e24c12009-10-30 11:49:00 +00004747 context->set_previous(previous);
4748 context->set_extension(extension);
4749 context->set_global(previous->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004750 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004751}
4752
4753
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004754MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4755 Context* previous,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004756 ScopeInfo* scope_info) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004757 Object* result;
4758 { MaybeObject* maybe_result =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004759 AllocateFixedArrayWithHoles(scope_info->ContextLength());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004760 if (!maybe_result->ToObject(&result)) return maybe_result;
4761 }
4762 Context* context = reinterpret_cast<Context*>(result);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004763 context->set_map_no_write_barrier(block_context_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004764 context->set_closure(function);
4765 context->set_previous(previous);
4766 context->set_extension(scope_info);
4767 context->set_global(previous->global());
4768 return context;
4769}
4770
4771
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004772MaybeObject* Heap::AllocateScopeInfo(int length) {
4773 FixedArray* scope_info;
4774 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4775 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
Ben Murdochc7cc0282012-03-05 14:35:55 +00004776 scope_info->set_map_no_write_barrier(scope_info_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004777 return scope_info;
4778}
4779
4780
John Reck59135872010-11-02 12:39:01 -07004781MaybeObject* Heap::AllocateStruct(InstanceType type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004782 Map* map;
4783 switch (type) {
Steve Block44f0eee2011-05-26 01:26:41 +01004784#define MAKE_CASE(NAME, Name, name) \
4785 case NAME##_TYPE: map = name##_map(); break;
Steve Blocka7e24c12009-10-30 11:49:00 +00004786STRUCT_LIST(MAKE_CASE)
4787#undef MAKE_CASE
4788 default:
4789 UNREACHABLE();
4790 return Failure::InternalError();
4791 }
4792 int size = map->instance_size();
4793 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004794 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
John Reck59135872010-11-02 12:39:01 -07004795 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004796 { MaybeObject* maybe_result = Allocate(map, space);
John Reck59135872010-11-02 12:39:01 -07004797 if (!maybe_result->ToObject(&result)) return maybe_result;
4798 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004799 Struct::cast(result)->InitializeBody(size);
4800 return result;
4801}
4802
4803
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004804bool Heap::IsHeapIterable() {
4805 return (!old_pointer_space()->was_swept_conservatively() &&
4806 !old_data_space()->was_swept_conservatively());
4807}
4808
4809
4810void Heap::EnsureHeapIsIterable() {
4811 ASSERT(IsAllocationAllowed());
4812 if (!IsHeapIterable()) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004813 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004814 }
4815 ASSERT(IsHeapIterable());
4816}
4817
4818
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004819void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
4820 // This flag prevents incremental marking from requesting GC via stack guard
4821 idle_notification_will_schedule_next_gc_ = true;
4822 incremental_marking()->Step(step_size);
4823 idle_notification_will_schedule_next_gc_ = false;
4824
4825 if (incremental_marking()->IsComplete()) {
4826 bool uncommit = false;
4827 if (gc_count_at_last_idle_gc_ == gc_count_) {
4828 // No GC since the last full GC, the mutator is probably not active.
4829 isolate_->compilation_cache()->Clear();
4830 uncommit = true;
4831 }
4832 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4833 gc_count_at_last_idle_gc_ = gc_count_;
4834 if (uncommit) {
4835 new_space_.Shrink();
4836 UncommitFromSpace();
4837 }
4838 }
4839}
4840
4841
Ben Murdochc7cc0282012-03-05 14:35:55 +00004842bool Heap::IdleNotification(int hint) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004843 const int kMaxHint = 1000;
4844 intptr_t size_factor = Min(Max(hint, 30), kMaxHint) / 10;
4845 // The size factor is in range [3..100].
4846 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
4847
4848 if (contexts_disposed_ > 0) {
4849 if (hint >= kMaxHint) {
4850 // The embedder is requesting a lot of GC work after context disposal,
4851 // we age inline caches so that they don't keep objects from
4852 // the old context alive.
4853 AgeInlineCaches();
4854 }
4855 int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
4856 if (hint >= mark_sweep_time && !FLAG_expose_gc &&
4857 incremental_marking()->IsStopped()) {
4858 HistogramTimerScope scope(isolate_->counters()->gc_context());
4859 CollectAllGarbage(kReduceMemoryFootprintMask,
4860 "idle notification: contexts disposed");
4861 } else {
4862 AdvanceIdleIncrementalMarking(step_size);
4863 contexts_disposed_ = 0;
4864 }
4865 // Make sure that we have no pending context disposals.
4866 // Take into account that we might have decided to delay full collection
4867 // because incremental marking is in progress.
4868 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
4869 return false;
4870 }
4871
4872 if (hint >= kMaxHint || !FLAG_incremental_marking ||
Ben Murdochc7cc0282012-03-05 14:35:55 +00004873 FLAG_expose_gc || Serializer::enabled()) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004874 return IdleGlobalGC();
Ben Murdochc7cc0282012-03-05 14:35:55 +00004875 }
4876
4877 // By doing small chunks of GC work in each IdleNotification,
4878 // perform a round of incremental GCs and after that wait until
4879 // the mutator creates enough garbage to justify a new round.
4880 // An incremental GC progresses as follows:
4881 // 1. many incremental marking steps,
4882 // 2. one old space mark-sweep-compact,
4883 // 3. many lazy sweep steps.
4884 // Use mark-sweep-compact events to count incremental GCs in a round.
4885
Ben Murdochc7cc0282012-03-05 14:35:55 +00004886
4887 if (incremental_marking()->IsStopped()) {
4888 if (!IsSweepingComplete() &&
4889 !AdvanceSweepers(static_cast<int>(step_size))) {
4890 return false;
4891 }
4892 }
4893
4894 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4895 if (EnoughGarbageSinceLastIdleRound()) {
4896 StartIdleRound();
4897 } else {
4898 return true;
4899 }
4900 }
4901
4902 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
4903 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
4904 ms_count_at_last_idle_notification_ = ms_count_;
4905
4906 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4907 FinishIdleRound();
4908 return true;
4909 }
4910
4911 if (incremental_marking()->IsStopped()) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004912 if (!WorthStartingGCWhenIdle()) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00004913 FinishIdleRound();
4914 return true;
4915 }
4916 incremental_marking()->Start();
4917 }
4918
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004919 AdvanceIdleIncrementalMarking(step_size);
Ben Murdochc7cc0282012-03-05 14:35:55 +00004920 return false;
4921}
4922
4923
4924bool Heap::IdleGlobalGC() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004925 static const int kIdlesBeforeScavenge = 4;
4926 static const int kIdlesBeforeMarkSweep = 7;
4927 static const int kIdlesBeforeMarkCompact = 8;
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004928 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
Ben Murdoche0cee9b2011-05-25 10:26:03 +01004929 static const unsigned int kGCsBetweenCleanup = 4;
Steve Block44f0eee2011-05-26 01:26:41 +01004930
4931 if (!last_idle_notification_gc_count_init_) {
4932 last_idle_notification_gc_count_ = gc_count_;
4933 last_idle_notification_gc_count_init_ = true;
4934 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004935
Steve Block6ded16b2010-05-10 14:33:55 +01004936 bool uncommit = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004937 bool finished = false;
4938
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004939 // Reset the number of idle notifications received when a number of
4940 // GCs have taken place. This allows another round of cleanup based
4941 // on idle notifications if enough work has been carried out to
4942 // provoke a number of garbage collections.
Steve Block44f0eee2011-05-26 01:26:41 +01004943 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4944 number_idle_notifications_ =
4945 Min(number_idle_notifications_ + 1, kMaxIdleCount);
Steve Blocka7e24c12009-10-30 11:49:00 +00004946 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01004947 number_idle_notifications_ = 0;
4948 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004949 }
4950
Steve Block44f0eee2011-05-26 01:26:41 +01004951 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004952 CollectGarbage(NEW_SPACE, "idle notification");
Steve Blocka7e24c12009-10-30 11:49:00 +00004953 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004954 last_idle_notification_gc_count_ = gc_count_;
4955 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00004956 // Before doing the mark-sweep collections we clear the
4957 // compilation cache to avoid hanging on to source code and
4958 // generated code for cached functions.
Steve Block44f0eee2011-05-26 01:26:41 +01004959 isolate_->compilation_cache()->Clear();
Steve Blockd0582a62009-12-15 09:54:21 +00004960
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004961 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
Steve Blocka7e24c12009-10-30 11:49:00 +00004962 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004963 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004964
Steve Block44f0eee2011-05-26 01:26:41 +01004965 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01004966 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
Steve Blocka7e24c12009-10-30 11:49:00 +00004967 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004968 last_idle_notification_gc_count_ = gc_count_;
4969 number_idle_notifications_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00004970 finished = true;
Steve Block44f0eee2011-05-26 01:26:41 +01004971 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004972 // If we have received more than kIdlesBeforeMarkCompact idle
4973 // notifications we do not perform any cleanup because we don't
4974 // expect to gain much by doing so.
4975 finished = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004976 }
4977
Steve Block44f0eee2011-05-26 01:26:41 +01004978 if (uncommit) UncommitFromSpace();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004979
Steve Blocka7e24c12009-10-30 11:49:00 +00004980 return finished;
4981}
4982
4983
4984#ifdef DEBUG
4985
4986void Heap::Print() {
Ben Murdochc7cc0282012-03-05 14:35:55 +00004987 if (!HasBeenSetUp()) return;
Steve Block44f0eee2011-05-26 01:26:41 +01004988 isolate()->PrintStack();
Steve Blocka7e24c12009-10-30 11:49:00 +00004989 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004990 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4991 space->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +00004992}
4993
4994
4995void Heap::ReportCodeStatistics(const char* title) {
4996 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4997 PagedSpace::ResetCodeStatistics();
4998 // We do not look for code in new space, map space, or old space. If code
4999 // somehow ends up in those spaces, we would miss it here.
5000 code_space_->CollectCodeStatistics();
5001 lo_space_->CollectCodeStatistics();
5002 PagedSpace::ReportCodeStatistics();
5003}
5004
5005
5006// This function expects that NewSpace's allocated objects histogram is
5007// populated (via a call to CollectStatistics or else as a side effect of a
5008// just-completed scavenge collection).
5009void Heap::ReportHeapStatistics(const char* title) {
5010 USE(title);
5011 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5012 title, gc_count_);
Ben Murdochf87a2032010-10-22 12:50:53 +01005013 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5014 old_gen_promotion_limit_);
5015 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5016 old_gen_allocation_limit_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005017 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005018
5019 PrintF("\n");
5020 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
Steve Block44f0eee2011-05-26 01:26:41 +01005021 isolate_->global_handles()->PrintStats();
Steve Blocka7e24c12009-10-30 11:49:00 +00005022 PrintF("\n");
5023
5024 PrintF("Heap statistics : ");
Steve Block44f0eee2011-05-26 01:26:41 +01005025 isolate_->memory_allocator()->ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00005026 PrintF("To space : ");
5027 new_space_.ReportStatistics();
5028 PrintF("Old pointer space : ");
5029 old_pointer_space_->ReportStatistics();
5030 PrintF("Old data space : ");
5031 old_data_space_->ReportStatistics();
5032 PrintF("Code space : ");
5033 code_space_->ReportStatistics();
5034 PrintF("Map space : ");
5035 map_space_->ReportStatistics();
5036 PrintF("Cell space : ");
5037 cell_space_->ReportStatistics();
5038 PrintF("Large object space : ");
5039 lo_space_->ReportStatistics();
5040 PrintF(">>>>>> ========================================= >>>>>>\n");
5041}
5042
5043#endif // DEBUG
5044
5045bool Heap::Contains(HeapObject* value) {
5046 return Contains(value->address());
5047}
5048
5049
5050bool Heap::Contains(Address addr) {
5051 if (OS::IsOutsideAllocatedSpace(addr)) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005052 return HasBeenSetUp() &&
Steve Blocka7e24c12009-10-30 11:49:00 +00005053 (new_space_.ToSpaceContains(addr) ||
5054 old_pointer_space_->Contains(addr) ||
5055 old_data_space_->Contains(addr) ||
5056 code_space_->Contains(addr) ||
5057 map_space_->Contains(addr) ||
5058 cell_space_->Contains(addr) ||
5059 lo_space_->SlowContains(addr));
5060}
5061
5062
5063bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5064 return InSpace(value->address(), space);
5065}
5066
5067
5068bool Heap::InSpace(Address addr, AllocationSpace space) {
5069 if (OS::IsOutsideAllocatedSpace(addr)) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005070 if (!HasBeenSetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005071
5072 switch (space) {
5073 case NEW_SPACE:
5074 return new_space_.ToSpaceContains(addr);
5075 case OLD_POINTER_SPACE:
5076 return old_pointer_space_->Contains(addr);
5077 case OLD_DATA_SPACE:
5078 return old_data_space_->Contains(addr);
5079 case CODE_SPACE:
5080 return code_space_->Contains(addr);
5081 case MAP_SPACE:
5082 return map_space_->Contains(addr);
5083 case CELL_SPACE:
5084 return cell_space_->Contains(addr);
5085 case LO_SPACE:
5086 return lo_space_->SlowContains(addr);
5087 }
5088
5089 return false;
5090}
5091
5092
5093#ifdef DEBUG
5094void Heap::Verify() {
Ben Murdochc7cc0282012-03-05 14:35:55 +00005095 ASSERT(HasBeenSetUp());
Steve Blocka7e24c12009-10-30 11:49:00 +00005096
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005097 store_buffer()->Verify();
5098
Steve Blocka7e24c12009-10-30 11:49:00 +00005099 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00005100 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00005101
5102 new_space_.Verify();
5103
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005104 old_pointer_space_->Verify(&visitor);
5105 map_space_->Verify(&visitor);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005106
5107 VerifyPointersVisitor no_dirty_regions_visitor;
5108 old_data_space_->Verify(&no_dirty_regions_visitor);
5109 code_space_->Verify(&no_dirty_regions_visitor);
5110 cell_space_->Verify(&no_dirty_regions_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00005111
5112 lo_space_->Verify();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005113
5114 VerifyNoAccessorPairSharing();
Steve Blocka7e24c12009-10-30 11:49:00 +00005115}
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005116
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005117
5118void Heap::VerifyNoAccessorPairSharing() {
5119 // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5120 // that we mark only unmarked pairs, then we clear all marks, restoring the
5121 // initial state. We use the Smi tag of the AccessorPair's getter as the
5122 // marking bit, because we can never see a Smi as the getter.
5123 for (int phase = 0; phase < 2; phase++) {
5124 HeapObjectIterator iter(map_space());
5125 for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5126 if (obj->IsMap()) {
5127 DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5128 for (int i = 0; i < descs->number_of_descriptors(); i++) {
5129 if (descs->GetType(i) == CALLBACKS &&
5130 descs->GetValue(i)->IsAccessorPair()) {
5131 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5132 uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5133 uintptr_t after = (phase == 0) ?
5134 ((before & ~kSmiTagMask) | kSmiTag) :
5135 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5136 CHECK(before != after);
5137 accessors->set_getter(reinterpret_cast<Object*>(after));
5138 }
5139 }
5140 }
5141 }
5142 }
5143}
Steve Blocka7e24c12009-10-30 11:49:00 +00005144#endif // DEBUG
5145
5146
John Reck59135872010-11-02 12:39:01 -07005147MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005148 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07005149 Object* new_table;
5150 { MaybeObject* maybe_new_table =
5151 symbol_table()->LookupSymbol(string, &symbol);
5152 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5153 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005154 // Can't use set_symbol_table because SymbolTable::cast knows that
5155 // SymbolTable is a singleton and checks for identity.
5156 roots_[kSymbolTableRootIndex] = new_table;
5157 ASSERT(symbol != NULL);
5158 return symbol;
5159}
5160
5161
Steve Block9fac8402011-05-12 15:51:54 +01005162MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5163 Object* symbol = NULL;
5164 Object* new_table;
5165 { MaybeObject* maybe_new_table =
5166 symbol_table()->LookupAsciiSymbol(string, &symbol);
5167 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5168 }
5169 // Can't use set_symbol_table because SymbolTable::cast knows that
5170 // SymbolTable is a singleton and checks for identity.
5171 roots_[kSymbolTableRootIndex] = new_table;
5172 ASSERT(symbol != NULL);
5173 return symbol;
5174}
5175
5176
Ben Murdoch257744e2011-11-30 15:57:28 +00005177MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5178 int from,
5179 int length) {
5180 Object* symbol = NULL;
5181 Object* new_table;
5182 { MaybeObject* maybe_new_table =
5183 symbol_table()->LookupSubStringAsciiSymbol(string,
5184 from,
5185 length,
5186 &symbol);
5187 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5188 }
5189 // Can't use set_symbol_table because SymbolTable::cast knows that
5190 // SymbolTable is a singleton and checks for identity.
5191 roots_[kSymbolTableRootIndex] = new_table;
5192 ASSERT(symbol != NULL);
5193 return symbol;
5194}
5195
5196
Steve Block9fac8402011-05-12 15:51:54 +01005197MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5198 Object* symbol = NULL;
5199 Object* new_table;
5200 { MaybeObject* maybe_new_table =
5201 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5202 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5203 }
5204 // Can't use set_symbol_table because SymbolTable::cast knows that
5205 // SymbolTable is a singleton and checks for identity.
5206 roots_[kSymbolTableRootIndex] = new_table;
5207 ASSERT(symbol != NULL);
5208 return symbol;
5209}
5210
5211
John Reck59135872010-11-02 12:39:01 -07005212MaybeObject* Heap::LookupSymbol(String* string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005213 if (string->IsSymbol()) return string;
5214 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07005215 Object* new_table;
5216 { MaybeObject* maybe_new_table =
5217 symbol_table()->LookupString(string, &symbol);
5218 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5219 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005220 // Can't use set_symbol_table because SymbolTable::cast knows that
5221 // SymbolTable is a singleton and checks for identity.
5222 roots_[kSymbolTableRootIndex] = new_table;
5223 ASSERT(symbol != NULL);
5224 return symbol;
5225}
5226
5227
5228bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5229 if (string->IsSymbol()) {
5230 *symbol = string;
5231 return true;
5232 }
5233 return symbol_table()->LookupSymbolIfExists(string, symbol);
5234}
5235
5236
5237#ifdef DEBUG
5238void Heap::ZapFromSpace() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005239 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5240 new_space_.FromSpaceEnd());
5241 while (it.has_next()) {
5242 NewSpacePage* page = it.next();
5243 for (Address cursor = page->area_start(), limit = page->area_end();
5244 cursor < limit;
5245 cursor += kPointerSize) {
5246 Memory::Address_at(cursor) = kFromSpaceZapValue;
5247 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005248 }
5249}
5250#endif // DEBUG
5251
5252
Ben Murdoch3bec4d22010-07-22 14:51:16 +01005253void Heap::IterateAndMarkPointersToFromSpace(Address start,
5254 Address end,
5255 ObjectSlotCallback callback) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005256 Address slot_address = start;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005257
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005258 // We are not collecting slots on new space objects during mutation
5259 // thus we have to scan for pointers to evacuation candidates when we
5260 // promote objects. But we should not record any slots in non-black
5261 // objects. Grey object's slots would be rescanned.
5262 // White object might not survive until the end of collection
5263 // it would be a violation of the invariant to record it's slots.
5264 bool record_slots = false;
5265 if (incremental_marking()->IsCompacting()) {
5266 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5267 record_slots = Marking::IsBlack(mark_bit);
5268 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005269
5270 while (slot_address < end) {
5271 Object** slot = reinterpret_cast<Object**>(slot_address);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005272 Object* object = *slot;
5273 // If the store buffer becomes overfull we mark pages as being exempt from
5274 // the store buffer. These pages are scanned to find pointers that point
5275 // to the new space. In that case we may hit newly promoted objects and
5276 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5277 if (object->IsHeapObject()) {
5278 if (Heap::InFromSpace(object)) {
5279 callback(reinterpret_cast<HeapObject**>(slot),
5280 HeapObject::cast(object));
5281 Object* new_object = *slot;
5282 if (InNewSpace(new_object)) {
5283 SLOW_ASSERT(Heap::InToSpace(new_object));
5284 SLOW_ASSERT(new_object->IsHeapObject());
5285 store_buffer_.EnterDirectlyIntoStoreBuffer(
5286 reinterpret_cast<Address>(slot));
5287 }
5288 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5289 } else if (record_slots &&
5290 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5291 mark_compact_collector()->RecordSlot(slot, slot, object);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005292 }
5293 }
5294 slot_address += kPointerSize;
5295 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005296}
5297
5298
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005299#ifdef DEBUG
5300typedef bool (*CheckStoreBufferFilter)(Object** addr);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005301
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005302
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005303bool IsAMapPointerAddress(Object** addr) {
5304 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5305 int mod = a % Map::kSize;
5306 return mod >= Map::kPointerFieldsBeginOffset &&
5307 mod < Map::kPointerFieldsEndOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005308}
5309
5310
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005311bool EverythingsAPointer(Object** addr) {
5312 return true;
5313}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005314
Steve Blocka7e24c12009-10-30 11:49:00 +00005315
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005316static void CheckStoreBuffer(Heap* heap,
5317 Object** current,
5318 Object** limit,
5319 Object**** store_buffer_position,
5320 Object*** store_buffer_top,
5321 CheckStoreBufferFilter filter,
5322 Address special_garbage_start,
5323 Address special_garbage_end) {
5324 Map* free_space_map = heap->free_space_map();
5325 for ( ; current < limit; current++) {
5326 Object* o = *current;
5327 Address current_address = reinterpret_cast<Address>(current);
5328 // Skip free space.
5329 if (o == free_space_map) {
5330 Address current_address = reinterpret_cast<Address>(current);
5331 FreeSpace* free_space =
5332 FreeSpace::cast(HeapObject::FromAddress(current_address));
5333 int skip = free_space->Size();
5334 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5335 ASSERT(skip > 0);
5336 current_address += skip - kPointerSize;
5337 current = reinterpret_cast<Object**>(current_address);
5338 continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00005339 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005340 // Skip the current linear allocation space between top and limit which is
5341 // unmarked with the free space map, but can contain junk.
5342 if (current_address == special_garbage_start &&
5343 special_garbage_end != special_garbage_start) {
5344 current_address = special_garbage_end - kPointerSize;
5345 current = reinterpret_cast<Object**>(current_address);
5346 continue;
5347 }
5348 if (!(*filter)(current)) continue;
5349 ASSERT(current_address < special_garbage_start ||
5350 current_address >= special_garbage_end);
5351 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5352 // We have to check that the pointer does not point into new space
5353 // without trying to cast it to a heap object since the hash field of
5354 // a string can contain values like 1 and 3 which are tagged null
5355 // pointers.
5356 if (!heap->InNewSpace(o)) continue;
5357 while (**store_buffer_position < current &&
5358 *store_buffer_position < store_buffer_top) {
5359 (*store_buffer_position)++;
5360 }
5361 if (**store_buffer_position != current ||
5362 *store_buffer_position == store_buffer_top) {
5363 Object** obj_start = current;
5364 while (!(*obj_start)->IsMap()) obj_start--;
5365 UNREACHABLE();
5366 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005367 }
5368}
5369
5370
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005371// Check that the store buffer contains all intergenerational pointers by
5372// scanning a page and ensuring that all pointers to young space are in the
5373// store buffer.
5374void Heap::OldPointerSpaceCheckStoreBuffer() {
5375 OldSpace* space = old_pointer_space();
5376 PageIterator pages(space);
5377
5378 store_buffer()->SortUniq();
5379
5380 while (pages.has_next()) {
5381 Page* page = pages.next();
5382 Object** current = reinterpret_cast<Object**>(page->area_start());
5383
5384 Address end = page->area_end();
5385
5386 Object*** store_buffer_position = store_buffer()->Start();
5387 Object*** store_buffer_top = store_buffer()->Top();
5388
5389 Object** limit = reinterpret_cast<Object**>(end);
5390 CheckStoreBuffer(this,
5391 current,
5392 limit,
5393 &store_buffer_position,
5394 store_buffer_top,
5395 &EverythingsAPointer,
5396 space->top(),
5397 space->limit());
5398 }
5399}
5400
5401
5402void Heap::MapSpaceCheckStoreBuffer() {
5403 MapSpace* space = map_space();
5404 PageIterator pages(space);
5405
5406 store_buffer()->SortUniq();
5407
5408 while (pages.has_next()) {
5409 Page* page = pages.next();
5410 Object** current = reinterpret_cast<Object**>(page->area_start());
5411
5412 Address end = page->area_end();
5413
5414 Object*** store_buffer_position = store_buffer()->Start();
5415 Object*** store_buffer_top = store_buffer()->Top();
5416
5417 Object** limit = reinterpret_cast<Object**>(end);
5418 CheckStoreBuffer(this,
5419 current,
5420 limit,
5421 &store_buffer_position,
5422 store_buffer_top,
5423 &IsAMapPointerAddress,
5424 space->top(),
5425 space->limit());
5426 }
5427}
5428
5429
5430void Heap::LargeObjectSpaceCheckStoreBuffer() {
5431 LargeObjectIterator it(lo_space());
5432 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5433 // We only have code, sequential strings, or fixed arrays in large
5434 // object space, and only fixed arrays can possibly contain pointers to
5435 // the young generation.
5436 if (object->IsFixedArray()) {
5437 Object*** store_buffer_position = store_buffer()->Start();
5438 Object*** store_buffer_top = store_buffer()->Top();
5439 Object** current = reinterpret_cast<Object**>(object->address());
5440 Object** limit =
5441 reinterpret_cast<Object**>(object->address() + object->Size());
5442 CheckStoreBuffer(this,
5443 current,
5444 limit,
5445 &store_buffer_position,
5446 store_buffer_top,
5447 &EverythingsAPointer,
5448 NULL,
5449 NULL);
5450 }
5451 }
5452}
5453#endif
5454
5455
Steve Blockd0582a62009-12-15 09:54:21 +00005456void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5457 IterateStrongRoots(v, mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00005458 IterateWeakRoots(v, mode);
5459}
5460
5461
5462void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005463 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Ben Murdochc7cc0282012-03-05 14:35:55 +00005464 v->Synchronize(VisitorSynchronization::kSymbolTable);
Ben Murdoch257744e2011-11-30 15:57:28 +00005465 if (mode != VISIT_ALL_IN_SCAVENGE &&
5466 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00005467 // Scavenge collections have special processing for this.
Steve Block44f0eee2011-05-26 01:26:41 +01005468 external_string_table_.Iterate(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005469 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005470 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
Steve Blocka7e24c12009-10-30 11:49:00 +00005471}
5472
5473
Steve Blockd0582a62009-12-15 09:54:21 +00005474void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005475 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005476 v->Synchronize(VisitorSynchronization::kStrongRootList);
Steve Blocka7e24c12009-10-30 11:49:00 +00005477
Iain Merrick75681382010-08-19 15:07:18 +01005478 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
Ben Murdochc7cc0282012-03-05 14:35:55 +00005479 v->Synchronize(VisitorSynchronization::kSymbol);
Steve Blocka7e24c12009-10-30 11:49:00 +00005480
Steve Block44f0eee2011-05-26 01:26:41 +01005481 isolate_->bootstrapper()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005482 v->Synchronize(VisitorSynchronization::kBootstrapper);
Steve Block44f0eee2011-05-26 01:26:41 +01005483 isolate_->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005484 v->Synchronize(VisitorSynchronization::kTop);
Steve Blocka7e24c12009-10-30 11:49:00 +00005485 Relocatable::Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005486 v->Synchronize(VisitorSynchronization::kRelocatable);
Steve Blocka7e24c12009-10-30 11:49:00 +00005487
5488#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +01005489 isolate_->debug()->Iterate(v);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005490 if (isolate_->deoptimizer_data() != NULL) {
5491 isolate_->deoptimizer_data()->Iterate(v);
5492 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005493#endif
Ben Murdochc7cc0282012-03-05 14:35:55 +00005494 v->Synchronize(VisitorSynchronization::kDebug);
Steve Block44f0eee2011-05-26 01:26:41 +01005495 isolate_->compilation_cache()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005496 v->Synchronize(VisitorSynchronization::kCompilationCache);
Steve Blocka7e24c12009-10-30 11:49:00 +00005497
5498 // Iterate over local handles in handle scopes.
Steve Block44f0eee2011-05-26 01:26:41 +01005499 isolate_->handle_scope_implementer()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005500 v->Synchronize(VisitorSynchronization::kHandleScope);
Steve Blocka7e24c12009-10-30 11:49:00 +00005501
Leon Clarkee46be812010-01-19 14:06:41 +00005502 // Iterate over the builtin code objects and code stubs in the
5503 // heap. Note that it is not necessary to iterate over code objects
5504 // on scavenge collections.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005505 if (mode != VISIT_ALL_IN_SCAVENGE) {
Steve Block44f0eee2011-05-26 01:26:41 +01005506 isolate_->builtins()->IterateBuiltins(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005507 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005508 v->Synchronize(VisitorSynchronization::kBuiltins);
Steve Blocka7e24c12009-10-30 11:49:00 +00005509
5510 // Iterate over global handles.
Ben Murdoch257744e2011-11-30 15:57:28 +00005511 switch (mode) {
5512 case VISIT_ONLY_STRONG:
5513 isolate_->global_handles()->IterateStrongRoots(v);
5514 break;
5515 case VISIT_ALL_IN_SCAVENGE:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005516 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
Ben Murdoch257744e2011-11-30 15:57:28 +00005517 break;
5518 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5519 case VISIT_ALL:
5520 isolate_->global_handles()->IterateAllRoots(v);
5521 break;
Steve Blockd0582a62009-12-15 09:54:21 +00005522 }
Ben Murdochc7cc0282012-03-05 14:35:55 +00005523 v->Synchronize(VisitorSynchronization::kGlobalHandles);
Steve Blocka7e24c12009-10-30 11:49:00 +00005524
5525 // Iterate over pointers being held by inactive threads.
Steve Block44f0eee2011-05-26 01:26:41 +01005526 isolate_->thread_manager()->Iterate(v);
Ben Murdochc7cc0282012-03-05 14:35:55 +00005527 v->Synchronize(VisitorSynchronization::kThreadManager);
Leon Clarked91b9f72010-01-27 17:25:45 +00005528
5529 // Iterate over the pointers the Serialization/Deserialization code is
5530 // holding.
5531 // During garbage collection this keeps the partial snapshot cache alive.
5532 // During deserialization of the startup snapshot this creates the partial
5533 // snapshot cache and deserializes the objects it refers to. During
5534 // serialization this does nothing, since the partial snapshot cache is
5535 // empty. However the next thing we do is create the partial snapshot,
5536 // filling up the partial snapshot cache with objects it needs as we go.
5537 SerializerDeserializer::Iterate(v);
5538 // We don't do a v->Synchronize call here, because in debug mode that will
5539 // output a flag to the snapshot. However at this point the serializer and
5540 // deserializer are deliberately a little unsynchronized (see above) so the
5541 // checking of the sync flag in the snapshot would fail.
Steve Blocka7e24c12009-10-30 11:49:00 +00005542}
Steve Blocka7e24c12009-10-30 11:49:00 +00005543
5544
Steve Blocka7e24c12009-10-30 11:49:00 +00005545// TODO(1236194): Since the heap size is configurable on the command line
5546// and through the API, we should gracefully handle the case that the heap
5547// size is not big enough to fit all the initial objects.
Russell Brenner90bac252010-11-18 13:33:46 -08005548bool Heap::ConfigureHeap(int max_semispace_size,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005549 intptr_t max_old_gen_size,
5550 intptr_t max_executable_size) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00005551 if (HasBeenSetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005552
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005553 if (max_semispace_size > 0) {
5554 if (max_semispace_size < Page::kPageSize) {
5555 max_semispace_size = Page::kPageSize;
5556 if (FLAG_trace_gc) {
5557 PrintF("Max semispace size cannot be less than %dkbytes\n",
5558 Page::kPageSize >> 10);
5559 }
5560 }
5561 max_semispace_size_ = max_semispace_size;
5562 }
Steve Block3ce2e202009-11-05 08:53:23 +00005563
5564 if (Snapshot::IsEnabled()) {
5565 // If we are using a snapshot we always reserve the default amount
5566 // of memory for each semispace because code in the snapshot has
5567 // write-barrier code that relies on the size and alignment of new
5568 // space. We therefore cannot use a larger max semispace size
5569 // than the default reserved semispace size.
5570 if (max_semispace_size_ > reserved_semispace_size_) {
5571 max_semispace_size_ = reserved_semispace_size_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005572 if (FLAG_trace_gc) {
5573 PrintF("Max semispace size cannot be more than %dkbytes\n",
5574 reserved_semispace_size_ >> 10);
5575 }
Steve Block3ce2e202009-11-05 08:53:23 +00005576 }
5577 } else {
5578 // If we are not using snapshots we reserve space for the actual
5579 // max semispace size.
5580 reserved_semispace_size_ = max_semispace_size_;
5581 }
5582
5583 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Russell Brenner90bac252010-11-18 13:33:46 -08005584 if (max_executable_size > 0) {
5585 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5586 }
5587
5588 // The max executable size must be less than or equal to the max old
5589 // generation size.
5590 if (max_executable_size_ > max_old_generation_size_) {
5591 max_executable_size_ = max_old_generation_size_;
5592 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005593
5594 // The new space size must be a power of two to support single-bit testing
5595 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00005596 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5597 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5598 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5599 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00005600
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005601 // The old generation is paged and needs at least one page for each space.
5602 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5603 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5604 Page::kPageSize),
5605 RoundUp(max_old_generation_size_,
5606 Page::kPageSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00005607
Steve Block44f0eee2011-05-26 01:26:41 +01005608 configured_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00005609 return true;
5610}
5611
5612
5613bool Heap::ConfigureHeapDefault() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005614 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5615 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5616 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
Steve Blocka7e24c12009-10-30 11:49:00 +00005617}
5618
5619
Ben Murdochbb769b22010-08-11 14:56:33 +01005620void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
Iain Merrick75681382010-08-19 15:07:18 +01005621 *stats->start_marker = HeapStats::kStartMarker;
5622 *stats->end_marker = HeapStats::kEndMarker;
Ben Murdochf87a2032010-10-22 12:50:53 +01005623 *stats->new_space_size = new_space_.SizeAsInt();
5624 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005625 *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
Steve Blockd0582a62009-12-15 09:54:21 +00005626 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005627 *stats->old_data_space_size = old_data_space_->SizeOfObjects();
Steve Blockd0582a62009-12-15 09:54:21 +00005628 *stats->old_data_space_capacity = old_data_space_->Capacity();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005629 *stats->code_space_size = code_space_->SizeOfObjects();
Steve Blockd0582a62009-12-15 09:54:21 +00005630 *stats->code_space_capacity = code_space_->Capacity();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005631 *stats->map_space_size = map_space_->SizeOfObjects();
Steve Blockd0582a62009-12-15 09:54:21 +00005632 *stats->map_space_capacity = map_space_->Capacity();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005633 *stats->cell_space_size = cell_space_->SizeOfObjects();
Steve Blockd0582a62009-12-15 09:54:21 +00005634 *stats->cell_space_capacity = cell_space_->Capacity();
5635 *stats->lo_space_size = lo_space_->Size();
Steve Block44f0eee2011-05-26 01:26:41 +01005636 isolate_->global_handles()->RecordStats(stats);
5637 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
Ben Murdochbb769b22010-08-11 14:56:33 +01005638 *stats->memory_allocator_capacity =
Steve Block44f0eee2011-05-26 01:26:41 +01005639 isolate()->memory_allocator()->Size() +
5640 isolate()->memory_allocator()->Available();
Iain Merrick75681382010-08-19 15:07:18 +01005641 *stats->os_error = OS::GetLastError();
Steve Block44f0eee2011-05-26 01:26:41 +01005642 isolate()->memory_allocator()->Available();
Ben Murdochbb769b22010-08-11 14:56:33 +01005643 if (take_snapshot) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005644 HeapIterator iterator;
Ben Murdochbb769b22010-08-11 14:56:33 +01005645 for (HeapObject* obj = iterator.next();
5646 obj != NULL;
5647 obj = iterator.next()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005648 InstanceType type = obj->map()->instance_type();
5649 ASSERT(0 <= type && type <= LAST_TYPE);
5650 stats->objects_per_type[type]++;
5651 stats->size_per_type[type] += obj->Size();
5652 }
5653 }
Steve Blockd0582a62009-12-15 09:54:21 +00005654}
5655
5656
Ben Murdochf87a2032010-10-22 12:50:53 +01005657intptr_t Heap::PromotedSpaceSize() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005658 return old_pointer_space_->Size()
5659 + old_data_space_->Size()
5660 + code_space_->Size()
5661 + map_space_->Size()
5662 + cell_space_->Size()
5663 + lo_space_->Size();
5664}
5665
5666
Ben Murdochc7cc0282012-03-05 14:35:55 +00005667intptr_t Heap::PromotedSpaceSizeOfObjects() {
5668 return old_pointer_space_->SizeOfObjects()
5669 + old_data_space_->SizeOfObjects()
5670 + code_space_->SizeOfObjects()
5671 + map_space_->SizeOfObjects()
5672 + cell_space_->SizeOfObjects()
5673 + lo_space_->SizeOfObjects();
5674}
5675
5676
Steve Blocka7e24c12009-10-30 11:49:00 +00005677int Heap::PromotedExternalMemorySize() {
5678 if (amount_of_external_allocated_memory_
5679 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5680 return amount_of_external_allocated_memory_
5681 - amount_of_external_allocated_memory_at_last_global_gc_;
5682}
5683
Steve Block44f0eee2011-05-26 01:26:41 +01005684#ifdef DEBUG
5685
5686// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5687static const int kMarkTag = 2;
5688
5689
5690class HeapDebugUtils {
5691 public:
5692 explicit HeapDebugUtils(Heap* heap)
5693 : search_for_any_global_(false),
5694 search_target_(NULL),
5695 found_target_(false),
5696 object_stack_(20),
5697 heap_(heap) {
5698 }
5699
5700 class MarkObjectVisitor : public ObjectVisitor {
5701 public:
5702 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5703
5704 void VisitPointers(Object** start, Object** end) {
5705 // Copy all HeapObject pointers in [start, end)
5706 for (Object** p = start; p < end; p++) {
5707 if ((*p)->IsHeapObject())
5708 utils_->MarkObjectRecursively(p);
5709 }
5710 }
5711
5712 HeapDebugUtils* utils_;
5713 };
5714
5715 void MarkObjectRecursively(Object** p) {
5716 if (!(*p)->IsHeapObject()) return;
5717
5718 HeapObject* obj = HeapObject::cast(*p);
5719
5720 Object* map = obj->map();
5721
5722 if (!map->IsHeapObject()) return; // visited before
5723
5724 if (found_target_) return; // stop if target found
5725 object_stack_.Add(obj);
5726 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5727 (!search_for_any_global_ && (obj == search_target_))) {
5728 found_target_ = true;
5729 return;
5730 }
5731
5732 // not visited yet
5733 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5734
5735 Address map_addr = map_p->address();
5736
Ben Murdochc7cc0282012-03-05 14:35:55 +00005737 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
Steve Block44f0eee2011-05-26 01:26:41 +01005738
5739 MarkObjectRecursively(&map);
5740
5741 MarkObjectVisitor mark_visitor(this);
5742
5743 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5744 &mark_visitor);
5745
5746 if (!found_target_) // don't pop if found the target
5747 object_stack_.RemoveLast();
5748 }
5749
5750
5751 class UnmarkObjectVisitor : public ObjectVisitor {
5752 public:
5753 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5754
5755 void VisitPointers(Object** start, Object** end) {
5756 // Copy all HeapObject pointers in [start, end)
5757 for (Object** p = start; p < end; p++) {
5758 if ((*p)->IsHeapObject())
5759 utils_->UnmarkObjectRecursively(p);
5760 }
5761 }
5762
5763 HeapDebugUtils* utils_;
5764 };
5765
5766
5767 void UnmarkObjectRecursively(Object** p) {
5768 if (!(*p)->IsHeapObject()) return;
5769
5770 HeapObject* obj = HeapObject::cast(*p);
5771
5772 Object* map = obj->map();
5773
5774 if (map->IsHeapObject()) return; // unmarked already
5775
5776 Address map_addr = reinterpret_cast<Address>(map);
5777
5778 map_addr -= kMarkTag;
5779
5780 ASSERT_TAG_ALIGNED(map_addr);
5781
5782 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5783
Ben Murdochc7cc0282012-03-05 14:35:55 +00005784 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
Steve Block44f0eee2011-05-26 01:26:41 +01005785
5786 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5787
5788 UnmarkObjectVisitor unmark_visitor(this);
5789
5790 obj->IterateBody(Map::cast(map_p)->instance_type(),
5791 obj->SizeFromMap(Map::cast(map_p)),
5792 &unmark_visitor);
5793 }
5794
5795
5796 void MarkRootObjectRecursively(Object** root) {
5797 if (search_for_any_global_) {
5798 ASSERT(search_target_ == NULL);
5799 } else {
5800 ASSERT(search_target_->IsHeapObject());
5801 }
5802 found_target_ = false;
5803 object_stack_.Clear();
5804
5805 MarkObjectRecursively(root);
5806 UnmarkObjectRecursively(root);
5807
5808 if (found_target_) {
5809 PrintF("=====================================\n");
5810 PrintF("==== Path to object ====\n");
5811 PrintF("=====================================\n\n");
5812
5813 ASSERT(!object_stack_.is_empty());
5814 for (int i = 0; i < object_stack_.length(); i++) {
5815 if (i > 0) PrintF("\n |\n |\n V\n\n");
5816 Object* obj = object_stack_[i];
5817 obj->Print();
5818 }
5819 PrintF("=====================================\n");
5820 }
5821 }
5822
5823 // Helper class for visiting HeapObjects recursively.
5824 class MarkRootVisitor: public ObjectVisitor {
5825 public:
5826 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5827
5828 void VisitPointers(Object** start, Object** end) {
5829 // Visit all HeapObject pointers in [start, end)
5830 for (Object** p = start; p < end; p++) {
5831 if ((*p)->IsHeapObject())
5832 utils_->MarkRootObjectRecursively(p);
5833 }
5834 }
5835
5836 HeapDebugUtils* utils_;
5837 };
5838
5839 bool search_for_any_global_;
5840 Object* search_target_;
5841 bool found_target_;
5842 List<Object*> object_stack_;
5843 Heap* heap_;
5844
5845 friend class Heap;
5846};
5847
5848#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005849
Ben Murdochc7cc0282012-03-05 14:35:55 +00005850bool Heap::SetUp(bool create_heap_objects) {
Steve Block44f0eee2011-05-26 01:26:41 +01005851#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005852 allocation_timeout_ = FLAG_gc_interval;
Steve Block44f0eee2011-05-26 01:26:41 +01005853 debug_utils_ = new HeapDebugUtils(this);
5854#endif
5855
Steve Blocka7e24c12009-10-30 11:49:00 +00005856 // Initialize heap spaces and initial maps and objects. Whenever something
5857 // goes wrong, just return false. The caller should check the results and
5858 // call Heap::TearDown() to release allocated memory.
5859 //
Ben Murdochc7cc0282012-03-05 14:35:55 +00005860 // If the heap is not yet configured (e.g. through the API), configure it.
Steve Blocka7e24c12009-10-30 11:49:00 +00005861 // Configuration is based on the flags new-space-size (really the semispace
5862 // size) and old-space-size if set or the initial values of semispace_size_
5863 // and old_generation_size_ otherwise.
Steve Block44f0eee2011-05-26 01:26:41 +01005864 if (!configured_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005865 if (!ConfigureHeapDefault()) return false;
5866 }
5867
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005868 gc_initializer_mutex.Pointer()->Lock();
Steve Block44f0eee2011-05-26 01:26:41 +01005869 static bool initialized_gc = false;
5870 if (!initialized_gc) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005871 initialized_gc = true;
5872 InitializeScavengingVisitorsTables();
5873 NewSpaceScavenger::Initialize();
5874 MarkCompactCollector::Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01005875 }
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005876 gc_initializer_mutex.Pointer()->Unlock();
Iain Merrick75681382010-08-19 15:07:18 +01005877
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005878 MarkMapPointersAsEncoded(false);
5879
Ben Murdochc7cc0282012-03-05 14:35:55 +00005880 // Set up memory allocator.
5881 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
Steve Block44f0eee2011-05-26 01:26:41 +01005882 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005883
Ben Murdochc7cc0282012-03-05 14:35:55 +00005884 // Set up new space.
5885 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
Steve Block3ce2e202009-11-05 08:53:23 +00005886 return false;
5887 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005888
5889 // Initialize old pointer space.
5890 old_pointer_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005891 new OldSpace(this,
5892 max_old_generation_size_,
5893 OLD_POINTER_SPACE,
5894 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005895 if (old_pointer_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005896 if (!old_pointer_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005897
5898 // Initialize old data space.
5899 old_data_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005900 new OldSpace(this,
5901 max_old_generation_size_,
5902 OLD_DATA_SPACE,
5903 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005904 if (old_data_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005905 if (!old_data_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005906
5907 // Initialize the code space, set its maximum capacity to the old
5908 // generation size. It needs executable memory.
5909 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5910 // virtual address space, so that they can call each other with near calls.
5911 if (code_range_size_ > 0) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00005912 if (!isolate_->code_range()->SetUp(code_range_size_)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005913 return false;
5914 }
5915 }
5916
5917 code_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005918 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005919 if (code_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005920 if (!code_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005921
5922 // Initialize map space.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01005923 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005924 if (map_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005925 if (!map_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005926
5927 // Initialize global property cell space.
Steve Block44f0eee2011-05-26 01:26:41 +01005928 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005929 if (cell_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005930 if (!cell_space_->SetUp()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005931
5932 // The large object code space may contain code or data. We set the memory
5933 // to be non-executable here for safety, but this means we need to enable it
5934 // explicitly when allocating large code objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005935 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005936 if (lo_space_ == NULL) return false;
Ben Murdochc7cc0282012-03-05 14:35:55 +00005937 if (!lo_space_->SetUp()) return false;
5938
5939 // Set up the seed that is used to randomize the string hash function.
5940 ASSERT(hash_seed() == 0);
5941 if (FLAG_randomize_hashes) {
5942 if (FLAG_hash_seed == 0) {
5943 set_hash_seed(
5944 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
5945 } else {
5946 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5947 }
5948 }
5949
Steve Blocka7e24c12009-10-30 11:49:00 +00005950 if (create_heap_objects) {
5951 // Create initial maps.
5952 if (!CreateInitialMaps()) return false;
5953 if (!CreateApiObjects()) return false;
5954
5955 // Create initial objects
5956 if (!CreateInitialObjects()) return false;
Ben Murdochf87a2032010-10-22 12:50:53 +01005957
5958 global_contexts_list_ = undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005959 }
5960
Steve Block44f0eee2011-05-26 01:26:41 +01005961 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5962 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005963
Ben Murdochc7cc0282012-03-05 14:35:55 +00005964 store_buffer()->SetUp();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005965
Steve Blocka7e24c12009-10-30 11:49:00 +00005966 return true;
5967}
5968
5969
Steve Blockd0582a62009-12-15 09:54:21 +00005970void Heap::SetStackLimits() {
Steve Block44f0eee2011-05-26 01:26:41 +01005971 ASSERT(isolate_ != NULL);
5972 ASSERT(isolate_ == isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00005973 // On 64 bit machines, pointers are generally out of range of Smis. We write
5974 // something that looks like an out of range Smi to the GC.
5975
Steve Blockd0582a62009-12-15 09:54:21 +00005976 // Set up the special root array entries containing the stack limits.
5977 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00005978 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00005979 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005980 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blockd0582a62009-12-15 09:54:21 +00005981 roots_[kRealStackLimitRootIndex] =
5982 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005983 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00005984}
5985
5986
5987void Heap::TearDown() {
Leon Clarkef7060e22010-06-03 12:02:55 +01005988 if (FLAG_print_cumulative_gc_stat) {
5989 PrintF("\n\n");
5990 PrintF("gc_count=%d ", gc_count_);
5991 PrintF("mark_sweep_count=%d ", ms_count_);
Steve Block44f0eee2011-05-26 01:26:41 +01005992 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5993 PrintF("min_in_mutator=%d ", get_min_in_mutator());
Ben Murdochf87a2032010-10-22 12:50:53 +01005994 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
Steve Block44f0eee2011-05-26 01:26:41 +01005995 get_max_alive_after_gc());
Leon Clarkef7060e22010-06-03 12:02:55 +01005996 PrintF("\n\n");
5997 }
5998
Steve Block44f0eee2011-05-26 01:26:41 +01005999 isolate_->global_handles()->TearDown();
Steve Blocka7e24c12009-10-30 11:49:00 +00006000
Steve Block44f0eee2011-05-26 01:26:41 +01006001 external_string_table_.TearDown();
Leon Clarkee46be812010-01-19 14:06:41 +00006002
Steve Blocka7e24c12009-10-30 11:49:00 +00006003 new_space_.TearDown();
6004
6005 if (old_pointer_space_ != NULL) {
6006 old_pointer_space_->TearDown();
6007 delete old_pointer_space_;
6008 old_pointer_space_ = NULL;
6009 }
6010
6011 if (old_data_space_ != NULL) {
6012 old_data_space_->TearDown();
6013 delete old_data_space_;
6014 old_data_space_ = NULL;
6015 }
6016
6017 if (code_space_ != NULL) {
6018 code_space_->TearDown();
6019 delete code_space_;
6020 code_space_ = NULL;
6021 }
6022
6023 if (map_space_ != NULL) {
6024 map_space_->TearDown();
6025 delete map_space_;
6026 map_space_ = NULL;
6027 }
6028
6029 if (cell_space_ != NULL) {
6030 cell_space_->TearDown();
6031 delete cell_space_;
6032 cell_space_ = NULL;
6033 }
6034
6035 if (lo_space_ != NULL) {
6036 lo_space_->TearDown();
6037 delete lo_space_;
6038 lo_space_ = NULL;
6039 }
6040
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006041 store_buffer()->TearDown();
6042 incremental_marking()->TearDown();
6043
Steve Block44f0eee2011-05-26 01:26:41 +01006044 isolate_->memory_allocator()->TearDown();
6045
6046#ifdef DEBUG
6047 delete debug_utils_;
6048 debug_utils_ = NULL;
6049#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006050}
6051
6052
6053void Heap::Shrink() {
6054 // Try to shrink all paged spaces.
6055 PagedSpaces spaces;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006056 for (PagedSpace* space = spaces.next();
6057 space != NULL;
6058 space = spaces.next()) {
6059 space->ReleaseAllUnusedPages();
6060 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006061}
6062
6063
Steve Block6ded16b2010-05-10 14:33:55 +01006064void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6065 ASSERT(callback != NULL);
6066 GCPrologueCallbackPair pair(callback, gc_type);
6067 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6068 return gc_prologue_callbacks_.Add(pair);
6069}
6070
6071
6072void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6073 ASSERT(callback != NULL);
6074 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6075 if (gc_prologue_callbacks_[i].callback == callback) {
6076 gc_prologue_callbacks_.Remove(i);
6077 return;
6078 }
6079 }
6080 UNREACHABLE();
6081}
6082
6083
6084void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6085 ASSERT(callback != NULL);
6086 GCEpilogueCallbackPair pair(callback, gc_type);
6087 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6088 return gc_epilogue_callbacks_.Add(pair);
6089}
6090
6091
6092void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6093 ASSERT(callback != NULL);
6094 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6095 if (gc_epilogue_callbacks_[i].callback == callback) {
6096 gc_epilogue_callbacks_.Remove(i);
6097 return;
6098 }
6099 }
6100 UNREACHABLE();
6101}
6102
6103
Steve Blocka7e24c12009-10-30 11:49:00 +00006104#ifdef DEBUG
6105
6106class PrintHandleVisitor: public ObjectVisitor {
6107 public:
6108 void VisitPointers(Object** start, Object** end) {
6109 for (Object** p = start; p < end; p++)
Ben Murdochf87a2032010-10-22 12:50:53 +01006110 PrintF(" handle %p to %p\n",
6111 reinterpret_cast<void*>(p),
6112 reinterpret_cast<void*>(*p));
Steve Blocka7e24c12009-10-30 11:49:00 +00006113 }
6114};
6115
6116void Heap::PrintHandles() {
6117 PrintF("Handles:\n");
6118 PrintHandleVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +01006119 isolate_->handle_scope_implementer()->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +00006120}
6121
6122#endif
6123
6124
6125Space* AllSpaces::next() {
6126 switch (counter_++) {
6127 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006128 return HEAP->new_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006129 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006130 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006131 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006132 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006133 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006134 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006135 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006136 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006137 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006138 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006139 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006140 return HEAP->lo_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006141 default:
6142 return NULL;
6143 }
6144}
6145
6146
6147PagedSpace* PagedSpaces::next() {
6148 switch (counter_++) {
6149 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006150 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006151 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006152 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006153 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006154 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006155 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006156 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006157 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006158 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006159 default:
6160 return NULL;
6161 }
6162}
6163
6164
6165
6166OldSpace* OldSpaces::next() {
6167 switch (counter_++) {
6168 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006169 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006170 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006171 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006172 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006173 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00006174 default:
6175 return NULL;
6176 }
6177}
6178
6179
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006180SpaceIterator::SpaceIterator()
6181 : current_space_(FIRST_SPACE),
6182 iterator_(NULL),
6183 size_func_(NULL) {
6184}
6185
6186
6187SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6188 : current_space_(FIRST_SPACE),
6189 iterator_(NULL),
6190 size_func_(size_func) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006191}
6192
6193
6194SpaceIterator::~SpaceIterator() {
6195 // Delete active iterator if any.
6196 delete iterator_;
6197}
6198
6199
6200bool SpaceIterator::has_next() {
6201 // Iterate until no more spaces.
6202 return current_space_ != LAST_SPACE;
6203}
6204
6205
6206ObjectIterator* SpaceIterator::next() {
6207 if (iterator_ != NULL) {
6208 delete iterator_;
6209 iterator_ = NULL;
6210 // Move to the next space
6211 current_space_++;
6212 if (current_space_ > LAST_SPACE) {
6213 return NULL;
6214 }
6215 }
6216
6217 // Return iterator for the new current space.
6218 return CreateIterator();
6219}
6220
6221
6222// Create an iterator for the space to iterate.
6223ObjectIterator* SpaceIterator::CreateIterator() {
6224 ASSERT(iterator_ == NULL);
6225
6226 switch (current_space_) {
6227 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006228 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006229 break;
6230 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006231 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006232 break;
6233 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006234 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006235 break;
6236 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006237 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006238 break;
6239 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006240 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006241 break;
6242 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006243 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006244 break;
6245 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01006246 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006247 break;
6248 }
6249
6250 // Return the newly allocated iterator;
6251 ASSERT(iterator_ != NULL);
6252 return iterator_;
6253}
6254
6255
Ben Murdochb0fe1622011-05-05 13:52:32 +01006256class HeapObjectsFilter {
6257 public:
6258 virtual ~HeapObjectsFilter() {}
6259 virtual bool SkipObject(HeapObject* object) = 0;
6260};
6261
6262
Ben Murdochb0fe1622011-05-05 13:52:32 +01006263class UnreachableObjectsFilter : public HeapObjectsFilter {
6264 public:
6265 UnreachableObjectsFilter() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006266 MarkReachableObjects();
6267 }
6268
6269 ~UnreachableObjectsFilter() {
6270 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006271 }
6272
6273 bool SkipObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006274 MarkBit mark_bit = Marking::MarkBitFrom(object);
6275 return !mark_bit.Get();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006276 }
6277
6278 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006279 class MarkingVisitor : public ObjectVisitor {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006280 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006281 MarkingVisitor() : marking_stack_(10) {}
Ben Murdochb0fe1622011-05-05 13:52:32 +01006282
6283 void VisitPointers(Object** start, Object** end) {
6284 for (Object** p = start; p < end; p++) {
6285 if (!(*p)->IsHeapObject()) continue;
6286 HeapObject* obj = HeapObject::cast(*p);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006287 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6288 if (!mark_bit.Get()) {
6289 mark_bit.Set();
6290 marking_stack_.Add(obj);
Ben Murdochb0fe1622011-05-05 13:52:32 +01006291 }
6292 }
6293 }
6294
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006295 void TransitiveClosure() {
6296 while (!marking_stack_.is_empty()) {
6297 HeapObject* obj = marking_stack_.RemoveLast();
6298 obj->Iterate(this);
6299 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01006300 }
6301
6302 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006303 List<HeapObject*> marking_stack_;
Ben Murdochb0fe1622011-05-05 13:52:32 +01006304 };
6305
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006306 void MarkReachableObjects() {
6307 Heap* heap = Isolate::Current()->heap();
6308 MarkingVisitor visitor;
6309 heap->IterateRoots(&visitor, VISIT_ALL);
6310 visitor.TransitiveClosure();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006311 }
6312
6313 AssertNoAllocation no_alloc;
6314};
6315
6316
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006317HeapIterator::HeapIterator()
6318 : filtering_(HeapIterator::kNoFiltering),
6319 filter_(NULL) {
6320 Init();
6321}
6322
6323
Ben Murdochb0fe1622011-05-05 13:52:32 +01006324HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006325 : filtering_(filtering),
6326 filter_(NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006327 Init();
6328}
6329
6330
6331HeapIterator::~HeapIterator() {
6332 Shutdown();
6333}
6334
6335
6336void HeapIterator::Init() {
6337 // Start the iteration.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006338 space_iterator_ = new SpaceIterator;
Ben Murdochb0fe1622011-05-05 13:52:32 +01006339 switch (filtering_) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006340 case kFilterUnreachable:
6341 filter_ = new UnreachableObjectsFilter;
6342 break;
6343 default:
6344 break;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006345 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006346 object_iterator_ = space_iterator_->next();
6347}
6348
6349
6350void HeapIterator::Shutdown() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006351#ifdef DEBUG
Ben Murdochb0fe1622011-05-05 13:52:32 +01006352 // Assert that in filtering mode we have iterated through all
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006353 // objects. Otherwise, heap will be left in an inconsistent state.
Ben Murdochb0fe1622011-05-05 13:52:32 +01006354 if (filtering_ != kNoFiltering) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006355 ASSERT(object_iterator_ == NULL);
6356 }
6357#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006358 // Make sure the last iterator is deallocated.
6359 delete space_iterator_;
6360 space_iterator_ = NULL;
6361 object_iterator_ = NULL;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006362 delete filter_;
6363 filter_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006364}
6365
6366
Leon Clarked91b9f72010-01-27 17:25:45 +00006367HeapObject* HeapIterator::next() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006368 if (filter_ == NULL) return NextObject();
6369
6370 HeapObject* obj = NextObject();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006371 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08006372 return obj;
6373}
6374
6375
6376HeapObject* HeapIterator::NextObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006377 // No iterator means we are done.
Leon Clarked91b9f72010-01-27 17:25:45 +00006378 if (object_iterator_ == NULL) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006379
Leon Clarked91b9f72010-01-27 17:25:45 +00006380 if (HeapObject* obj = object_iterator_->next_object()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006381 // If the current iterator has more objects we are fine.
Leon Clarked91b9f72010-01-27 17:25:45 +00006382 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006383 } else {
6384 // Go though the spaces looking for one that has objects.
6385 while (space_iterator_->has_next()) {
6386 object_iterator_ = space_iterator_->next();
Leon Clarked91b9f72010-01-27 17:25:45 +00006387 if (HeapObject* obj = object_iterator_->next_object()) {
6388 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006389 }
6390 }
6391 }
6392 // Done with the last space.
6393 object_iterator_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00006394 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006395}
6396
6397
6398void HeapIterator::reset() {
6399 // Restart the iterator.
6400 Shutdown();
6401 Init();
6402}
6403
6404
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006405#if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
Steve Blocka7e24c12009-10-30 11:49:00 +00006406
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006407Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00006408
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006409class PathTracer::MarkVisitor: public ObjectVisitor {
Steve Blocka7e24c12009-10-30 11:49:00 +00006410 public:
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006411 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00006412 void VisitPointers(Object** start, Object** end) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006413 // Scan all HeapObject pointers in [start, end)
6414 for (Object** p = start; !tracer_->found() && (p < end); p++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006415 if ((*p)->IsHeapObject())
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006416 tracer_->MarkRecursively(p, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006417 }
6418 }
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006419
6420 private:
6421 PathTracer* tracer_;
Steve Blocka7e24c12009-10-30 11:49:00 +00006422};
6423
Steve Blocka7e24c12009-10-30 11:49:00 +00006424
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006425class PathTracer::UnmarkVisitor: public ObjectVisitor {
6426 public:
6427 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6428 void VisitPointers(Object** start, Object** end) {
6429 // Scan all HeapObject pointers in [start, end)
6430 for (Object** p = start; p < end; p++) {
6431 if ((*p)->IsHeapObject())
6432 tracer_->UnmarkRecursively(p, this);
6433 }
6434 }
6435
6436 private:
6437 PathTracer* tracer_;
6438};
6439
6440
6441void PathTracer::VisitPointers(Object** start, Object** end) {
6442 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6443 // Visit all HeapObject pointers in [start, end)
6444 for (Object** p = start; !done && (p < end); p++) {
6445 if ((*p)->IsHeapObject()) {
6446 TracePathFrom(p);
6447 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6448 }
6449 }
6450}
6451
6452
6453void PathTracer::Reset() {
6454 found_target_ = false;
6455 object_stack_.Clear();
6456}
6457
6458
6459void PathTracer::TracePathFrom(Object** root) {
6460 ASSERT((search_target_ == kAnyGlobalObject) ||
6461 search_target_->IsHeapObject());
6462 found_target_in_trace_ = false;
6463 object_stack_.Clear();
6464
6465 MarkVisitor mark_visitor(this);
6466 MarkRecursively(root, &mark_visitor);
6467
6468 UnmarkVisitor unmark_visitor(this);
6469 UnmarkRecursively(root, &unmark_visitor);
6470
6471 ProcessResults();
6472}
6473
6474
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006475static bool SafeIsGlobalContext(HeapObject* obj) {
6476 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6477}
6478
6479
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006480void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006481 if (!(*p)->IsHeapObject()) return;
6482
6483 HeapObject* obj = HeapObject::cast(*p);
6484
6485 Object* map = obj->map();
6486
6487 if (!map->IsHeapObject()) return; // visited before
6488
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006489 if (found_target_in_trace_) return; // stop if target found
6490 object_stack_.Add(obj);
6491 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6492 (obj == search_target_)) {
6493 found_target_in_trace_ = true;
6494 found_target_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00006495 return;
6496 }
6497
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006498 bool is_global_context = SafeIsGlobalContext(obj);
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006499
Steve Blocka7e24c12009-10-30 11:49:00 +00006500 // not visited yet
6501 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6502
6503 Address map_addr = map_p->address();
6504
Ben Murdochc7cc0282012-03-05 14:35:55 +00006505 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
Steve Blocka7e24c12009-10-30 11:49:00 +00006506
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006507 // Scan the object body.
6508 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6509 // This is specialized to scan Context's properly.
6510 Object** start = reinterpret_cast<Object**>(obj->address() +
6511 Context::kHeaderSize);
6512 Object** end = reinterpret_cast<Object**>(obj->address() +
6513 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6514 mark_visitor->VisitPointers(start, end);
6515 } else {
6516 obj->IterateBody(map_p->instance_type(),
6517 obj->SizeFromMap(map_p),
6518 mark_visitor);
6519 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006520
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006521 // Scan the map after the body because the body is a lot more interesting
6522 // when doing leak detection.
6523 MarkRecursively(&map, mark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006524
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006525 if (!found_target_in_trace_) // don't pop if found the target
6526 object_stack_.RemoveLast();
Steve Blocka7e24c12009-10-30 11:49:00 +00006527}
6528
6529
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006530void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006531 if (!(*p)->IsHeapObject()) return;
6532
6533 HeapObject* obj = HeapObject::cast(*p);
6534
6535 Object* map = obj->map();
6536
6537 if (map->IsHeapObject()) return; // unmarked already
6538
6539 Address map_addr = reinterpret_cast<Address>(map);
6540
6541 map_addr -= kMarkTag;
6542
6543 ASSERT_TAG_ALIGNED(map_addr);
6544
6545 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6546
Ben Murdochc7cc0282012-03-05 14:35:55 +00006547 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
Steve Blocka7e24c12009-10-30 11:49:00 +00006548
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006549 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006550
6551 obj->IterateBody(Map::cast(map_p)->instance_type(),
6552 obj->SizeFromMap(Map::cast(map_p)),
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006553 unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006554}
6555
6556
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006557void PathTracer::ProcessResults() {
6558 if (found_target_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006559 PrintF("=====================================\n");
6560 PrintF("==== Path to object ====\n");
6561 PrintF("=====================================\n\n");
6562
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006563 ASSERT(!object_stack_.is_empty());
6564 for (int i = 0; i < object_stack_.length(); i++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006565 if (i > 0) PrintF("\n |\n |\n V\n\n");
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006566 Object* obj = object_stack_[i];
6567#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00006568 obj->Print();
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006569#else
6570 obj->ShortPrint();
6571#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006572 }
6573 PrintF("=====================================\n");
6574 }
6575}
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006576#endif // DEBUG || LIVE_OBJECT_LIST
Steve Blocka7e24c12009-10-30 11:49:00 +00006577
6578
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006579#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00006580// Triggers a depth-first traversal of reachable objects from roots
6581// and finds a path to a specific heap object and prints it.
Leon Clarkee46be812010-01-19 14:06:41 +00006582void Heap::TracePathToObject(Object* target) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006583 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6584 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006585}
6586
6587
6588// Triggers a depth-first traversal of reachable objects from roots
6589// and finds a path to any global object and prints it. Useful for
6590// determining the source for leaks of global objects.
6591void Heap::TracePathToGlobal() {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006592 PathTracer tracer(PathTracer::kAnyGlobalObject,
6593 PathTracer::FIND_ALL,
6594 VISIT_ALL);
6595 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006596}
6597#endif
6598
6599
Ben Murdochf87a2032010-10-22 12:50:53 +01006600static intptr_t CountTotalHolesSize() {
6601 intptr_t holes_size = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +01006602 OldSpaces spaces;
6603 for (OldSpace* space = spaces.next();
6604 space != NULL;
6605 space = spaces.next()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006606 holes_size += space->Waste() + space->Available();
Leon Clarkef7060e22010-06-03 12:02:55 +01006607 }
6608 return holes_size;
6609}
6610
6611
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006612GCTracer::GCTracer(Heap* heap,
6613 const char* gc_reason,
6614 const char* collector_reason)
Steve Blocka7e24c12009-10-30 11:49:00 +00006615 : start_time_(0.0),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006616 start_object_size_(0),
6617 start_memory_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +00006618 gc_count_(0),
6619 full_gc_count_(0),
Leon Clarkef7060e22010-06-03 12:02:55 +01006620 allocated_since_last_gc_(0),
6621 spent_in_mutator_(0),
Steve Block44f0eee2011-05-26 01:26:41 +01006622 promoted_objects_size_(0),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006623 heap_(heap),
6624 gc_reason_(gc_reason),
6625 collector_reason_(collector_reason) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006626 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00006627 start_time_ = OS::TimeCurrentMillis();
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006628 start_object_size_ = heap_->SizeOfObjects();
6629 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
Leon Clarkef7060e22010-06-03 12:02:55 +01006630
6631 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6632 scopes_[i] = 0;
6633 }
6634
6635 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6636
Steve Block44f0eee2011-05-26 01:26:41 +01006637 allocated_since_last_gc_ =
6638 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
Leon Clarkef7060e22010-06-03 12:02:55 +01006639
Steve Block44f0eee2011-05-26 01:26:41 +01006640 if (heap_->last_gc_end_timestamp_ > 0) {
6641 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006642 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006643
6644 steps_count_ = heap_->incremental_marking()->steps_count();
6645 steps_took_ = heap_->incremental_marking()->steps_took();
6646 longest_step_ = heap_->incremental_marking()->longest_step();
6647 steps_count_since_last_gc_ =
6648 heap_->incremental_marking()->steps_count_since_last_gc();
6649 steps_took_since_last_gc_ =
6650 heap_->incremental_marking()->steps_took_since_last_gc();
Steve Blocka7e24c12009-10-30 11:49:00 +00006651}
6652
6653
6654GCTracer::~GCTracer() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006655 // Printf ONE line iff flag is set.
Leon Clarkef7060e22010-06-03 12:02:55 +01006656 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6657
Steve Block44f0eee2011-05-26 01:26:41 +01006658 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006659
Steve Block44f0eee2011-05-26 01:26:41 +01006660 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6661 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
Leon Clarkef7060e22010-06-03 12:02:55 +01006662
Steve Block44f0eee2011-05-26 01:26:41 +01006663 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006664
6665 // Update cumulative GC statistics if required.
6666 if (FLAG_print_cumulative_gc_stat) {
Steve Block44f0eee2011-05-26 01:26:41 +01006667 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6668 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6669 heap_->alive_after_last_gc_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006670 if (!first_gc) {
Steve Block44f0eee2011-05-26 01:26:41 +01006671 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6672 static_cast<int>(spent_in_mutator_));
Leon Clarkef7060e22010-06-03 12:02:55 +01006673 }
6674 }
6675
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006676 PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6677
Leon Clarkef7060e22010-06-03 12:02:55 +01006678 if (!FLAG_trace_gc_nvp) {
6679 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6680
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006681 double end_memory_size_mb =
6682 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6683
6684 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
Leon Clarkef7060e22010-06-03 12:02:55 +01006685 CollectorString(),
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006686 static_cast<double>(start_object_size_) / MB,
6687 static_cast<double>(start_memory_size_) / MB,
6688 SizeOfHeapObjects(),
6689 end_memory_size_mb);
Leon Clarkef7060e22010-06-03 12:02:55 +01006690
6691 if (external_time > 0) PrintF("%d / ", external_time);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006692 PrintF("%d ms", time);
6693 if (steps_count_ > 0) {
6694 if (collector_ == SCAVENGER) {
6695 PrintF(" (+ %d ms in %d steps since last GC)",
6696 static_cast<int>(steps_took_since_last_gc_),
6697 steps_count_since_last_gc_);
6698 } else {
6699 PrintF(" (+ %d ms in %d steps since start of marking, "
6700 "biggest step %f ms)",
6701 static_cast<int>(steps_took_),
6702 steps_count_,
6703 longest_step_);
6704 }
6705 }
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006706
6707 if (gc_reason_ != NULL) {
6708 PrintF(" [%s]", gc_reason_);
6709 }
6710
6711 if (collector_reason_ != NULL) {
6712 PrintF(" [%s]", collector_reason_);
6713 }
6714
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006715 PrintF(".\n");
Leon Clarkef7060e22010-06-03 12:02:55 +01006716 } else {
6717 PrintF("pause=%d ", time);
6718 PrintF("mutator=%d ",
6719 static_cast<int>(spent_in_mutator_));
6720
6721 PrintF("gc=");
6722 switch (collector_) {
6723 case SCAVENGER:
6724 PrintF("s");
6725 break;
6726 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006727 PrintF("ms");
Leon Clarkef7060e22010-06-03 12:02:55 +01006728 break;
6729 default:
6730 UNREACHABLE();
6731 }
6732 PrintF(" ");
6733
6734 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6735 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6736 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
Iain Merrick75681382010-08-19 15:07:18 +01006737 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006738 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6739 PrintF("new_new=%d ",
6740 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6741 PrintF("root_new=%d ",
6742 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6743 PrintF("old_new=%d ",
6744 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6745 PrintF("compaction_ptrs=%d ",
6746 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6747 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6748 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6749 PrintF("misc_compaction=%d ",
6750 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
Leon Clarkef7060e22010-06-03 12:02:55 +01006751
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006752 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
Steve Block44f0eee2011-05-26 01:26:41 +01006753 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
Ben Murdochf87a2032010-10-22 12:50:53 +01006754 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6755 in_free_list_or_wasted_before_gc_);
6756 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
Leon Clarkef7060e22010-06-03 12:02:55 +01006757
Ben Murdochf87a2032010-10-22 12:50:53 +01006758 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6759 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006760
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006761 if (collector_ == SCAVENGER) {
6762 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6763 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6764 } else {
6765 PrintF("stepscount=%d ", steps_count_);
6766 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6767 }
6768
Leon Clarkef7060e22010-06-03 12:02:55 +01006769 PrintF("\n");
6770 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006771
Steve Block44f0eee2011-05-26 01:26:41 +01006772 heap_->PrintShortHeapStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00006773}
6774
6775
6776const char* GCTracer::CollectorString() {
6777 switch (collector_) {
6778 case SCAVENGER:
6779 return "Scavenge";
6780 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006781 return "Mark-sweep";
Steve Blocka7e24c12009-10-30 11:49:00 +00006782 }
6783 return "Unknown GC";
6784}
6785
6786
6787int KeyedLookupCache::Hash(Map* map, String* name) {
6788 // Uses only lower 32 bits if pointers are larger.
6789 uintptr_t addr_hash =
Leon Clarkee46be812010-01-19 14:06:41 +00006790 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
Andrei Popescu402d9372010-02-26 13:31:12 +00006791 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
Steve Blocka7e24c12009-10-30 11:49:00 +00006792}
6793
6794
6795int KeyedLookupCache::Lookup(Map* map, String* name) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00006796 int index = (Hash(map, name) & kHashMask);
6797 for (int i = 0; i < kEntriesPerBucket; i++) {
6798 Key& key = keys_[index + i];
6799 if ((key.map == map) && key.name->Equals(name)) {
6800 return field_offsets_[index + i];
6801 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006802 }
Steve Block44f0eee2011-05-26 01:26:41 +01006803 return kNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00006804}
6805
6806
6807void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6808 String* symbol;
Steve Block44f0eee2011-05-26 01:26:41 +01006809 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
Ben Murdochc7cc0282012-03-05 14:35:55 +00006810 int index = (Hash(map, symbol) & kHashMask);
6811 // After a GC there will be free slots, so we use them in order (this may
6812 // help to get the most frequently used one in position 0).
6813 for (int i = 0; i< kEntriesPerBucket; i++) {
6814 Key& key = keys_[index];
6815 Object* free_entry_indicator = NULL;
6816 if (key.map == free_entry_indicator) {
6817 key.map = map;
6818 key.name = symbol;
6819 field_offsets_[index + i] = field_offset;
6820 return;
6821 }
6822 }
6823 // No free entry found in this bucket, so we move them all down one and
6824 // put the new entry at position zero.
6825 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6826 Key& key = keys_[index + i];
6827 Key& key2 = keys_[index + i - 1];
6828 key = key2;
6829 field_offsets_[index + i] = field_offsets_[index + i - 1];
6830 }
6831
6832 // Write the new first entry.
Steve Blocka7e24c12009-10-30 11:49:00 +00006833 Key& key = keys_[index];
6834 key.map = map;
6835 key.name = symbol;
6836 field_offsets_[index] = field_offset;
6837 }
6838}
6839
6840
6841void KeyedLookupCache::Clear() {
6842 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6843}
6844
6845
Steve Blocka7e24c12009-10-30 11:49:00 +00006846void DescriptorLookupCache::Clear() {
6847 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6848}
6849
6850
Steve Blocka7e24c12009-10-30 11:49:00 +00006851#ifdef DEBUG
Ben Murdochf87a2032010-10-22 12:50:53 +01006852void Heap::GarbageCollectionGreedyCheck() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006853 ASSERT(FLAG_gc_greedy);
Steve Block44f0eee2011-05-26 01:26:41 +01006854 if (isolate_->bootstrapper()->IsActive()) return;
Ben Murdochf87a2032010-10-22 12:50:53 +01006855 if (disallow_allocation_failure()) return;
6856 CollectGarbage(NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00006857}
6858#endif
6859
6860
Steve Block44f0eee2011-05-26 01:26:41 +01006861TranscendentalCache::SubCache::SubCache(Type t)
6862 : type_(t),
6863 isolate_(Isolate::Current()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006864 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6865 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6866 for (int i = 0; i < kCacheSize; i++) {
6867 elements_[i].in[0] = in0;
6868 elements_[i].in[1] = in1;
6869 elements_[i].output = NULL;
6870 }
6871}
6872
6873
Steve Blocka7e24c12009-10-30 11:49:00 +00006874void TranscendentalCache::Clear() {
6875 for (int i = 0; i < kNumberOfCaches; i++) {
6876 if (caches_[i] != NULL) {
6877 delete caches_[i];
6878 caches_[i] = NULL;
6879 }
6880 }
6881}
6882
6883
Leon Clarkee46be812010-01-19 14:06:41 +00006884void ExternalStringTable::CleanUp() {
6885 int last = 0;
6886 for (int i = 0; i < new_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006887 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6888 continue;
6889 }
Steve Block44f0eee2011-05-26 01:26:41 +01006890 if (heap_->InNewSpace(new_space_strings_[i])) {
Leon Clarkee46be812010-01-19 14:06:41 +00006891 new_space_strings_[last++] = new_space_strings_[i];
6892 } else {
6893 old_space_strings_.Add(new_space_strings_[i]);
6894 }
6895 }
6896 new_space_strings_.Rewind(last);
6897 last = 0;
6898 for (int i = 0; i < old_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006899 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6900 continue;
6901 }
Steve Block44f0eee2011-05-26 01:26:41 +01006902 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
Leon Clarkee46be812010-01-19 14:06:41 +00006903 old_space_strings_[last++] = old_space_strings_[i];
6904 }
6905 old_space_strings_.Rewind(last);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006906 if (FLAG_verify_heap) {
6907 Verify();
6908 }
Leon Clarkee46be812010-01-19 14:06:41 +00006909}
6910
6911
6912void ExternalStringTable::TearDown() {
6913 new_space_strings_.Free();
6914 old_space_strings_.Free();
6915}
6916
6917
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006918void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6919 chunk->set_next_chunk(chunks_queued_for_free_);
6920 chunks_queued_for_free_ = chunk;
6921}
6922
6923
6924void Heap::FreeQueuedChunks() {
6925 if (chunks_queued_for_free_ == NULL) return;
6926 MemoryChunk* next;
6927 MemoryChunk* chunk;
6928 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6929 next = chunk->next_chunk();
6930 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6931
6932 if (chunk->owner()->identity() == LO_SPACE) {
6933 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6934 // If FromAnyPointerAddress encounters a slot that belongs to a large
6935 // chunk queued for deletion it will fail to find the chunk because
6936 // it try to perform a search in the list of pages owned by of the large
6937 // object space and queued chunks were detached from that list.
6938 // To work around this we split large chunk into normal kPageSize aligned
6939 // pieces and initialize size, owner and flags field of every piece.
6940 // If FromAnyPointerAddress encounters a slot that belongs to one of
6941 // these smaller pieces it will treat it as a slot on a normal Page.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006942 Address chunk_end = chunk->address() + chunk->size();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006943 MemoryChunk* inner = MemoryChunk::FromAddress(
6944 chunk->address() + Page::kPageSize);
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006945 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006946 while (inner <= inner_last) {
6947 // Size of a large chunk is always a multiple of
6948 // OS::AllocateAlignment() so there is always
6949 // enough space for a fake MemoryChunk header.
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006950 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
6951 // Guard against overflow.
6952 if (area_end < inner->address()) area_end = chunk_end;
6953 inner->SetArea(inner->address(), area_end);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006954 inner->set_size(Page::kPageSize);
6955 inner->set_owner(lo_space());
6956 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6957 inner = MemoryChunk::FromAddress(
6958 inner->address() + Page::kPageSize);
6959 }
6960 }
6961 }
6962 isolate_->heap()->store_buffer()->Compact();
6963 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6964 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6965 next = chunk->next_chunk();
6966 isolate_->memory_allocator()->Free(chunk);
6967 }
6968 chunks_queued_for_free_ = NULL;
6969}
6970
Ben Murdoch5d4cdbf2012-04-11 10:23:59 +01006971
6972void Heap::RememberUnmappedPage(Address page, bool compacted) {
6973 uintptr_t p = reinterpret_cast<uintptr_t>(page);
6974 // Tag the page pointer to make it findable in the dump file.
6975 if (compacted) {
6976 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
6977 } else {
6978 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
6979 }
6980 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
6981 reinterpret_cast<Address>(p);
6982 remembered_unmapped_pages_index_++;
6983 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
6984}
6985
Steve Blocka7e24c12009-10-30 11:49:00 +00006986} } // namespace v8::internal