blob: 9bb4e40a1703947f92096cd9230d795f2b09949c [file] [log] [blame]
Ben Murdoch8b112d22011-06-08 16:22:53 +01001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
Ben Murdoch8b112d22011-06-08 16:22:53 +010033#include "codegen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000034#include "compilation-cache.h"
35#include "debug.h"
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000036#include "deoptimizer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000037#include "global-handles.h"
Ben Murdoch257744e2011-11-30 15:57:28 +000038#include "heap-profiler.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000039#include "incremental-marking.h"
Steve Block1e0659c2011-05-24 12:43:12 +010040#include "liveobjectlist-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000041#include "mark-compact.h"
42#include "natives.h"
Iain Merrick75681382010-08-19 15:07:18 +010043#include "objects-visiting.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000044#include "objects-visiting-inl.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010045#include "runtime-profiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000046#include "scopeinfo.h"
Steve Block3ce2e202009-11-05 08:53:23 +000047#include "snapshot.h"
Ben Murdoch592a9fc2012-03-05 11:04:45 +000048#include "store-buffer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000049#include "v8threads.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010050#include "vm-state-inl.h"
Steve Block6ded16b2010-05-10 14:33:55 +010051#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000052#include "regexp-macro-assembler.h"
Steve Blockd0582a62009-12-15 09:54:21 +000053#include "arm/regexp-macro-assembler-arm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000054#endif
Steve Block44f0eee2011-05-26 01:26:41 +010055#if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
56#include "regexp-macro-assembler.h"
57#include "mips/regexp-macro-assembler-mips.h"
58#endif
Steve Block6ded16b2010-05-10 14:33:55 +010059
Steve Blocka7e24c12009-10-30 11:49:00 +000060namespace v8 {
61namespace internal {
62
63
Steve Block44f0eee2011-05-26 01:26:41 +010064static Mutex* gc_initializer_mutex = OS::CreateMutex();
Steve Blocka7e24c12009-10-30 11:49:00 +000065
Steve Blocka7e24c12009-10-30 11:49:00 +000066
Steve Block44f0eee2011-05-26 01:26:41 +010067Heap::Heap()
68 : isolate_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +000069// semispace_size_ should be a power of 2 and old_generation_size_ should be
70// a multiple of Page::kPageSize.
Ben Murdoch589d6972011-11-30 16:04:58 +000071#if defined(ANDROID)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000072#define LUMP_OF_MEMORY (128 * KB)
Steve Block44f0eee2011-05-26 01:26:41 +010073 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000074#elif defined(V8_TARGET_ARCH_X64)
Ben Murdoch592a9fc2012-03-05 11:04:45 +000075#define LUMP_OF_MEMORY (2 * MB)
Steve Block44f0eee2011-05-26 01:26:41 +010076 code_range_size_(512*MB),
Steve Blocka7e24c12009-10-30 11:49:00 +000077#else
Ben Murdoch592a9fc2012-03-05 11:04:45 +000078#define LUMP_OF_MEMORY MB
Steve Block44f0eee2011-05-26 01:26:41 +010079 code_range_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +000080#endif
Ben Murdoch592a9fc2012-03-05 11:04:45 +000081 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
82 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
83 initial_semispace_size_(Max(LUMP_OF_MEMORY, Page::kPageSize)),
84 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
85 max_executable_size_(128l * LUMP_OF_MEMORY),
86
Steve Blocka7e24c12009-10-30 11:49:00 +000087// Variables set based on semispace_size_ and old_generation_size_ in
Steve Block44f0eee2011-05-26 01:26:41 +010088// ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
Steve Block3ce2e202009-11-05 08:53:23 +000089// Will be 4 * reserved_semispace_size_ to ensure that young
90// generation can be aligned to its size.
Steve Block44f0eee2011-05-26 01:26:41 +010091 survived_since_last_expansion_(0),
Ben Murdoch257744e2011-11-30 15:57:28 +000092 sweep_generation_(0),
Steve Block44f0eee2011-05-26 01:26:41 +010093 always_allocate_scope_depth_(0),
94 linear_allocation_scope_depth_(0),
95 contexts_disposed_(0),
Ben Murdoch592a9fc2012-03-05 11:04:45 +000096 scan_on_scavenge_pages_(0),
Steve Block44f0eee2011-05-26 01:26:41 +010097 new_space_(this),
98 old_pointer_space_(NULL),
99 old_data_space_(NULL),
100 code_space_(NULL),
101 map_space_(NULL),
102 cell_space_(NULL),
103 lo_space_(NULL),
104 gc_state_(NOT_IN_GC),
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000105 gc_post_processing_depth_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100106 ms_count_(0),
107 gc_count_(0),
108 unflattened_strings_length_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000109#ifdef DEBUG
Steve Block44f0eee2011-05-26 01:26:41 +0100110 allocation_allowed_(true),
111 allocation_timeout_(0),
112 disallow_allocation_failure_(false),
113 debug_utils_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +0000114#endif // DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000115 new_space_high_promotion_mode_active_(false),
Steve Block44f0eee2011-05-26 01:26:41 +0100116 old_gen_promotion_limit_(kMinimumPromotionLimit),
117 old_gen_allocation_limit_(kMinimumAllocationLimit),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000118 old_gen_limit_factor_(1),
119 size_of_old_gen_at_last_old_space_gc_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100120 external_allocation_limit_(0),
121 amount_of_external_allocated_memory_(0),
122 amount_of_external_allocated_memory_at_last_global_gc_(0),
123 old_gen_exhausted_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000124 store_buffer_rebuilder_(store_buffer()),
Steve Block44f0eee2011-05-26 01:26:41 +0100125 hidden_symbol_(NULL),
126 global_gc_prologue_callback_(NULL),
127 global_gc_epilogue_callback_(NULL),
128 gc_safe_size_of_old_object_(NULL),
Steve Block053d10c2011-06-13 19:13:29 +0100129 total_regexp_code_generated_(0),
Steve Block44f0eee2011-05-26 01:26:41 +0100130 tracer_(NULL),
131 young_survivors_after_last_gc_(0),
132 high_survival_rate_period_length_(0),
133 survival_rate_(0),
134 previous_survival_rate_trend_(Heap::STABLE),
135 survival_rate_trend_(Heap::STABLE),
136 max_gc_pause_(0),
137 max_alive_after_gc_(0),
138 min_in_mutator_(kMaxInt),
139 alive_after_last_gc_(0),
140 last_gc_end_timestamp_(0.0),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000141 store_buffer_(this),
142 marking_(this),
143 incremental_marking_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100144 number_idle_notifications_(0),
145 last_idle_notification_gc_count_(0),
146 last_idle_notification_gc_count_init_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000147 promotion_queue_(this),
Steve Block44f0eee2011-05-26 01:26:41 +0100148 configured_(false),
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000149 chunks_queued_for_free_(NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +0100150 // Allow build-time customization of the max semispace size. Building
151 // V8 with snapshots and a non-default max semispace size is much
152 // easier if you can define it as part of the build environment.
153#if defined(V8_MAX_SEMISPACE_SIZE)
154 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
155#endif
Steve Blocka7e24c12009-10-30 11:49:00 +0000156
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000157 intptr_t max_virtual = OS::MaxVirtualMemory();
158
159 if (max_virtual > 0) {
160 if (code_range_size_ > 0) {
161 // Reserve no more than 1/8 of the memory for the code range.
162 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
163 }
164 }
165
Steve Block44f0eee2011-05-26 01:26:41 +0100166 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
167 global_contexts_list_ = NULL;
168 mark_compact_collector_.heap_ = this;
169 external_string_table_.heap_ = this;
170}
171
Steve Blocka7e24c12009-10-30 11:49:00 +0000172
Ben Murdochf87a2032010-10-22 12:50:53 +0100173intptr_t Heap::Capacity() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000174 if (!HasBeenSetup()) return 0;
175
176 return new_space_.Capacity() +
177 old_pointer_space_->Capacity() +
178 old_data_space_->Capacity() +
179 code_space_->Capacity() +
180 map_space_->Capacity() +
181 cell_space_->Capacity();
182}
183
184
Ben Murdochf87a2032010-10-22 12:50:53 +0100185intptr_t Heap::CommittedMemory() {
Steve Block3ce2e202009-11-05 08:53:23 +0000186 if (!HasBeenSetup()) return 0;
187
188 return new_space_.CommittedMemory() +
189 old_pointer_space_->CommittedMemory() +
190 old_data_space_->CommittedMemory() +
191 code_space_->CommittedMemory() +
192 map_space_->CommittedMemory() +
193 cell_space_->CommittedMemory() +
194 lo_space_->Size();
195}
196
Russell Brenner90bac252010-11-18 13:33:46 -0800197intptr_t Heap::CommittedMemoryExecutable() {
198 if (!HasBeenSetup()) return 0;
199
Steve Block44f0eee2011-05-26 01:26:41 +0100200 return isolate()->memory_allocator()->SizeExecutable();
Russell Brenner90bac252010-11-18 13:33:46 -0800201}
202
Steve Block3ce2e202009-11-05 08:53:23 +0000203
Ben Murdochf87a2032010-10-22 12:50:53 +0100204intptr_t Heap::Available() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000205 if (!HasBeenSetup()) return 0;
206
207 return new_space_.Available() +
208 old_pointer_space_->Available() +
209 old_data_space_->Available() +
210 code_space_->Available() +
211 map_space_->Available() +
212 cell_space_->Available();
213}
214
215
216bool Heap::HasBeenSetup() {
217 return old_pointer_space_ != NULL &&
218 old_data_space_ != NULL &&
219 code_space_ != NULL &&
220 map_space_ != NULL &&
221 cell_space_ != NULL &&
222 lo_space_ != NULL;
223}
224
225
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100226int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000227 if (IntrusiveMarking::IsMarked(object)) {
228 return IntrusiveMarking::SizeOfMarkedObject(object);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100229 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000230 return object->SizeFromMap(object->map());
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100231}
232
233
Steve Blocka7e24c12009-10-30 11:49:00 +0000234GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
235 // Is global GC requested?
236 if (space != NEW_SPACE || FLAG_gc_global) {
Steve Block44f0eee2011-05-26 01:26:41 +0100237 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000238 return MARK_COMPACTOR;
239 }
240
241 // Is enough data promoted to justify a global GC?
242 if (OldGenerationPromotionLimitReached()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100243 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000244 return MARK_COMPACTOR;
245 }
246
247 // Have allocation in OLD and LO failed?
248 if (old_gen_exhausted_) {
Steve Block44f0eee2011-05-26 01:26:41 +0100249 isolate_->counters()->
250 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000251 return MARK_COMPACTOR;
252 }
253
254 // Is there enough space left in OLD to guarantee that a scavenge can
255 // succeed?
256 //
257 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
258 // for object promotion. It counts only the bytes that the memory
259 // allocator has not yet allocated from the OS and assigned to any space,
260 // and does not count available bytes already in the old space or code
261 // space. Undercounting is safe---we may get an unrequested full GC when
262 // a scavenge would have succeeded.
Steve Block44f0eee2011-05-26 01:26:41 +0100263 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
264 isolate_->counters()->
265 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +0000266 return MARK_COMPACTOR;
267 }
268
269 // Default
270 return SCAVENGER;
271}
272
273
274// TODO(1238405): Combine the infrastructure for --heap-stats and
275// --log-gc to avoid the complicated preprocessor and flag testing.
Steve Blocka7e24c12009-10-30 11:49:00 +0000276void Heap::ReportStatisticsBeforeGC() {
277 // Heap::ReportHeapStatistics will also log NewSpace statistics when
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000278 // compiled --log-gc is set. The following logic is used to avoid
279 // double logging.
280#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000281 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
282 if (FLAG_heap_stats) {
283 ReportHeapStatistics("Before GC");
284 } else if (FLAG_log_gc) {
285 new_space_.ReportStatistics();
286 }
287 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000288#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000289 if (FLAG_log_gc) {
290 new_space_.CollectStatistics();
291 new_space_.ReportStatistics();
292 new_space_.ClearHistograms();
293 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000294#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000295}
296
297
Steve Blocka7e24c12009-10-30 11:49:00 +0000298void Heap::PrintShortHeapStatistics() {
299 if (!FLAG_trace_gc_verbose) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100300 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
301 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block44f0eee2011-05-26 01:26:41 +0100302 isolate_->memory_allocator()->Size(),
303 isolate_->memory_allocator()->Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100304 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
305 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000306 Heap::new_space_.Size(),
307 new_space_.Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100308 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
309 ", available: %8" V8_PTR_PREFIX "d"
310 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000311 old_pointer_space_->Size(),
312 old_pointer_space_->Available(),
313 old_pointer_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100314 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
315 ", available: %8" V8_PTR_PREFIX "d"
316 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000317 old_data_space_->Size(),
318 old_data_space_->Available(),
319 old_data_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100320 PrintF("Code space, 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 code_space_->Size(),
324 code_space_->Available(),
325 code_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100326 PrintF("Map 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 map_space_->Size(),
330 map_space_->Available(),
331 map_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100332 PrintF("Cell 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 cell_space_->Size(),
336 cell_space_->Available(),
337 cell_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100338 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
339 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000340 lo_space_->Size(),
341 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000342}
Steve Blocka7e24c12009-10-30 11:49:00 +0000343
344
345// TODO(1238405): Combine the infrastructure for --heap-stats and
346// --log-gc to avoid the complicated preprocessor and flag testing.
347void Heap::ReportStatisticsAfterGC() {
348 // Similar to the before GC, we use some complicated logic to ensure that
349 // NewSpace statistics are logged exactly once when --log-gc is turned on.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000350#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000351 if (FLAG_heap_stats) {
352 new_space_.CollectStatistics();
353 ReportHeapStatistics("After GC");
354 } else if (FLAG_log_gc) {
355 new_space_.ReportStatistics();
356 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000357#else
Steve Blocka7e24c12009-10-30 11:49:00 +0000358 if (FLAG_log_gc) new_space_.ReportStatistics();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000359#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000360}
Steve Blocka7e24c12009-10-30 11:49:00 +0000361
362
363void Heap::GarbageCollectionPrologue() {
Steve Block44f0eee2011-05-26 01:26:41 +0100364 isolate_->transcendental_cache()->Clear();
Steve Block6ded16b2010-05-10 14:33:55 +0100365 ClearJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000366 gc_count_++;
Steve Block6ded16b2010-05-10 14:33:55 +0100367 unflattened_strings_length_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000368#ifdef DEBUG
369 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
370 allow_allocation(false);
371
372 if (FLAG_verify_heap) {
373 Verify();
374 }
375
376 if (FLAG_gc_verbose) Print();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000377#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000378
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000379#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000380 ReportStatisticsBeforeGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000381#endif // DEBUG
Steve Block1e0659c2011-05-24 12:43:12 +0100382
383 LiveObjectList::GCPrologue();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000384 store_buffer()->GCPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000385}
386
Ben Murdochf87a2032010-10-22 12:50:53 +0100387intptr_t Heap::SizeOfObjects() {
388 intptr_t total = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000389 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +0000390 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800391 total += space->SizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 }
393 return total;
394}
395
396void Heap::GarbageCollectionEpilogue() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000397 store_buffer()->GCEpilogue();
Steve Block1e0659c2011-05-24 12:43:12 +0100398 LiveObjectList::GCEpilogue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000399#ifdef DEBUG
400 allow_allocation(true);
401 ZapFromSpace();
402
403 if (FLAG_verify_heap) {
404 Verify();
405 }
406
Steve Block44f0eee2011-05-26 01:26:41 +0100407 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +0000408 if (FLAG_print_handles) PrintHandles();
409 if (FLAG_gc_verbose) Print();
410 if (FLAG_code_stats) ReportCodeStatistics("After GC");
411#endif
412
Steve Block44f0eee2011-05-26 01:26:41 +0100413 isolate_->counters()->alive_after_last_gc()->Set(
414 static_cast<int>(SizeOfObjects()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000415
Steve Block44f0eee2011-05-26 01:26:41 +0100416 isolate_->counters()->symbol_table_capacity()->Set(
417 symbol_table()->Capacity());
418 isolate_->counters()->number_of_symbols()->Set(
419 symbol_table()->NumberOfElements());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000420#if defined(DEBUG)
Steve Blocka7e24c12009-10-30 11:49:00 +0000421 ReportStatisticsAfterGC();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000422#endif // DEBUG
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000423#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +0100424 isolate_->debug()->AfterGarbageCollection();
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000425#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +0000426}
427
428
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000429void Heap::CollectAllGarbage(int flags) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000430 // Since we are ignoring the return value, the exact choice of space does
431 // not matter, so long as we do not specify NEW_SPACE, which would not
432 // cause a full GC.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000433 mark_compact_collector_.SetFlags(flags);
John Reck59135872010-11-02 12:39:01 -0700434 CollectGarbage(OLD_POINTER_SPACE);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000435 mark_compact_collector_.SetFlags(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000436}
437
438
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800439void Heap::CollectAllAvailableGarbage() {
440 // Since we are ignoring the return value, the exact choice of space does
441 // not matter, so long as we do not specify NEW_SPACE, which would not
442 // cause a full GC.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800443 // Major GC would invoke weak handle callbacks on weakly reachable
444 // handles, but won't collect weakly reachable objects until next
445 // major GC. Therefore if we collect aggressively and weak handle callback
446 // has been invoked, we rerun major GC to release objects which become
447 // garbage.
448 // Note: as weak callbacks can execute arbitrary code, we cannot
449 // hope that eventually there will be no weak callbacks invocations.
450 // Therefore stop recollecting after several attempts.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000451 mark_compact_collector()->SetFlags(kMakeHeapIterableMask);
452 isolate_->compilation_cache()->Clear();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800453 const int kMaxNumberOfAttempts = 7;
454 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
455 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR)) {
456 break;
457 }
458 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000459 mark_compact_collector()->SetFlags(kNoGCFlags);
460 new_space_.Shrink();
461 incremental_marking()->UncommitMarkingDeque();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800462}
463
464
465bool Heap::CollectGarbage(AllocationSpace space, GarbageCollector collector) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000466 // The VM is in the GC state until exiting this function.
Steve Block44f0eee2011-05-26 01:26:41 +0100467 VMState state(isolate_, GC);
Steve Blocka7e24c12009-10-30 11:49:00 +0000468
469#ifdef DEBUG
470 // Reset the allocation timeout to the GC interval, but make sure to
471 // allow at least a few allocations after a collection. The reason
472 // for this is that we have a lot of allocation sequences and we
473 // assume that a garbage collection will allow the subsequent
474 // allocation attempts to go through.
475 allocation_timeout_ = Max(6, FLAG_gc_interval);
476#endif
477
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000478 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
479 if (FLAG_trace_incremental_marking) {
480 PrintF("[IncrementalMarking] Scavenge during marking.\n");
481 }
482 }
483
484 if (collector == MARK_COMPACTOR &&
485 !mark_compact_collector()->PreciseSweepingRequired() &&
486 !incremental_marking()->IsStopped() &&
487 !incremental_marking()->should_hurry() &&
488 FLAG_incremental_marking_steps) {
489 if (FLAG_trace_incremental_marking) {
490 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
491 }
492 collector = SCAVENGER;
493 }
494
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800495 bool next_gc_likely_to_collect_more = false;
496
Steve Block44f0eee2011-05-26 01:26:41 +0100497 { GCTracer tracer(this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000498 GarbageCollectionPrologue();
499 // The GC count was incremented in the prologue. Tell the tracer about
500 // it.
501 tracer.set_gc_count(gc_count_);
502
Steve Blocka7e24c12009-10-30 11:49:00 +0000503 // Tell the tracer which collector we've selected.
504 tracer.set_collector(collector);
505
506 HistogramTimer* rate = (collector == SCAVENGER)
Steve Block44f0eee2011-05-26 01:26:41 +0100507 ? isolate_->counters()->gc_scavenger()
508 : isolate_->counters()->gc_compactor();
Steve Blocka7e24c12009-10-30 11:49:00 +0000509 rate->Start();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800510 next_gc_likely_to_collect_more =
511 PerformGarbageCollection(collector, &tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000512 rate->Stop();
513
514 GarbageCollectionEpilogue();
515 }
516
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000517 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
518 if (incremental_marking()->IsStopped()) {
519 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
520 incremental_marking()->Start();
521 }
522 }
523
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800524 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000525}
526
527
528void Heap::PerformScavenge() {
Steve Block44f0eee2011-05-26 01:26:41 +0100529 GCTracer tracer(this);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000530 if (incremental_marking()->IsStopped()) {
531 PerformGarbageCollection(SCAVENGER, &tracer);
532 } else {
533 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
534 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000535}
536
537
538#ifdef DEBUG
539// Helper class for verifying the symbol table.
540class SymbolTableVerifier : public ObjectVisitor {
541 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000542 void VisitPointers(Object** start, Object** end) {
543 // Visit all HeapObject pointers in [start, end).
544 for (Object** p = start; p < end; p++) {
545 if ((*p)->IsHeapObject()) {
546 // Check that the symbol is actually a symbol.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000547 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
Steve Blocka7e24c12009-10-30 11:49:00 +0000548 }
549 }
550 }
551};
552#endif // DEBUG
553
554
555static void VerifySymbolTable() {
556#ifdef DEBUG
557 SymbolTableVerifier verifier;
Steve Block44f0eee2011-05-26 01:26:41 +0100558 HEAP->symbol_table()->IterateElements(&verifier);
Steve Blocka7e24c12009-10-30 11:49:00 +0000559#endif // DEBUG
560}
561
562
Leon Clarkee46be812010-01-19 14:06:41 +0000563void Heap::ReserveSpace(
564 int new_space_size,
565 int pointer_space_size,
566 int data_space_size,
567 int code_space_size,
568 int map_space_size,
569 int cell_space_size,
570 int large_object_size) {
571 NewSpace* new_space = Heap::new_space();
572 PagedSpace* old_pointer_space = Heap::old_pointer_space();
573 PagedSpace* old_data_space = Heap::old_data_space();
574 PagedSpace* code_space = Heap::code_space();
575 PagedSpace* map_space = Heap::map_space();
576 PagedSpace* cell_space = Heap::cell_space();
577 LargeObjectSpace* lo_space = Heap::lo_space();
578 bool gc_performed = true;
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000579 int counter = 0;
580 static const int kThreshold = 20;
581 while (gc_performed && counter++ < kThreshold) {
Leon Clarkee46be812010-01-19 14:06:41 +0000582 gc_performed = false;
583 if (!new_space->ReserveSpace(new_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100584 Heap::CollectGarbage(NEW_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000585 gc_performed = true;
586 }
587 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100588 Heap::CollectGarbage(OLD_POINTER_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000589 gc_performed = true;
590 }
591 if (!(old_data_space->ReserveSpace(data_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100592 Heap::CollectGarbage(OLD_DATA_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000593 gc_performed = true;
594 }
595 if (!(code_space->ReserveSpace(code_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100596 Heap::CollectGarbage(CODE_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000597 gc_performed = true;
598 }
599 if (!(map_space->ReserveSpace(map_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100600 Heap::CollectGarbage(MAP_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000601 gc_performed = true;
602 }
603 if (!(cell_space->ReserveSpace(cell_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100604 Heap::CollectGarbage(CELL_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000605 gc_performed = true;
606 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100607 // We add a slack-factor of 2 in order to have space for a series of
608 // large-object allocations that are only just larger than the page size.
Leon Clarkee46be812010-01-19 14:06:41 +0000609 large_object_size *= 2;
610 // The ReserveSpace method on the large object space checks how much
611 // we can expand the old generation. This includes expansion caused by
612 // allocation in the other spaces.
613 large_object_size += cell_space_size + map_space_size + code_space_size +
614 data_space_size + pointer_space_size;
615 if (!(lo_space->ReserveSpace(large_object_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100616 Heap::CollectGarbage(LO_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000617 gc_performed = true;
618 }
619 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000620
621 if (gc_performed) {
622 // Failed to reserve the space after several attempts.
623 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
624 }
Leon Clarkee46be812010-01-19 14:06:41 +0000625}
626
627
Steve Blocka7e24c12009-10-30 11:49:00 +0000628void Heap::EnsureFromSpaceIsCommitted() {
629 if (new_space_.CommitFromSpaceIfNeeded()) return;
630
631 // Committing memory to from space failed.
632 // Try shrinking and try again.
633 Shrink();
634 if (new_space_.CommitFromSpaceIfNeeded()) return;
635
636 // Committing memory to from space failed again.
637 // Memory is exhausted and we will die.
638 V8::FatalProcessOutOfMemory("Committing semi space failed.");
639}
640
641
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800642void Heap::ClearJSFunctionResultCaches() {
Steve Block44f0eee2011-05-26 01:26:41 +0100643 if (isolate_->bootstrapper()->IsActive()) return;
Steve Block6ded16b2010-05-10 14:33:55 +0100644
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800645 Object* context = global_contexts_list_;
646 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000647 // Get the caches for this context. GC can happen when the context
648 // is not fully initialized, so the caches can be undefined.
649 Object* caches_or_undefined =
650 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
651 if (!caches_or_undefined->IsUndefined()) {
652 FixedArray* caches = FixedArray::cast(caches_or_undefined);
653 // Clear the caches:
654 int length = caches->length();
655 for (int i = 0; i < length; i++) {
656 JSFunctionResultCache::cast(caches->get(i))->Clear();
657 }
Steve Block6ded16b2010-05-10 14:33:55 +0100658 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800659 // Get the next context:
660 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
Steve Block6ded16b2010-05-10 14:33:55 +0100661 }
Steve Block6ded16b2010-05-10 14:33:55 +0100662}
663
664
Steve Block44f0eee2011-05-26 01:26:41 +0100665
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100666void Heap::ClearNormalizedMapCaches() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000667 if (isolate_->bootstrapper()->IsActive() &&
668 !incremental_marking()->IsMarking()) {
669 return;
670 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100671
672 Object* context = global_contexts_list_;
673 while (!context->IsUndefined()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000674 // GC can happen when the context is not fully initialized,
675 // so the cache can be undefined.
676 Object* cache =
677 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
678 if (!cache->IsUndefined()) {
679 NormalizedMapCache::cast(cache)->Clear();
680 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100681 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
682 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100683}
684
685
Steve Block8defd9f2010-07-08 12:39:36 +0100686void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
687 double survival_rate =
688 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
689 start_new_space_size;
690
691 if (survival_rate > kYoungSurvivalRateThreshold) {
692 high_survival_rate_period_length_++;
693 } else {
694 high_survival_rate_period_length_ = 0;
695 }
696
697 double survival_rate_diff = survival_rate_ - survival_rate;
698
699 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
700 set_survival_rate_trend(DECREASING);
701 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
702 set_survival_rate_trend(INCREASING);
703 } else {
704 set_survival_rate_trend(STABLE);
705 }
706
707 survival_rate_ = survival_rate;
708}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100709
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800710bool Heap::PerformGarbageCollection(GarbageCollector collector,
John Reck59135872010-11-02 12:39:01 -0700711 GCTracer* tracer) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800712 bool next_gc_likely_to_collect_more = false;
713
Ben Murdochf87a2032010-10-22 12:50:53 +0100714 if (collector != SCAVENGER) {
Steve Block44f0eee2011-05-26 01:26:41 +0100715 PROFILE(isolate_, CodeMovingGCEvent());
Ben Murdochf87a2032010-10-22 12:50:53 +0100716 }
717
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000718 if (FLAG_verify_heap) {
719 VerifySymbolTable();
720 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000721 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
722 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100723 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000724 global_gc_prologue_callback_();
725 }
Steve Block6ded16b2010-05-10 14:33:55 +0100726
727 GCType gc_type =
728 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
729
730 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
731 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
732 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
733 }
734 }
735
Steve Blocka7e24c12009-10-30 11:49:00 +0000736 EnsureFromSpaceIsCommitted();
Steve Block6ded16b2010-05-10 14:33:55 +0100737
Ben Murdochf87a2032010-10-22 12:50:53 +0100738 int start_new_space_size = Heap::new_space()->SizeAsInt();
Steve Block8defd9f2010-07-08 12:39:36 +0100739
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000740 if (IsHighSurvivalRate()) {
741 // We speed up the incremental marker if it is running so that it
742 // does not fall behind the rate of promotion, which would cause a
743 // constantly growing old space.
744 incremental_marking()->NotifyOfHighPromotionRate();
745 }
746
Steve Blocka7e24c12009-10-30 11:49:00 +0000747 if (collector == MARK_COMPACTOR) {
Steve Block6ded16b2010-05-10 14:33:55 +0100748 // Perform mark-sweep with optional compaction.
Steve Blocka7e24c12009-10-30 11:49:00 +0000749 MarkCompact(tracer);
Ben Murdoch257744e2011-11-30 15:57:28 +0000750 sweep_generation_++;
Steve Block8defd9f2010-07-08 12:39:36 +0100751 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
752 IsStableOrIncreasingSurvivalTrend();
753
754 UpdateSurvivalRateTrend(start_new_space_size);
755
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000756 if (!new_space_high_promotion_mode_active_ &&
757 new_space_.Capacity() == new_space_.MaximumCapacity() &&
758 IsStableOrIncreasingSurvivalTrend() &&
759 IsHighSurvivalRate()) {
760 // Stable high survival rates even though young generation is at
761 // maximum capacity indicates that most objects will be promoted.
762 // To decrease scavenger pauses and final mark-sweep pauses, we
763 // have to limit maximal capacity of the young generation.
764 new_space_high_promotion_mode_active_ = true;
765 if (FLAG_trace_gc) {
766 PrintF("Limited new space size due to high promotion rate: %d MB\n",
767 new_space_.InitialCapacity() / MB);
768 }
769 } else if (new_space_high_promotion_mode_active_ &&
770 IsDecreasingSurvivalTrend() &&
771 !IsHighSurvivalRate()) {
772 // Decreasing low survival rates might indicate that the above high
773 // promotion mode is over and we should allow the young generation
774 // to grow again.
775 new_space_high_promotion_mode_active_ = false;
776 if (FLAG_trace_gc) {
777 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
778 new_space_.MaximumCapacity() / MB);
779 }
780 }
781
782 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSize();
Steve Block8defd9f2010-07-08 12:39:36 +0100783
John Reck59135872010-11-02 12:39:01 -0700784 if (high_survival_rate_during_scavenges &&
785 IsStableOrIncreasingSurvivalTrend()) {
786 // Stable high survival rates of young objects both during partial and
787 // full collection indicate that mutator is either building or modifying
788 // a structure with a long lifetime.
789 // In this case we aggressively raise old generation memory limits to
790 // postpone subsequent mark-sweep collection and thus trade memory
791 // space for the mutation speed.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000792 old_gen_limit_factor_ = 2;
793 } else {
794 old_gen_limit_factor_ = 1;
Steve Block8defd9f2010-07-08 12:39:36 +0100795 }
796
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000797 old_gen_promotion_limit_ =
798 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
799 old_gen_allocation_limit_ =
800 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
801
John Reck59135872010-11-02 12:39:01 -0700802 old_gen_exhausted_ = false;
Steve Block6ded16b2010-05-10 14:33:55 +0100803 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +0100804 tracer_ = tracer;
Steve Block6ded16b2010-05-10 14:33:55 +0100805 Scavenge();
Leon Clarkef7060e22010-06-03 12:02:55 +0100806 tracer_ = NULL;
Steve Block8defd9f2010-07-08 12:39:36 +0100807
808 UpdateSurvivalRateTrend(start_new_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000809 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000810
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000811 if (new_space_high_promotion_mode_active_ &&
812 new_space_.Capacity() > new_space_.InitialCapacity()) {
813 new_space_.Shrink();
814 }
815
Steve Block44f0eee2011-05-26 01:26:41 +0100816 isolate_->counters()->objs_since_last_young()->Set(0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000817
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000818 gc_post_processing_depth_++;
Ben Murdoch257744e2011-11-30 15:57:28 +0000819 { DisableAssertNoAllocation allow_allocation;
John Reck59135872010-11-02 12:39:01 -0700820 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800821 next_gc_likely_to_collect_more =
Ben Murdoch257744e2011-11-30 15:57:28 +0000822 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
John Reck59135872010-11-02 12:39:01 -0700823 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000824 gc_post_processing_depth_--;
John Reck59135872010-11-02 12:39:01 -0700825
Steve Block3ce2e202009-11-05 08:53:23 +0000826 // Update relocatables.
827 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000828
829 if (collector == MARK_COMPACTOR) {
830 // Register the amount of external allocated memory.
831 amount_of_external_allocated_memory_at_last_global_gc_ =
832 amount_of_external_allocated_memory_;
833 }
834
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000835 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
Steve Block6ded16b2010-05-10 14:33:55 +0100836 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
837 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
838 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
839 }
840 }
841
Steve Blocka7e24c12009-10-30 11:49:00 +0000842 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
843 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100844 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000845 global_gc_epilogue_callback_();
846 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000847 if (FLAG_verify_heap) {
848 VerifySymbolTable();
849 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800850
851 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000852}
853
854
Steve Blocka7e24c12009-10-30 11:49:00 +0000855void Heap::MarkCompact(GCTracer* tracer) {
856 gc_state_ = MARK_COMPACT;
Steve Block44f0eee2011-05-26 01:26:41 +0100857 LOG(isolate_, ResourceEvent("markcompact", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000858
Steve Block44f0eee2011-05-26 01:26:41 +0100859 mark_compact_collector_.Prepare(tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000860
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000861 ms_count_++;
862 tracer->set_full_gc_count(ms_count_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000863
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000864 MarkCompactPrologue();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100865
Steve Block44f0eee2011-05-26 01:26:41 +0100866 mark_compact_collector_.CollectGarbage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000867
Steve Block44f0eee2011-05-26 01:26:41 +0100868 LOG(isolate_, ResourceEvent("markcompact", "end"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000869
870 gc_state_ = NOT_IN_GC;
871
Steve Block44f0eee2011-05-26 01:26:41 +0100872 isolate_->counters()->objs_since_last_full()->Set(0);
Steve Block6ded16b2010-05-10 14:33:55 +0100873
874 contexts_disposed_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000875}
876
877
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000878void Heap::MarkCompactPrologue() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000879 // At any old GC clear the keyed lookup cache to enable collection of unused
880 // maps.
Steve Block44f0eee2011-05-26 01:26:41 +0100881 isolate_->keyed_lookup_cache()->Clear();
882 isolate_->context_slot_cache()->Clear();
883 isolate_->descriptor_lookup_cache()->Clear();
Ben Murdoch589d6972011-11-30 16:04:58 +0000884 StringSplitCache::Clear(string_split_cache());
Steve Blocka7e24c12009-10-30 11:49:00 +0000885
Steve Block44f0eee2011-05-26 01:26:41 +0100886 isolate_->compilation_cache()->MarkCompactPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000887
Kristian Monsen25f61362010-05-21 11:50:48 +0100888 CompletelyClearInstanceofCache();
889
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000890 // TODO(1605) select heuristic for flushing NumberString cache with
891 // FlushNumberStringCache
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000892 if (FLAG_cleanup_code_caches_at_gc) {
893 polymorphic_code_cache()->set_cache(undefined_value());
894 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000895
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100896 ClearNormalizedMapCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000897}
898
899
900Object* Heap::FindCodeObject(Address a) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000901 return isolate()->inner_pointer_to_code_cache()->
902 GcSafeFindCodeForInnerPointer(a);
Steve Blocka7e24c12009-10-30 11:49:00 +0000903}
904
905
906// Helper class for copying HeapObjects
907class ScavengeVisitor: public ObjectVisitor {
908 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100909 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000910
911 void VisitPointer(Object** p) { ScavengePointer(p); }
912
913 void VisitPointers(Object** start, Object** end) {
914 // Copy all HeapObject pointers in [start, end)
915 for (Object** p = start; p < end; p++) ScavengePointer(p);
916 }
917
918 private:
919 void ScavengePointer(Object** p) {
920 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +0100921 if (!heap_->InNewSpace(object)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +0000922 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
923 reinterpret_cast<HeapObject*>(object));
924 }
Steve Block44f0eee2011-05-26 01:26:41 +0100925
926 Heap* heap_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000927};
928
929
Steve Blocka7e24c12009-10-30 11:49:00 +0000930#ifdef DEBUG
931// Visitor class to verify pointers in code or data space do not point into
932// new space.
933class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
934 public:
935 void VisitPointers(Object** start, Object**end) {
936 for (Object** current = start; current < end; current++) {
937 if ((*current)->IsHeapObject()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100938 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000939 }
940 }
941 }
942};
943
944
945static void VerifyNonPointerSpacePointers() {
946 // Verify that there are no pointers to new space in spaces where we
947 // do not expect them.
948 VerifyNonPointerSpacePointersVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +0100949 HeapObjectIterator code_it(HEAP->code_space());
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000950 for (HeapObject* object = code_it.Next();
951 object != NULL; object = code_it.Next())
Steve Blocka7e24c12009-10-30 11:49:00 +0000952 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000953
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000954 // The old data space was normally swept conservatively so that the iterator
955 // doesn't work, so we normally skip the next bit.
956 if (!HEAP->old_data_space()->was_swept_conservatively()) {
957 HeapObjectIterator data_it(HEAP->old_data_space());
958 for (HeapObject* object = data_it.Next();
959 object != NULL; object = data_it.Next())
960 object->Iterate(&v);
961 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000962}
963#endif
964
965
Steve Block6ded16b2010-05-10 14:33:55 +0100966void Heap::CheckNewSpaceExpansionCriteria() {
967 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000968 survived_since_last_expansion_ > new_space_.Capacity() &&
969 !new_space_high_promotion_mode_active_) {
970 // Grow the size of new space if there is room to grow, enough data
971 // has survived scavenge since the last expansion and we are not in
972 // high promotion mode.
Steve Block6ded16b2010-05-10 14:33:55 +0100973 new_space_.Grow();
974 survived_since_last_expansion_ = 0;
975 }
976}
977
978
Ben Murdoch257744e2011-11-30 15:57:28 +0000979static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
980 return heap->InNewSpace(*p) &&
981 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
982}
983
984
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000985void Heap::ScavengeStoreBufferCallback(
986 Heap* heap,
987 MemoryChunk* page,
988 StoreBufferEvent event) {
989 heap->store_buffer_rebuilder_.Callback(page, event);
990}
991
992
993void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
994 if (event == kStoreBufferStartScanningPagesEvent) {
995 start_of_current_page_ = NULL;
996 current_page_ = NULL;
997 } else if (event == kStoreBufferScanningPageEvent) {
998 if (current_page_ != NULL) {
999 // If this page already overflowed the store buffer during this iteration.
1000 if (current_page_->scan_on_scavenge()) {
1001 // Then we should wipe out the entries that have been added for it.
1002 store_buffer_->SetTop(start_of_current_page_);
1003 } else if (store_buffer_->Top() - start_of_current_page_ >=
1004 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1005 // Did we find too many pointers in the previous page? The heuristic is
1006 // that no page can take more then 1/5 the remaining slots in the store
1007 // buffer.
1008 current_page_->set_scan_on_scavenge(true);
1009 store_buffer_->SetTop(start_of_current_page_);
1010 } else {
1011 // In this case the page we scanned took a reasonable number of slots in
1012 // the store buffer. It has now been rehabilitated and is no longer
1013 // marked scan_on_scavenge.
1014 ASSERT(!current_page_->scan_on_scavenge());
1015 }
1016 }
1017 start_of_current_page_ = store_buffer_->Top();
1018 current_page_ = page;
1019 } else if (event == kStoreBufferFullEvent) {
1020 // The current page overflowed the store buffer again. Wipe out its entries
1021 // in the store buffer and mark it scan-on-scavenge again. This may happen
1022 // several times while scanning.
1023 if (current_page_ == NULL) {
1024 // Store Buffer overflowed while scanning promoted objects. These are not
1025 // in any particular page, though they are likely to be clustered by the
1026 // allocation routines.
1027 store_buffer_->HandleFullness();
1028 } else {
1029 // Store Buffer overflowed while scanning a particular old space page for
1030 // pointers to new space.
1031 ASSERT(current_page_ == page);
1032 ASSERT(page != NULL);
1033 current_page_->set_scan_on_scavenge(true);
1034 ASSERT(start_of_current_page_ != store_buffer_->Top());
1035 store_buffer_->SetTop(start_of_current_page_);
1036 }
1037 } else {
1038 UNREACHABLE();
1039 }
1040}
1041
1042
1043void PromotionQueue::Initialize() {
1044 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1045 // entries (where each is a pair of intptr_t). This allows us to simplify
1046 // the test fpr when to switch pages.
1047 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1048 == 0);
1049 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1050 front_ = rear_ =
1051 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1052 emergency_stack_ = NULL;
1053 guard_ = false;
1054}
1055
1056
1057void PromotionQueue::RelocateQueueHead() {
1058 ASSERT(emergency_stack_ == NULL);
1059
1060 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1061 intptr_t* head_start = rear_;
1062 intptr_t* head_end =
1063 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1064
1065 int entries_count =
1066 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1067
1068 emergency_stack_ = new List<Entry>(2 * entries_count);
1069
1070 while (head_start != head_end) {
1071 int size = static_cast<int>(*(head_start++));
1072 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1073 emergency_stack_->Add(Entry(obj, size));
1074 }
1075 rear_ = head_end;
1076}
1077
1078
Steve Blocka7e24c12009-10-30 11:49:00 +00001079void Heap::Scavenge() {
1080#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001081 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
Steve Blocka7e24c12009-10-30 11:49:00 +00001082#endif
1083
1084 gc_state_ = SCAVENGE;
1085
1086 // Implements Cheney's copying algorithm
Steve Block44f0eee2011-05-26 01:26:41 +01001087 LOG(isolate_, ResourceEvent("scavenge", "begin"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001088
1089 // Clear descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01001090 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00001091
1092 // Used for updating survived_since_last_expansion_ at function end.
Ben Murdochf87a2032010-10-22 12:50:53 +01001093 intptr_t survived_watermark = PromotedSpaceSize();
Steve Blocka7e24c12009-10-30 11:49:00 +00001094
Steve Block6ded16b2010-05-10 14:33:55 +01001095 CheckNewSpaceExpansionCriteria();
Steve Blocka7e24c12009-10-30 11:49:00 +00001096
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001097 SelectScavengingVisitorsTable();
1098
1099 incremental_marking()->PrepareForScavenge();
1100
1101 old_pointer_space()->AdvanceSweeper(new_space_.Size());
1102 old_data_space()->AdvanceSweeper(new_space_.Size());
1103
Steve Blocka7e24c12009-10-30 11:49:00 +00001104 // Flip the semispaces. After flipping, to space is empty, from space has
1105 // live objects.
1106 new_space_.Flip();
1107 new_space_.ResetAllocationInfo();
1108
1109 // We need to sweep newly copied objects which can be either in the
1110 // to space or promoted to the old generation. For to-space
1111 // objects, we treat the bottom of the to space as a queue. Newly
1112 // copied and unswept objects lie between a 'front' mark and the
1113 // allocation pointer.
1114 //
1115 // Promoted objects can go into various old-generation spaces, and
1116 // can be allocated internally in the spaces (from the free list).
1117 // We treat the top of the to space as a queue of addresses of
1118 // promoted objects. The addresses of newly promoted and unswept
1119 // objects lie between a 'front' mark and a 'rear' mark that is
1120 // updated as a side effect of promoting an object.
1121 //
1122 // There is guaranteed to be enough room at the top of the to space
1123 // for the addresses of promoted objects: every object promoted
1124 // frees up its size in bytes from the top of the new space, and
1125 // objects are at least one pointer in size.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001126 Address new_space_front = new_space_.ToSpaceStart();
1127 promotion_queue_.Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +00001128
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001129#ifdef DEBUG
1130 store_buffer()->Clean();
1131#endif
1132
Steve Block44f0eee2011-05-26 01:26:41 +01001133 ScavengeVisitor scavenge_visitor(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00001134 // Copy roots.
Leon Clarkee46be812010-01-19 14:06:41 +00001135 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001136
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001137 // Copy objects reachable from the old generation.
1138 {
1139 StoreBufferRebuildScope scope(this,
1140 store_buffer(),
1141 &ScavengeStoreBufferCallback);
1142 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1143 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001144
1145 // Copy objects reachable from cells by scavenging cell values directly.
1146 HeapObjectIterator cell_iterator(cell_space_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001147 for (HeapObject* cell = cell_iterator.Next();
1148 cell != NULL; cell = cell_iterator.Next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001149 if (cell->IsJSGlobalPropertyCell()) {
1150 Address value_address =
1151 reinterpret_cast<Address>(cell) +
1152 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1153 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1154 }
1155 }
1156
Ben Murdochf87a2032010-10-22 12:50:53 +01001157 // Scavenge object reachable from the global contexts list directly.
1158 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1159
Leon Clarkee46be812010-01-19 14:06:41 +00001160 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001161 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
Ben Murdoch257744e2011-11-30 15:57:28 +00001162 &IsUnscavengedHeapObject);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001163 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1164 &scavenge_visitor);
Ben Murdoch257744e2011-11-30 15:57:28 +00001165 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1166
Steve Block6ded16b2010-05-10 14:33:55 +01001167 UpdateNewSpaceReferencesInExternalStringTable(
1168 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1169
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001170 promotion_queue_.Destroy();
1171
Steve Block1e0659c2011-05-24 12:43:12 +01001172 LiveObjectList::UpdateReferencesForScavengeGC();
Steve Block44f0eee2011-05-26 01:26:41 +01001173 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001174 incremental_marking()->UpdateMarkingDequeAfterScavenge();
Steve Block1e0659c2011-05-24 12:43:12 +01001175
Leon Clarkee46be812010-01-19 14:06:41 +00001176 ASSERT(new_space_front == new_space_.top());
1177
1178 // Set age mark.
1179 new_space_.set_age_mark(new_space_.top());
1180
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001181 new_space_.LowerInlineAllocationLimit(
1182 new_space_.inline_allocation_limit_step());
1183
Leon Clarkee46be812010-01-19 14:06:41 +00001184 // Update how much has survived scavenge.
Ben Murdochf87a2032010-10-22 12:50:53 +01001185 IncrementYoungSurvivorsCounter(static_cast<int>(
1186 (PromotedSpaceSize() - survived_watermark) + new_space_.Size()));
Leon Clarkee46be812010-01-19 14:06:41 +00001187
Steve Block44f0eee2011-05-26 01:26:41 +01001188 LOG(isolate_, ResourceEvent("scavenge", "end"));
Leon Clarkee46be812010-01-19 14:06:41 +00001189
1190 gc_state_ = NOT_IN_GC;
1191}
1192
1193
Steve Block44f0eee2011-05-26 01:26:41 +01001194String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1195 Object** p) {
Steve Block6ded16b2010-05-10 14:33:55 +01001196 MapWord first_word = HeapObject::cast(*p)->map_word();
1197
1198 if (!first_word.IsForwardingAddress()) {
1199 // Unreachable external string can be finalized.
Steve Block44f0eee2011-05-26 01:26:41 +01001200 heap->FinalizeExternalString(String::cast(*p));
Steve Block6ded16b2010-05-10 14:33:55 +01001201 return NULL;
1202 }
1203
1204 // String is still reachable.
1205 return String::cast(first_word.ToForwardingAddress());
1206}
1207
1208
1209void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1210 ExternalStringTableUpdaterCallback updater_func) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001211 if (FLAG_verify_heap) {
1212 external_string_table_.Verify();
1213 }
Leon Clarkee46be812010-01-19 14:06:41 +00001214
Steve Block44f0eee2011-05-26 01:26:41 +01001215 if (external_string_table_.new_space_strings_.is_empty()) return;
Leon Clarkee46be812010-01-19 14:06:41 +00001216
Steve Block44f0eee2011-05-26 01:26:41 +01001217 Object** start = &external_string_table_.new_space_strings_[0];
1218 Object** end = start + external_string_table_.new_space_strings_.length();
Leon Clarkee46be812010-01-19 14:06:41 +00001219 Object** last = start;
1220
1221 for (Object** p = start; p < end; ++p) {
Steve Block44f0eee2011-05-26 01:26:41 +01001222 ASSERT(InFromSpace(*p));
1223 String* target = updater_func(this, p);
Leon Clarkee46be812010-01-19 14:06:41 +00001224
Steve Block6ded16b2010-05-10 14:33:55 +01001225 if (target == NULL) continue;
Leon Clarkee46be812010-01-19 14:06:41 +00001226
Leon Clarkee46be812010-01-19 14:06:41 +00001227 ASSERT(target->IsExternalString());
1228
Steve Block44f0eee2011-05-26 01:26:41 +01001229 if (InNewSpace(target)) {
Leon Clarkee46be812010-01-19 14:06:41 +00001230 // String is still in new space. Update the table entry.
1231 *last = target;
1232 ++last;
1233 } else {
1234 // String got promoted. Move it to the old string list.
Steve Block44f0eee2011-05-26 01:26:41 +01001235 external_string_table_.AddOldString(target);
Leon Clarkee46be812010-01-19 14:06:41 +00001236 }
1237 }
1238
1239 ASSERT(last <= end);
Steve Block44f0eee2011-05-26 01:26:41 +01001240 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
Leon Clarkee46be812010-01-19 14:06:41 +00001241}
1242
1243
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001244void Heap::UpdateReferencesInExternalStringTable(
1245 ExternalStringTableUpdaterCallback updater_func) {
1246
1247 // Update old space string references.
1248 if (external_string_table_.old_space_strings_.length() > 0) {
1249 Object** start = &external_string_table_.old_space_strings_[0];
1250 Object** end = start + external_string_table_.old_space_strings_.length();
1251 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1252 }
1253
1254 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1255}
1256
1257
Steve Block44f0eee2011-05-26 01:26:41 +01001258static Object* ProcessFunctionWeakReferences(Heap* heap,
1259 Object* function,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001260 WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001261 Object* undefined = heap->undefined_value();
1262 Object* head = undefined;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001263 JSFunction* tail = NULL;
1264 Object* candidate = function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001265 while (candidate != undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001266 // Check whether to keep the candidate in the list.
1267 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1268 Object* retain = retainer->RetainAs(candidate);
1269 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001270 if (head == undefined) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01001271 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001272 head = retain;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001273 } else {
1274 // Subsequent elements in the list.
1275 ASSERT(tail != NULL);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001276 tail->set_next_function_link(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001277 }
1278 // Retained function is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001279 candidate_function = reinterpret_cast<JSFunction*>(retain);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001280 tail = candidate_function;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001281
1282 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1283
1284 if (retain == undefined) break;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001285 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001286
Ben Murdochb0fe1622011-05-05 13:52:32 +01001287 // Move to next element in the list.
1288 candidate = candidate_function->next_function_link();
1289 }
1290
1291 // Terminate the list if there is one or more elements.
1292 if (tail != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001293 tail->set_next_function_link(undefined);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001294 }
1295
1296 return head;
1297}
1298
1299
Ben Murdochf87a2032010-10-22 12:50:53 +01001300void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001301 Object* undefined = undefined_value();
1302 Object* head = undefined;
Ben Murdochf87a2032010-10-22 12:50:53 +01001303 Context* tail = NULL;
1304 Object* candidate = global_contexts_list_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001305 while (candidate != undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001306 // Check whether to keep the candidate in the list.
1307 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1308 Object* retain = retainer->RetainAs(candidate);
1309 if (retain != NULL) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001310 if (head == undefined) {
Ben Murdochf87a2032010-10-22 12:50:53 +01001311 // First element in the list.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001312 head = retain;
Ben Murdochf87a2032010-10-22 12:50:53 +01001313 } else {
1314 // Subsequent elements in the list.
1315 ASSERT(tail != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01001316 tail->set_unchecked(this,
1317 Context::NEXT_CONTEXT_LINK,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001318 retain,
Ben Murdochf87a2032010-10-22 12:50:53 +01001319 UPDATE_WRITE_BARRIER);
1320 }
1321 // Retained context is new tail.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001322 candidate_context = reinterpret_cast<Context*>(retain);
Ben Murdochf87a2032010-10-22 12:50:53 +01001323 tail = candidate_context;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001324
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001325 if (retain == undefined) break;
1326
Ben Murdochb0fe1622011-05-05 13:52:32 +01001327 // Process the weak list of optimized functions for the context.
1328 Object* function_list_head =
1329 ProcessFunctionWeakReferences(
Steve Block44f0eee2011-05-26 01:26:41 +01001330 this,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001331 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1332 retainer);
Steve Block44f0eee2011-05-26 01:26:41 +01001333 candidate_context->set_unchecked(this,
1334 Context::OPTIMIZED_FUNCTIONS_LIST,
Ben Murdochb0fe1622011-05-05 13:52:32 +01001335 function_list_head,
1336 UPDATE_WRITE_BARRIER);
Ben Murdochf87a2032010-10-22 12:50:53 +01001337 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001338
Ben Murdochf87a2032010-10-22 12:50:53 +01001339 // Move to next element in the list.
1340 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1341 }
1342
1343 // Terminate the list if there is one or more elements.
1344 if (tail != NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01001345 tail->set_unchecked(this,
1346 Context::NEXT_CONTEXT_LINK,
Ben Murdochf87a2032010-10-22 12:50:53 +01001347 Heap::undefined_value(),
1348 UPDATE_WRITE_BARRIER);
1349 }
1350
1351 // Update the head of the list of contexts.
Steve Block44f0eee2011-05-26 01:26:41 +01001352 global_contexts_list_ = head;
Ben Murdochf87a2032010-10-22 12:50:53 +01001353}
1354
1355
Iain Merrick75681382010-08-19 15:07:18 +01001356class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1357 public:
Steve Block44f0eee2011-05-26 01:26:41 +01001358 static inline void VisitPointer(Heap* heap, Object** p) {
Iain Merrick75681382010-08-19 15:07:18 +01001359 Object* object = *p;
Steve Block44f0eee2011-05-26 01:26:41 +01001360 if (!heap->InNewSpace(object)) return;
Iain Merrick75681382010-08-19 15:07:18 +01001361 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1362 reinterpret_cast<HeapObject*>(object));
1363 }
1364};
1365
1366
Leon Clarkee46be812010-01-19 14:06:41 +00001367Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1368 Address new_space_front) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001369 do {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001370 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001371 // The addresses new_space_front and new_space_.top() define a
1372 // queue of unprocessed copied objects. Process them until the
1373 // queue is empty.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001374 while (new_space_front != new_space_.top()) {
1375 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1376 HeapObject* object = HeapObject::FromAddress(new_space_front);
1377 new_space_front +=
1378 NewSpaceScavenger::IterateBody(object->map(), object);
1379 } else {
1380 new_space_front =
1381 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1382 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001383 }
1384
1385 // Promote and process all the to-be-promoted objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001386 {
1387 StoreBufferRebuildScope scope(this,
1388 store_buffer(),
1389 &ScavengeStoreBufferCallback);
1390 while (!promotion_queue()->is_empty()) {
1391 HeapObject* target;
1392 int size;
1393 promotion_queue()->remove(&target, &size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001394
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001395 // Promoted object might be already partially visited
1396 // during old space pointer iteration. Thus we search specificly
1397 // for pointers to from semispace instead of looking for pointers
1398 // to new space.
1399 ASSERT(!target->IsMap());
1400 IterateAndMarkPointersToFromSpace(target->address(),
1401 target->address() + size,
1402 &ScavengeObject);
1403 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001404 }
1405
1406 // Take another spin if there are now unswept objects in new space
1407 // (there are currently no more unswept promoted objects).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001408 } while (new_space_front != new_space_.top());
Steve Blocka7e24c12009-10-30 11:49:00 +00001409
Leon Clarkee46be812010-01-19 14:06:41 +00001410 return new_space_front;
Steve Blocka7e24c12009-10-30 11:49:00 +00001411}
1412
1413
Ben Murdoch8b112d22011-06-08 16:22:53 +01001414enum LoggingAndProfiling {
1415 LOGGING_AND_PROFILING_ENABLED,
1416 LOGGING_AND_PROFILING_DISABLED
1417};
1418
1419
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001420enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
Ben Murdoch8b112d22011-06-08 16:22:53 +01001421
1422
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001423template<MarksHandling marks_handling,
1424 LoggingAndProfiling logging_and_profiling_mode>
Iain Merrick75681382010-08-19 15:07:18 +01001425class ScavengingVisitor : public StaticVisitorBase {
1426 public:
1427 static void Initialize() {
1428 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1429 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1430 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1431 table_.Register(kVisitByteArray, &EvacuateByteArray);
1432 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001433 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001434
Ben Murdochf87a2032010-10-22 12:50:53 +01001435 table_.Register(kVisitGlobalContext,
1436 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001437 template VisitSpecialized<Context::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001438
1439 table_.Register(kVisitConsString,
1440 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001441 template VisitSpecialized<ConsString::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001442
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001443 table_.Register(kVisitSlicedString,
1444 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1445 template VisitSpecialized<SlicedString::kSize>);
1446
Iain Merrick75681382010-08-19 15:07:18 +01001447 table_.Register(kVisitSharedFunctionInfo,
1448 &ObjectEvacuationStrategy<POINTER_OBJECT>::
Ben Murdoch8b112d22011-06-08 16:22:53 +01001449 template VisitSpecialized<SharedFunctionInfo::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001450
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001451 table_.Register(kVisitJSWeakMap,
1452 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1453 Visit);
1454
Ben Murdoch257744e2011-11-30 15:57:28 +00001455 table_.Register(kVisitJSRegExp,
1456 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1457 Visit);
1458
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001459 if (marks_handling == IGNORE_MARKS) {
1460 table_.Register(kVisitJSFunction,
1461 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1462 template VisitSpecialized<JSFunction::kSize>);
1463 } else {
1464 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1465 }
Iain Merrick75681382010-08-19 15:07:18 +01001466
1467 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1468 kVisitDataObject,
1469 kVisitDataObjectGeneric>();
1470
1471 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1472 kVisitJSObject,
1473 kVisitJSObjectGeneric>();
1474
1475 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1476 kVisitStruct,
1477 kVisitStructGeneric>();
1478 }
1479
Ben Murdoch8b112d22011-06-08 16:22:53 +01001480 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1481 return &table_;
Iain Merrick75681382010-08-19 15:07:18 +01001482 }
1483
Iain Merrick75681382010-08-19 15:07:18 +01001484 private:
1485 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1486 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1487
Steve Block44f0eee2011-05-26 01:26:41 +01001488 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
Iain Merrick75681382010-08-19 15:07:18 +01001489 bool should_record = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001490#ifdef DEBUG
Iain Merrick75681382010-08-19 15:07:18 +01001491 should_record = FLAG_heap_stats;
Steve Blocka7e24c12009-10-30 11:49:00 +00001492#endif
Iain Merrick75681382010-08-19 15:07:18 +01001493 should_record = should_record || FLAG_log_gc;
Iain Merrick75681382010-08-19 15:07:18 +01001494 if (should_record) {
Steve Block44f0eee2011-05-26 01:26:41 +01001495 if (heap->new_space()->Contains(obj)) {
1496 heap->new_space()->RecordAllocation(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001497 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001498 heap->new_space()->RecordPromotion(obj);
Iain Merrick75681382010-08-19 15:07:18 +01001499 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001500 }
1501 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001502
Iain Merrick75681382010-08-19 15:07:18 +01001503 // Helper function used by CopyObject to copy a source object to an
1504 // allocated target object and update the forwarding pointer in the source
1505 // object. Returns the target object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001506 INLINE(static void MigrateObject(Heap* heap,
1507 HeapObject* source,
1508 HeapObject* target,
1509 int size)) {
Iain Merrick75681382010-08-19 15:07:18 +01001510 // Copy the content of source to target.
Steve Block44f0eee2011-05-26 01:26:41 +01001511 heap->CopyBlock(target->address(), source->address(), size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001512
Iain Merrick75681382010-08-19 15:07:18 +01001513 // Set the forwarding address.
1514 source->set_map_word(MapWord::FromForwardingAddress(target));
Steve Blocka7e24c12009-10-30 11:49:00 +00001515
Ben Murdoch8b112d22011-06-08 16:22:53 +01001516 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001517 // Update NewSpace stats if necessary.
1518 RecordCopiedObject(heap, target);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001519 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
Ben Murdoch8b112d22011-06-08 16:22:53 +01001520 Isolate* isolate = heap->isolate();
1521 if (isolate->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001522 CpuProfiler::is_profiling(isolate)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001523 if (target->IsSharedFunctionInfo()) {
1524 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1525 source->address(), target->address()));
1526 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001527 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001528 }
1529
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001530 if (marks_handling == TRANSFER_MARKS) {
1531 if (Marking::TransferColor(source, target)) {
1532 MemoryChunk::IncrementLiveBytes(target->address(), size);
1533 }
1534 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001535 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001536
Iain Merrick75681382010-08-19 15:07:18 +01001537 template<ObjectContents object_contents, SizeRestriction size_restriction>
1538 static inline void EvacuateObject(Map* map,
1539 HeapObject** slot,
1540 HeapObject* object,
1541 int object_size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001542 SLOW_ASSERT((size_restriction != SMALL) ||
1543 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1544 SLOW_ASSERT(object->Size() == object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001545
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001546 Heap* heap = map->GetHeap();
Steve Block44f0eee2011-05-26 01:26:41 +01001547 if (heap->ShouldBePromoted(object->address(), object_size)) {
John Reck59135872010-11-02 12:39:01 -07001548 MaybeObject* maybe_result;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001549
Iain Merrick75681382010-08-19 15:07:18 +01001550 if ((size_restriction != SMALL) &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001551 (object_size > Page::kMaxNonCodeHeapObjectSize)) {
1552 maybe_result = heap->lo_space()->AllocateRaw(object_size,
1553 NOT_EXECUTABLE);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001554 } else {
Iain Merrick75681382010-08-19 15:07:18 +01001555 if (object_contents == DATA_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001556 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001557 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001558 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001559 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001560 }
1561
John Reck59135872010-11-02 12:39:01 -07001562 Object* result = NULL; // Initialization to please compiler.
1563 if (maybe_result->ToObject(&result)) {
Iain Merrick75681382010-08-19 15:07:18 +01001564 HeapObject* target = HeapObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001565
1566 // Order is important: slot might be inside of the target if target
1567 // was allocated over a dead object and slot comes from the store
1568 // buffer.
1569 *slot = target;
1570 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001571
Iain Merrick75681382010-08-19 15:07:18 +01001572 if (object_contents == POINTER_OBJECT) {
Steve Block44f0eee2011-05-26 01:26:41 +01001573 heap->promotion_queue()->insert(target, object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001574 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001575
Steve Block44f0eee2011-05-26 01:26:41 +01001576 heap->tracer()->increment_promoted_objects_size(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001577 return;
1578 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001579 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001580 MaybeObject* allocation = heap->new_space()->AllocateRaw(object_size);
1581 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1582 Object* result = allocation->ToObjectUnchecked();
1583 HeapObject* target = HeapObject::cast(result);
1584
1585 // Order is important: slot might be inside of the target if target
1586 // was allocated over a dead object and slot comes from the store
1587 // buffer.
1588 *slot = target;
1589 MigrateObject(heap, object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001590 return;
1591 }
1592
Iain Merrick75681382010-08-19 15:07:18 +01001593
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001594 static inline void EvacuateJSFunction(Map* map,
1595 HeapObject** slot,
1596 HeapObject* object) {
1597 ObjectEvacuationStrategy<POINTER_OBJECT>::
1598 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1599
1600 HeapObject* target = *slot;
1601 MarkBit mark_bit = Marking::MarkBitFrom(target);
1602 if (Marking::IsBlack(mark_bit)) {
1603 // This object is black and it might not be rescanned by marker.
1604 // We should explicitly record code entry slot for compaction because
1605 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1606 // miss it as it is not HeapObject-tagged.
1607 Address code_entry_slot =
1608 target->address() + JSFunction::kCodeEntryOffset;
1609 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1610 map->GetHeap()->mark_compact_collector()->
1611 RecordCodeEntrySlot(code_entry_slot, code);
1612 }
1613 }
1614
1615
Iain Merrick75681382010-08-19 15:07:18 +01001616 static inline void EvacuateFixedArray(Map* map,
1617 HeapObject** slot,
1618 HeapObject* object) {
1619 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1620 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1621 slot,
1622 object,
1623 object_size);
1624 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001625
1626
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001627 static inline void EvacuateFixedDoubleArray(Map* map,
1628 HeapObject** slot,
1629 HeapObject* object) {
1630 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1631 int object_size = FixedDoubleArray::SizeFor(length);
1632 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1633 slot,
1634 object,
1635 object_size);
1636 }
1637
1638
Iain Merrick75681382010-08-19 15:07:18 +01001639 static inline void EvacuateByteArray(Map* map,
1640 HeapObject** slot,
1641 HeapObject* object) {
1642 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1643 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1644 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001645
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001646
Iain Merrick75681382010-08-19 15:07:18 +01001647 static inline void EvacuateSeqAsciiString(Map* map,
1648 HeapObject** slot,
1649 HeapObject* object) {
1650 int object_size = SeqAsciiString::cast(object)->
1651 SeqAsciiStringSize(map->instance_type());
1652 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1653 }
1654
1655
1656 static inline void EvacuateSeqTwoByteString(Map* map,
1657 HeapObject** slot,
1658 HeapObject* object) {
1659 int object_size = SeqTwoByteString::cast(object)->
1660 SeqTwoByteStringSize(map->instance_type());
1661 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1662 }
1663
1664
1665 static inline bool IsShortcutCandidate(int type) {
1666 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1667 }
1668
1669 static inline void EvacuateShortcutCandidate(Map* map,
1670 HeapObject** slot,
1671 HeapObject* object) {
1672 ASSERT(IsShortcutCandidate(map->instance_type()));
1673
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001674 Heap* heap = map->GetHeap();
1675
1676 if (marks_handling == IGNORE_MARKS &&
1677 ConsString::cast(object)->unchecked_second() ==
1678 heap->empty_string()) {
Iain Merrick75681382010-08-19 15:07:18 +01001679 HeapObject* first =
1680 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1681
1682 *slot = first;
1683
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001684 if (!heap->InNewSpace(first)) {
Iain Merrick75681382010-08-19 15:07:18 +01001685 object->set_map_word(MapWord::FromForwardingAddress(first));
1686 return;
1687 }
1688
1689 MapWord first_word = first->map_word();
1690 if (first_word.IsForwardingAddress()) {
1691 HeapObject* target = first_word.ToForwardingAddress();
1692
1693 *slot = target;
1694 object->set_map_word(MapWord::FromForwardingAddress(target));
1695 return;
1696 }
1697
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001698 heap->DoScavengeObject(first->map(), slot, first);
Iain Merrick75681382010-08-19 15:07:18 +01001699 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1700 return;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001701 }
Iain Merrick75681382010-08-19 15:07:18 +01001702
1703 int object_size = ConsString::kSize;
1704 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001705 }
1706
Iain Merrick75681382010-08-19 15:07:18 +01001707 template<ObjectContents object_contents>
1708 class ObjectEvacuationStrategy {
1709 public:
1710 template<int object_size>
1711 static inline void VisitSpecialized(Map* map,
1712 HeapObject** slot,
1713 HeapObject* object) {
1714 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1715 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001716
Iain Merrick75681382010-08-19 15:07:18 +01001717 static inline void Visit(Map* map,
1718 HeapObject** slot,
1719 HeapObject* object) {
1720 int object_size = map->instance_size();
1721 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1722 }
1723 };
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001724
Ben Murdoch8b112d22011-06-08 16:22:53 +01001725 static VisitorDispatchTable<ScavengingCallback> table_;
Iain Merrick75681382010-08-19 15:07:18 +01001726};
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001727
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001728
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001729template<MarksHandling marks_handling,
1730 LoggingAndProfiling logging_and_profiling_mode>
Ben Murdoch8b112d22011-06-08 16:22:53 +01001731VisitorDispatchTable<ScavengingCallback>
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001732 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001733
1734
1735static void InitializeScavengingVisitorsTables() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001736 ScavengingVisitor<TRANSFER_MARKS,
1737 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1738 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1739 ScavengingVisitor<TRANSFER_MARKS,
1740 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1741 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
Ben Murdoch8b112d22011-06-08 16:22:53 +01001742}
1743
1744
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001745void Heap::SelectScavengingVisitorsTable() {
1746 bool logging_and_profiling =
1747 isolate()->logger()->is_logging() ||
Ben Murdoch257744e2011-11-30 15:57:28 +00001748 CpuProfiler::is_profiling(isolate()) ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01001749 (isolate()->heap_profiler() != NULL &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001750 isolate()->heap_profiler()->is_profiling());
Ben Murdoch8b112d22011-06-08 16:22:53 +01001751
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001752 if (!incremental_marking()->IsMarking()) {
1753 if (!logging_and_profiling) {
1754 scavenging_visitors_table_.CopyFrom(
1755 ScavengingVisitor<IGNORE_MARKS,
1756 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1757 } else {
1758 scavenging_visitors_table_.CopyFrom(
1759 ScavengingVisitor<IGNORE_MARKS,
1760 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1761 }
1762 } else {
1763 if (!logging_and_profiling) {
1764 scavenging_visitors_table_.CopyFrom(
1765 ScavengingVisitor<TRANSFER_MARKS,
1766 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1767 } else {
1768 scavenging_visitors_table_.CopyFrom(
1769 ScavengingVisitor<TRANSFER_MARKS,
1770 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1771 }
1772
1773 if (incremental_marking()->IsCompacting()) {
1774 // When compacting forbid short-circuiting of cons-strings.
1775 // Scavenging code relies on the fact that new space object
1776 // can't be evacuated into evacuation candidate but
1777 // short-circuiting violates this assumption.
1778 scavenging_visitors_table_.Register(
1779 StaticVisitorBase::kVisitShortcutCandidate,
1780 scavenging_visitors_table_.GetVisitorById(
1781 StaticVisitorBase::kVisitConsString));
1782 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001783 }
1784}
Steve Blocka7e24c12009-10-30 11:49:00 +00001785
1786
1787void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001788 SLOW_ASSERT(HEAP->InFromSpace(object));
Steve Blocka7e24c12009-10-30 11:49:00 +00001789 MapWord first_word = object->map_word();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001790 SLOW_ASSERT(!first_word.IsForwardingAddress());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001791 Map* map = first_word.ToMap();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001792 map->GetHeap()->DoScavengeObject(map, p, object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001793}
1794
1795
John Reck59135872010-11-02 12:39:01 -07001796MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1797 int instance_size) {
1798 Object* result;
1799 { MaybeObject* maybe_result = AllocateRawMap();
1800 if (!maybe_result->ToObject(&result)) return maybe_result;
1801 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001802
1803 // Map::cast cannot be used due to uninitialized map field.
1804 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1805 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1806 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
Steve Block44f0eee2011-05-26 01:26:41 +01001807 reinterpret_cast<Map*>(result)->set_visitor_id(
1808 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Steve Blocka7e24c12009-10-30 11:49:00 +00001809 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001810 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001811 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001812 reinterpret_cast<Map*>(result)->set_bit_field(0);
1813 reinterpret_cast<Map*>(result)->set_bit_field2(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001814 return result;
1815}
1816
1817
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001818MaybeObject* Heap::AllocateMap(InstanceType instance_type,
1819 int instance_size,
1820 ElementsKind elements_kind) {
John Reck59135872010-11-02 12:39:01 -07001821 Object* result;
1822 { MaybeObject* maybe_result = AllocateRawMap();
1823 if (!maybe_result->ToObject(&result)) return maybe_result;
1824 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001825
1826 Map* map = reinterpret_cast<Map*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001827 map->set_map_unsafe(meta_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00001828 map->set_instance_type(instance_type);
Iain Merrick75681382010-08-19 15:07:18 +01001829 map->set_visitor_id(
1830 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001831 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
1832 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001833 map->set_instance_size(instance_size);
1834 map->set_inobject_properties(0);
1835 map->set_pre_allocated_property_fields(0);
Ben Murdoch257744e2011-11-30 15:57:28 +00001836 map->init_instance_descriptors();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001837 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1838 map->set_prototype_transitions(empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Blocka7e24c12009-10-30 11:49:00 +00001839 map->set_unused_property_fields(0);
1840 map->set_bit_field(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001841 map->set_bit_field2(1 << Map::kIsExtensible);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001842 map->set_elements_kind(elements_kind);
Leon Clarkee46be812010-01-19 14:06:41 +00001843
1844 // If the map object is aligned fill the padding area with Smi 0 objects.
1845 if (Map::kPadStart < Map::kSize) {
1846 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1847 0,
1848 Map::kSize - Map::kPadStart);
1849 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001850 return map;
1851}
1852
1853
John Reck59135872010-11-02 12:39:01 -07001854MaybeObject* Heap::AllocateCodeCache() {
1855 Object* result;
1856 { MaybeObject* maybe_result = AllocateStruct(CODE_CACHE_TYPE);
1857 if (!maybe_result->ToObject(&result)) return maybe_result;
1858 }
Steve Block6ded16b2010-05-10 14:33:55 +01001859 CodeCache* code_cache = CodeCache::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001860 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1861 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
Steve Block6ded16b2010-05-10 14:33:55 +01001862 return code_cache;
1863}
1864
1865
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001866MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1867 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1868}
1869
1870
Steve Blocka7e24c12009-10-30 11:49:00 +00001871const Heap::StringTypeTable Heap::string_type_table[] = {
1872#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1873 {type, size, k##camel_name##MapRootIndex},
1874 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1875#undef STRING_TYPE_ELEMENT
1876};
1877
1878
1879const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1880#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1881 {contents, k##name##RootIndex},
1882 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1883#undef CONSTANT_SYMBOL_ELEMENT
1884};
1885
1886
1887const Heap::StructTable Heap::struct_table[] = {
1888#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1889 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1890 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1891#undef STRUCT_TABLE_ELEMENT
1892};
1893
1894
1895bool Heap::CreateInitialMaps() {
John Reck59135872010-11-02 12:39:01 -07001896 Object* obj;
1897 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1898 if (!maybe_obj->ToObject(&obj)) return false;
1899 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001900 // Map::cast cannot be used due to uninitialized map field.
1901 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1902 set_meta_map(new_meta_map);
1903 new_meta_map->set_map(new_meta_map);
1904
John Reck59135872010-11-02 12:39:01 -07001905 { MaybeObject* maybe_obj =
1906 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1907 if (!maybe_obj->ToObject(&obj)) return false;
1908 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001909 set_fixed_array_map(Map::cast(obj));
1910
John Reck59135872010-11-02 12:39:01 -07001911 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1912 if (!maybe_obj->ToObject(&obj)) return false;
1913 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001914 set_oddball_map(Map::cast(obj));
1915
Steve Block6ded16b2010-05-10 14:33:55 +01001916 // Allocate the empty array.
John Reck59135872010-11-02 12:39:01 -07001917 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1918 if (!maybe_obj->ToObject(&obj)) return false;
1919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001920 set_empty_fixed_array(FixedArray::cast(obj));
1921
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001922 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07001923 if (!maybe_obj->ToObject(&obj)) return false;
1924 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001925 set_null_value(Oddball::cast(obj));
Steve Block44f0eee2011-05-26 01:26:41 +01001926 Oddball::cast(obj)->set_kind(Oddball::kNull);
Steve Blocka7e24c12009-10-30 11:49:00 +00001927
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001928 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
1929 if (!maybe_obj->ToObject(&obj)) return false;
1930 }
1931 set_undefined_value(Oddball::cast(obj));
1932 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
1933 ASSERT(!InNewSpace(undefined_value()));
1934
Steve Blocka7e24c12009-10-30 11:49:00 +00001935 // Allocate the empty descriptor array.
John Reck59135872010-11-02 12:39:01 -07001936 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1937 if (!maybe_obj->ToObject(&obj)) return false;
1938 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001939 set_empty_descriptor_array(DescriptorArray::cast(obj));
1940
1941 // Fix the instance_descriptors for the existing maps.
Ben Murdoch257744e2011-11-30 15:57:28 +00001942 meta_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00001943 meta_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01001944 meta_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00001945
Ben Murdoch257744e2011-11-30 15:57:28 +00001946 fixed_array_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00001947 fixed_array_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01001948 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00001949
Ben Murdoch257744e2011-11-30 15:57:28 +00001950 oddball_map()->init_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00001951 oddball_map()->set_code_cache(empty_fixed_array());
Steve Block053d10c2011-06-13 19:13:29 +01001952 oddball_map()->set_prototype_transitions(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00001953
1954 // Fix prototype object for existing maps.
1955 meta_map()->set_prototype(null_value());
1956 meta_map()->set_constructor(null_value());
1957
1958 fixed_array_map()->set_prototype(null_value());
1959 fixed_array_map()->set_constructor(null_value());
1960
1961 oddball_map()->set_prototype(null_value());
1962 oddball_map()->set_constructor(null_value());
1963
John Reck59135872010-11-02 12:39:01 -07001964 { MaybeObject* maybe_obj =
1965 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1966 if (!maybe_obj->ToObject(&obj)) return false;
1967 }
Iain Merrick75681382010-08-19 15:07:18 +01001968 set_fixed_cow_array_map(Map::cast(obj));
1969 ASSERT(fixed_array_map() != fixed_cow_array_map());
1970
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001971 { MaybeObject* maybe_obj =
1972 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1973 if (!maybe_obj->ToObject(&obj)) return false;
1974 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001975 set_scope_info_map(Map::cast(obj));
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001976
John Reck59135872010-11-02 12:39:01 -07001977 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1978 if (!maybe_obj->ToObject(&obj)) return false;
1979 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001980 set_heap_number_map(Map::cast(obj));
1981
Ben Murdoch257744e2011-11-30 15:57:28 +00001982 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
John Reck59135872010-11-02 12:39:01 -07001983 if (!maybe_obj->ToObject(&obj)) return false;
1984 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001985 set_foreign_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001986
1987 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1988 const StringTypeTable& entry = string_type_table[i];
John Reck59135872010-11-02 12:39:01 -07001989 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
1990 if (!maybe_obj->ToObject(&obj)) return false;
1991 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001992 roots_[entry.index] = Map::cast(obj);
1993 }
1994
John Reck59135872010-11-02 12:39:01 -07001995 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
1996 if (!maybe_obj->ToObject(&obj)) return false;
1997 }
Steve Blockd0582a62009-12-15 09:54:21 +00001998 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001999 Map::cast(obj)->set_is_undetectable();
2000
John Reck59135872010-11-02 12:39:01 -07002001 { MaybeObject* maybe_obj =
2002 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2003 if (!maybe_obj->ToObject(&obj)) return false;
2004 }
Steve Blockd0582a62009-12-15 09:54:21 +00002005 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002006 Map::cast(obj)->set_is_undetectable();
2007
John Reck59135872010-11-02 12:39:01 -07002008 { MaybeObject* maybe_obj =
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002009 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2010 if (!maybe_obj->ToObject(&obj)) return false;
2011 }
2012 set_fixed_double_array_map(Map::cast(obj));
2013
2014 { MaybeObject* maybe_obj =
John Reck59135872010-11-02 12:39:01 -07002015 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2016 if (!maybe_obj->ToObject(&obj)) return false;
2017 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002018 set_byte_array_map(Map::cast(obj));
2019
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002020 { MaybeObject* maybe_obj =
2021 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2022 if (!maybe_obj->ToObject(&obj)) return false;
2023 }
2024 set_free_space_map(Map::cast(obj));
2025
Ben Murdochb0fe1622011-05-05 13:52:32 +01002026 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2027 if (!maybe_obj->ToObject(&obj)) return false;
2028 }
2029 set_empty_byte_array(ByteArray::cast(obj));
2030
John Reck59135872010-11-02 12:39:01 -07002031 { MaybeObject* maybe_obj =
Steve Block44f0eee2011-05-26 01:26:41 +01002032 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
John Reck59135872010-11-02 12:39:01 -07002033 if (!maybe_obj->ToObject(&obj)) return false;
2034 }
Steve Block44f0eee2011-05-26 01:26:41 +01002035 set_external_pixel_array_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002036
John Reck59135872010-11-02 12:39:01 -07002037 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2038 ExternalArray::kAlignedSize);
2039 if (!maybe_obj->ToObject(&obj)) return false;
2040 }
Steve Block3ce2e202009-11-05 08:53:23 +00002041 set_external_byte_array_map(Map::cast(obj));
2042
John Reck59135872010-11-02 12:39:01 -07002043 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2044 ExternalArray::kAlignedSize);
2045 if (!maybe_obj->ToObject(&obj)) return false;
2046 }
Steve Block3ce2e202009-11-05 08:53:23 +00002047 set_external_unsigned_byte_array_map(Map::cast(obj));
2048
John Reck59135872010-11-02 12:39:01 -07002049 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2050 ExternalArray::kAlignedSize);
2051 if (!maybe_obj->ToObject(&obj)) return false;
2052 }
Steve Block3ce2e202009-11-05 08:53:23 +00002053 set_external_short_array_map(Map::cast(obj));
2054
John Reck59135872010-11-02 12:39:01 -07002055 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2056 ExternalArray::kAlignedSize);
2057 if (!maybe_obj->ToObject(&obj)) return false;
2058 }
Steve Block3ce2e202009-11-05 08:53:23 +00002059 set_external_unsigned_short_array_map(Map::cast(obj));
2060
John Reck59135872010-11-02 12:39:01 -07002061 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2062 ExternalArray::kAlignedSize);
2063 if (!maybe_obj->ToObject(&obj)) return false;
2064 }
Steve Block3ce2e202009-11-05 08:53:23 +00002065 set_external_int_array_map(Map::cast(obj));
2066
John Reck59135872010-11-02 12:39:01 -07002067 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2068 ExternalArray::kAlignedSize);
2069 if (!maybe_obj->ToObject(&obj)) return false;
2070 }
Steve Block3ce2e202009-11-05 08:53:23 +00002071 set_external_unsigned_int_array_map(Map::cast(obj));
2072
John Reck59135872010-11-02 12:39:01 -07002073 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2074 ExternalArray::kAlignedSize);
2075 if (!maybe_obj->ToObject(&obj)) return false;
2076 }
Steve Block3ce2e202009-11-05 08:53:23 +00002077 set_external_float_array_map(Map::cast(obj));
2078
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002079 { MaybeObject* maybe_obj =
2080 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2081 if (!maybe_obj->ToObject(&obj)) return false;
2082 }
2083 set_non_strict_arguments_elements_map(Map::cast(obj));
2084
Ben Murdoch257744e2011-11-30 15:57:28 +00002085 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2086 ExternalArray::kAlignedSize);
2087 if (!maybe_obj->ToObject(&obj)) return false;
2088 }
2089 set_external_double_array_map(Map::cast(obj));
2090
John Reck59135872010-11-02 12:39:01 -07002091 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2092 if (!maybe_obj->ToObject(&obj)) return false;
2093 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002094 set_code_map(Map::cast(obj));
2095
John Reck59135872010-11-02 12:39:01 -07002096 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2097 JSGlobalPropertyCell::kSize);
2098 if (!maybe_obj->ToObject(&obj)) return false;
2099 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002100 set_global_property_cell_map(Map::cast(obj));
2101
John Reck59135872010-11-02 12:39:01 -07002102 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2103 if (!maybe_obj->ToObject(&obj)) return false;
2104 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002105 set_one_pointer_filler_map(Map::cast(obj));
2106
John Reck59135872010-11-02 12:39:01 -07002107 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2108 if (!maybe_obj->ToObject(&obj)) return false;
2109 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002110 set_two_pointer_filler_map(Map::cast(obj));
2111
2112 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2113 const StructTable& entry = struct_table[i];
John Reck59135872010-11-02 12:39:01 -07002114 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2115 if (!maybe_obj->ToObject(&obj)) return false;
2116 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002117 roots_[entry.index] = Map::cast(obj);
2118 }
2119
John Reck59135872010-11-02 12:39:01 -07002120 { MaybeObject* maybe_obj =
2121 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2122 if (!maybe_obj->ToObject(&obj)) return false;
2123 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002124 set_hash_table_map(Map::cast(obj));
2125
John Reck59135872010-11-02 12:39:01 -07002126 { MaybeObject* maybe_obj =
2127 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2128 if (!maybe_obj->ToObject(&obj)) return false;
2129 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002130 set_function_context_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002131
John Reck59135872010-11-02 12:39:01 -07002132 { MaybeObject* maybe_obj =
2133 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2134 if (!maybe_obj->ToObject(&obj)) return false;
2135 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002136 set_catch_context_map(Map::cast(obj));
2137
John Reck59135872010-11-02 12:39:01 -07002138 { MaybeObject* maybe_obj =
2139 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2140 if (!maybe_obj->ToObject(&obj)) return false;
2141 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002142 set_with_context_map(Map::cast(obj));
2143
2144 { MaybeObject* maybe_obj =
2145 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2146 if (!maybe_obj->ToObject(&obj)) return false;
2147 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002148 set_block_context_map(Map::cast(obj));
2149
2150 { MaybeObject* maybe_obj =
2151 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2152 if (!maybe_obj->ToObject(&obj)) return false;
2153 }
Ben Murdochf87a2032010-10-22 12:50:53 +01002154 Map* global_context_map = Map::cast(obj);
2155 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2156 set_global_context_map(global_context_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002157
John Reck59135872010-11-02 12:39:01 -07002158 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2159 SharedFunctionInfo::kAlignedSize);
2160 if (!maybe_obj->ToObject(&obj)) return false;
2161 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002162 set_shared_function_info_map(Map::cast(obj));
2163
Steve Block1e0659c2011-05-24 12:43:12 +01002164 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2165 JSMessageObject::kSize);
2166 if (!maybe_obj->ToObject(&obj)) return false;
2167 }
2168 set_message_object_map(Map::cast(obj));
2169
Steve Block44f0eee2011-05-26 01:26:41 +01002170 ASSERT(!InNewSpace(empty_fixed_array()));
Steve Blocka7e24c12009-10-30 11:49:00 +00002171 return true;
2172}
2173
2174
John Reck59135872010-11-02 12:39:01 -07002175MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002176 // Statically ensure that it is safe to allocate heap numbers in paged
2177 // spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002178 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002179 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2180
John Reck59135872010-11-02 12:39:01 -07002181 Object* result;
2182 { MaybeObject* maybe_result =
2183 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2184 if (!maybe_result->ToObject(&result)) return maybe_result;
2185 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002186
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002187 HeapObject::cast(result)->set_map_unsafe(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002188 HeapNumber::cast(result)->set_value(value);
2189 return result;
2190}
2191
2192
John Reck59135872010-11-02 12:39:01 -07002193MaybeObject* Heap::AllocateHeapNumber(double value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002194 // Use general version, if we're forced to always allocate.
2195 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2196
2197 // This version of AllocateHeapNumber is optimized for
2198 // allocation in new space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002199 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002200 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
John Reck59135872010-11-02 12:39:01 -07002201 Object* result;
2202 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2203 if (!maybe_result->ToObject(&result)) return maybe_result;
2204 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002205 HeapObject::cast(result)->set_map_unsafe(heap_number_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002206 HeapNumber::cast(result)->set_value(value);
2207 return result;
2208}
2209
2210
John Reck59135872010-11-02 12:39:01 -07002211MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2212 Object* result;
2213 { MaybeObject* maybe_result = AllocateRawCell();
2214 if (!maybe_result->ToObject(&result)) return maybe_result;
2215 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002216 HeapObject::cast(result)->set_map_unsafe(global_property_cell_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002217 JSGlobalPropertyCell::cast(result)->set_value(value);
2218 return result;
2219}
2220
2221
John Reck59135872010-11-02 12:39:01 -07002222MaybeObject* Heap::CreateOddball(const char* to_string,
Steve Block44f0eee2011-05-26 01:26:41 +01002223 Object* to_number,
2224 byte kind) {
John Reck59135872010-11-02 12:39:01 -07002225 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002226 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07002227 if (!maybe_result->ToObject(&result)) return maybe_result;
2228 }
Steve Block44f0eee2011-05-26 01:26:41 +01002229 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
Steve Blocka7e24c12009-10-30 11:49:00 +00002230}
2231
2232
2233bool Heap::CreateApiObjects() {
2234 Object* obj;
2235
John Reck59135872010-11-02 12:39:01 -07002236 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2237 if (!maybe_obj->ToObject(&obj)) return false;
2238 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002239 // Don't use Smi-only elements optimizations for objects with the neander
2240 // map. There are too many cases where element values are set directly with a
2241 // bottleneck to trap the Smi-only -> fast elements transition, and there
2242 // appears to be no benefit for optimize this case.
2243 Map* new_neander_map = Map::cast(obj);
2244 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2245 set_neander_map(new_neander_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002246
Steve Block44f0eee2011-05-26 01:26:41 +01002247 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
John Reck59135872010-11-02 12:39:01 -07002248 if (!maybe_obj->ToObject(&obj)) return false;
2249 }
2250 Object* elements;
2251 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2252 if (!maybe_elements->ToObject(&elements)) return false;
2253 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002254 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2255 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2256 set_message_listeners(JSObject::cast(obj));
2257
2258 return true;
2259}
2260
2261
Steve Blocka7e24c12009-10-30 11:49:00 +00002262void Heap::CreateJSEntryStub() {
2263 JSEntryStub stub;
2264 set_js_entry_code(*stub.GetCode());
2265}
2266
2267
2268void Heap::CreateJSConstructEntryStub() {
2269 JSConstructEntryStub stub;
2270 set_js_construct_entry_code(*stub.GetCode());
2271}
2272
2273
2274void Heap::CreateFixedStubs() {
2275 // Here we create roots for fixed stubs. They are needed at GC
2276 // for cooking and uncooking (check out frames.cc).
2277 // The eliminates the need for doing dictionary lookup in the
2278 // stub cache for these stubs.
2279 HandleScope scope;
2280 // gcc-4.4 has problem generating correct code of following snippet:
Steve Block44f0eee2011-05-26 01:26:41 +01002281 // { JSEntryStub stub;
2282 // js_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002283 // }
Steve Block44f0eee2011-05-26 01:26:41 +01002284 // { JSConstructEntryStub stub;
2285 // js_construct_entry_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00002286 // }
2287 // To workaround the problem, make separate functions without inlining.
Steve Blocka7e24c12009-10-30 11:49:00 +00002288 Heap::CreateJSEntryStub();
2289 Heap::CreateJSConstructEntryStub();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002290
2291 // Create stubs that should be there, so we don't unexpectedly have to
2292 // create them if we need them during the creation of another stub.
2293 // Stub creation mixes raw pointers and handles in an unsafe manner so
2294 // we cannot create stubs while we are creating stubs.
2295 CodeStub::GenerateStubsAheadOfTime();
Steve Blocka7e24c12009-10-30 11:49:00 +00002296}
2297
2298
2299bool Heap::CreateInitialObjects() {
2300 Object* obj;
2301
2302 // The -0 value must be set before NumberFromDouble works.
John Reck59135872010-11-02 12:39:01 -07002303 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2304 if (!maybe_obj->ToObject(&obj)) return false;
2305 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002306 set_minus_zero_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002307 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2308
John Reck59135872010-11-02 12:39:01 -07002309 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2310 if (!maybe_obj->ToObject(&obj)) return false;
2311 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002312 set_nan_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002313
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002314 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
John Reck59135872010-11-02 12:39:01 -07002315 if (!maybe_obj->ToObject(&obj)) return false;
2316 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002317 set_infinity_value(HeapNumber::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002318
2319 // Allocate initial symbol table.
John Reck59135872010-11-02 12:39:01 -07002320 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2321 if (!maybe_obj->ToObject(&obj)) return false;
2322 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002323 // Don't use set_symbol_table() due to asserts.
2324 roots_[kSymbolTableRootIndex] = obj;
2325
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002326 // Finish initializing oddballs after creating symboltable.
John Reck59135872010-11-02 12:39:01 -07002327 { MaybeObject* maybe_obj =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002328 undefined_value()->Initialize("undefined",
2329 nan_value(),
2330 Oddball::kUndefined);
2331 if (!maybe_obj->ToObject(&obj)) return false;
2332 }
2333
2334 // Initialize the null_value.
2335 { MaybeObject* maybe_obj =
2336 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
John Reck59135872010-11-02 12:39:01 -07002337 if (!maybe_obj->ToObject(&obj)) return false;
2338 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002339
Steve Block44f0eee2011-05-26 01:26:41 +01002340 { MaybeObject* maybe_obj = CreateOddball("true",
2341 Smi::FromInt(1),
2342 Oddball::kTrue);
John Reck59135872010-11-02 12:39:01 -07002343 if (!maybe_obj->ToObject(&obj)) return false;
2344 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002345 set_true_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002346
Steve Block44f0eee2011-05-26 01:26:41 +01002347 { MaybeObject* maybe_obj = CreateOddball("false",
2348 Smi::FromInt(0),
2349 Oddball::kFalse);
John Reck59135872010-11-02 12:39:01 -07002350 if (!maybe_obj->ToObject(&obj)) return false;
2351 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002352 set_false_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002353
Steve Block44f0eee2011-05-26 01:26:41 +01002354 { MaybeObject* maybe_obj = CreateOddball("hole",
2355 Smi::FromInt(-1),
2356 Oddball::kTheHole);
John Reck59135872010-11-02 12:39:01 -07002357 if (!maybe_obj->ToObject(&obj)) return false;
2358 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002359 set_the_hole_value(Oddball::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002360
Ben Murdoch086aeea2011-05-13 15:57:08 +01002361 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002362 Smi::FromInt(-2),
Steve Block44f0eee2011-05-26 01:26:41 +01002363 Oddball::kArgumentMarker);
Ben Murdoch086aeea2011-05-13 15:57:08 +01002364 if (!maybe_obj->ToObject(&obj)) return false;
2365 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002366 set_arguments_marker(Oddball::cast(obj));
Ben Murdoch086aeea2011-05-13 15:57:08 +01002367
Steve Block44f0eee2011-05-26 01:26:41 +01002368 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002369 Smi::FromInt(-3),
Steve Block44f0eee2011-05-26 01:26:41 +01002370 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002371 if (!maybe_obj->ToObject(&obj)) return false;
2372 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002373 set_no_interceptor_result_sentinel(obj);
2374
Steve Block44f0eee2011-05-26 01:26:41 +01002375 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002376 Smi::FromInt(-4),
Steve Block44f0eee2011-05-26 01:26:41 +01002377 Oddball::kOther);
John Reck59135872010-11-02 12:39:01 -07002378 if (!maybe_obj->ToObject(&obj)) return false;
2379 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002380 set_termination_exception(obj);
2381
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002382 { MaybeObject* maybe_obj = CreateOddball("frame_alignment_marker",
2383 Smi::FromInt(-5),
2384 Oddball::kOther);
2385 if (!maybe_obj->ToObject(&obj)) return false;
2386 }
2387 set_frame_alignment_marker(Oddball::cast(obj));
2388 STATIC_ASSERT(Oddball::kLeastHiddenOddballNumber == -5);
2389
Steve Blocka7e24c12009-10-30 11:49:00 +00002390 // Allocate the empty string.
John Reck59135872010-11-02 12:39:01 -07002391 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2392 if (!maybe_obj->ToObject(&obj)) return false;
2393 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002394 set_empty_string(String::cast(obj));
2395
2396 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
John Reck59135872010-11-02 12:39:01 -07002397 { MaybeObject* maybe_obj =
2398 LookupAsciiSymbol(constant_symbol_table[i].contents);
2399 if (!maybe_obj->ToObject(&obj)) return false;
2400 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002401 roots_[constant_symbol_table[i].index] = String::cast(obj);
2402 }
2403
2404 // Allocate the hidden symbol which is used to identify the hidden properties
2405 // in JSObjects. The hash code has a special value so that it will not match
2406 // the empty string when searching for the property. It cannot be part of the
2407 // loop above because it needs to be allocated manually with the special
2408 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2409 // that it will always be at the first entry in property descriptors.
John Reck59135872010-11-02 12:39:01 -07002410 { MaybeObject* maybe_obj =
2411 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2412 if (!maybe_obj->ToObject(&obj)) return false;
2413 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002414 hidden_symbol_ = String::cast(obj);
2415
Ben Murdoch257744e2011-11-30 15:57:28 +00002416 // Allocate the foreign for __proto__.
John Reck59135872010-11-02 12:39:01 -07002417 { MaybeObject* maybe_obj =
Ben Murdoch257744e2011-11-30 15:57:28 +00002418 AllocateForeign((Address) &Accessors::ObjectPrototype);
John Reck59135872010-11-02 12:39:01 -07002419 if (!maybe_obj->ToObject(&obj)) return false;
2420 }
Ben Murdoch257744e2011-11-30 15:57:28 +00002421 set_prototype_accessors(Foreign::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002422
2423 // Allocate the code_stubs dictionary. The initial size is set to avoid
2424 // expanding the dictionary during bootstrapping.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002425 { MaybeObject* maybe_obj = NumberDictionary::Allocate(128);
John Reck59135872010-11-02 12:39:01 -07002426 if (!maybe_obj->ToObject(&obj)) return false;
2427 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002428 set_code_stubs(NumberDictionary::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002429
2430 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2431 // is set to avoid expanding the dictionary during bootstrapping.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002432 { MaybeObject* maybe_obj = NumberDictionary::Allocate(64);
John Reck59135872010-11-02 12:39:01 -07002433 if (!maybe_obj->ToObject(&obj)) return false;
2434 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002435 set_non_monomorphic_cache(NumberDictionary::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00002436
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002437 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2438 if (!maybe_obj->ToObject(&obj)) return false;
2439 }
2440 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2441
Kristian Monsen25f61362010-05-21 11:50:48 +01002442 set_instanceof_cache_function(Smi::FromInt(0));
2443 set_instanceof_cache_map(Smi::FromInt(0));
2444 set_instanceof_cache_answer(Smi::FromInt(0));
2445
Steve Blocka7e24c12009-10-30 11:49:00 +00002446 CreateFixedStubs();
2447
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002448 // Allocate the dictionary of intrinsic function names.
John Reck59135872010-11-02 12:39:01 -07002449 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2450 if (!maybe_obj->ToObject(&obj)) return false;
2451 }
Steve Block44f0eee2011-05-26 01:26:41 +01002452 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2453 obj);
John Reck59135872010-11-02 12:39:01 -07002454 if (!maybe_obj->ToObject(&obj)) return false;
2455 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002456 set_intrinsic_function_names(StringDictionary::cast(obj));
2457
Leon Clarkee46be812010-01-19 14:06:41 +00002458 if (InitializeNumberStringCache()->IsFailure()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002459
Steve Block6ded16b2010-05-10 14:33:55 +01002460 // Allocate cache for single character ASCII strings.
John Reck59135872010-11-02 12:39:01 -07002461 { MaybeObject* maybe_obj =
2462 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2463 if (!maybe_obj->ToObject(&obj)) return false;
2464 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002465 set_single_character_string_cache(FixedArray::cast(obj));
2466
Ben Murdoch589d6972011-11-30 16:04:58 +00002467 // Allocate cache for string split.
2468 { MaybeObject* maybe_obj =
2469 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2470 if (!maybe_obj->ToObject(&obj)) return false;
2471 }
2472 set_string_split_cache(FixedArray::cast(obj));
2473
Steve Blocka7e24c12009-10-30 11:49:00 +00002474 // Allocate cache for external strings pointing to native source code.
John Reck59135872010-11-02 12:39:01 -07002475 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2476 if (!maybe_obj->ToObject(&obj)) return false;
2477 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002478 set_natives_source_cache(FixedArray::cast(obj));
2479
Steve Block44f0eee2011-05-26 01:26:41 +01002480 // Handling of script id generation is in FACTORY->NewScript.
Steve Blocka7e24c12009-10-30 11:49:00 +00002481 set_last_script_id(undefined_value());
2482
2483 // Initialize keyed lookup cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002484 isolate_->keyed_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002485
2486 // Initialize context slot cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002487 isolate_->context_slot_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002488
2489 // Initialize descriptor cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002490 isolate_->descriptor_lookup_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002491
2492 // Initialize compilation cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002493 isolate_->compilation_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +00002494
2495 return true;
2496}
2497
2498
Ben Murdoch589d6972011-11-30 16:04:58 +00002499Object* StringSplitCache::Lookup(
2500 FixedArray* cache, String* string, String* pattern) {
2501 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2502 uint32_t hash = string->Hash();
2503 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2504 ~(kArrayEntriesPerCacheEntry - 1));
2505 if (cache->get(index + kStringOffset) == string &&
2506 cache->get(index + kPatternOffset) == pattern) {
2507 return cache->get(index + kArrayOffset);
2508 }
2509 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2510 if (cache->get(index + kStringOffset) == string &&
2511 cache->get(index + kPatternOffset) == pattern) {
2512 return cache->get(index + kArrayOffset);
2513 }
2514 return Smi::FromInt(0);
2515}
2516
2517
2518void StringSplitCache::Enter(Heap* heap,
2519 FixedArray* cache,
2520 String* string,
2521 String* pattern,
2522 FixedArray* array) {
2523 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2524 uint32_t hash = string->Hash();
2525 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2526 ~(kArrayEntriesPerCacheEntry - 1));
2527 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2528 cache->set(index + kStringOffset, string);
2529 cache->set(index + kPatternOffset, pattern);
2530 cache->set(index + kArrayOffset, array);
2531 } else {
2532 uint32_t index2 =
2533 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2534 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2535 cache->set(index2 + kStringOffset, string);
2536 cache->set(index2 + kPatternOffset, pattern);
2537 cache->set(index2 + kArrayOffset, array);
2538 } else {
2539 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2540 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2541 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2542 cache->set(index + kStringOffset, string);
2543 cache->set(index + kPatternOffset, pattern);
2544 cache->set(index + kArrayOffset, array);
2545 }
2546 }
2547 if (array->length() < 100) { // Limit how many new symbols we want to make.
2548 for (int i = 0; i < array->length(); i++) {
2549 String* str = String::cast(array->get(i));
2550 Object* symbol;
2551 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2552 if (maybe_symbol->ToObject(&symbol)) {
2553 array->set(i, symbol);
2554 }
2555 }
2556 }
2557 array->set_map(heap->fixed_cow_array_map());
2558}
2559
2560
2561void StringSplitCache::Clear(FixedArray* cache) {
2562 for (int i = 0; i < kStringSplitCacheSize; i++) {
2563 cache->set(i, Smi::FromInt(0));
2564 }
2565}
2566
2567
John Reck59135872010-11-02 12:39:01 -07002568MaybeObject* Heap::InitializeNumberStringCache() {
Leon Clarkee46be812010-01-19 14:06:41 +00002569 // Compute the size of the number string cache based on the max heap size.
2570 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
2571 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
2572 int number_string_cache_size = max_semispace_size_ / 512;
2573 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
John Reck59135872010-11-02 12:39:01 -07002574 Object* obj;
2575 MaybeObject* maybe_obj =
2576 AllocateFixedArray(number_string_cache_size * 2, TENURED);
2577 if (maybe_obj->ToObject(&obj)) set_number_string_cache(FixedArray::cast(obj));
2578 return maybe_obj;
Leon Clarkee46be812010-01-19 14:06:41 +00002579}
2580
2581
2582void Heap::FlushNumberStringCache() {
2583 // Flush the number to string cache.
2584 int len = number_string_cache()->length();
2585 for (int i = 0; i < len; i++) {
Steve Block44f0eee2011-05-26 01:26:41 +01002586 number_string_cache()->set_undefined(this, i);
Leon Clarkee46be812010-01-19 14:06:41 +00002587 }
2588}
2589
2590
Steve Blocka7e24c12009-10-30 11:49:00 +00002591static inline int double_get_hash(double d) {
2592 DoubleRepresentation rep(d);
Leon Clarkee46be812010-01-19 14:06:41 +00002593 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
Steve Blocka7e24c12009-10-30 11:49:00 +00002594}
2595
2596
2597static inline int smi_get_hash(Smi* smi) {
Leon Clarkee46be812010-01-19 14:06:41 +00002598 return smi->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002599}
2600
2601
Steve Blocka7e24c12009-10-30 11:49:00 +00002602Object* Heap::GetNumberStringCache(Object* number) {
2603 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002604 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002605 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002606 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002607 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002608 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002609 }
2610 Object* key = number_string_cache()->get(hash * 2);
2611 if (key == number) {
2612 return String::cast(number_string_cache()->get(hash * 2 + 1));
2613 } else if (key->IsHeapNumber() &&
2614 number->IsHeapNumber() &&
2615 key->Number() == number->Number()) {
2616 return String::cast(number_string_cache()->get(hash * 2 + 1));
2617 }
2618 return undefined_value();
2619}
2620
2621
2622void Heap::SetNumberStringCache(Object* number, String* string) {
2623 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002624 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002625 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002626 hash = smi_get_hash(Smi::cast(number)) & mask;
Leon Clarke4515c472010-02-03 11:58:03 +00002627 number_string_cache()->set(hash * 2, Smi::cast(number));
Steve Blocka7e24c12009-10-30 11:49:00 +00002628 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002629 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002630 number_string_cache()->set(hash * 2, number);
2631 }
2632 number_string_cache()->set(hash * 2 + 1, string);
2633}
2634
2635
John Reck59135872010-11-02 12:39:01 -07002636MaybeObject* Heap::NumberToString(Object* number,
2637 bool check_number_string_cache) {
Steve Block44f0eee2011-05-26 01:26:41 +01002638 isolate_->counters()->number_to_string_runtime()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002639 if (check_number_string_cache) {
2640 Object* cached = GetNumberStringCache(number);
2641 if (cached != undefined_value()) {
2642 return cached;
2643 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002644 }
2645
2646 char arr[100];
2647 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2648 const char* str;
2649 if (number->IsSmi()) {
2650 int num = Smi::cast(number)->value();
2651 str = IntToCString(num, buffer);
2652 } else {
2653 double num = HeapNumber::cast(number)->value();
2654 str = DoubleToCString(num, buffer);
2655 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002656
John Reck59135872010-11-02 12:39:01 -07002657 Object* js_string;
2658 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2659 if (maybe_js_string->ToObject(&js_string)) {
2660 SetNumberStringCache(number, String::cast(js_string));
Steve Blocka7e24c12009-10-30 11:49:00 +00002661 }
John Reck59135872010-11-02 12:39:01 -07002662 return maybe_js_string;
Steve Blocka7e24c12009-10-30 11:49:00 +00002663}
2664
2665
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002666MaybeObject* Heap::Uint32ToString(uint32_t value,
2667 bool check_number_string_cache) {
2668 Object* number;
2669 MaybeObject* maybe = NumberFromUint32(value);
2670 if (!maybe->To<Object>(&number)) return maybe;
2671 return NumberToString(number, check_number_string_cache);
2672}
2673
2674
Steve Block3ce2e202009-11-05 08:53:23 +00002675Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2676 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2677}
2678
2679
2680Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2681 ExternalArrayType array_type) {
2682 switch (array_type) {
2683 case kExternalByteArray:
2684 return kExternalByteArrayMapRootIndex;
2685 case kExternalUnsignedByteArray:
2686 return kExternalUnsignedByteArrayMapRootIndex;
2687 case kExternalShortArray:
2688 return kExternalShortArrayMapRootIndex;
2689 case kExternalUnsignedShortArray:
2690 return kExternalUnsignedShortArrayMapRootIndex;
2691 case kExternalIntArray:
2692 return kExternalIntArrayMapRootIndex;
2693 case kExternalUnsignedIntArray:
2694 return kExternalUnsignedIntArrayMapRootIndex;
2695 case kExternalFloatArray:
2696 return kExternalFloatArrayMapRootIndex;
Ben Murdoch257744e2011-11-30 15:57:28 +00002697 case kExternalDoubleArray:
2698 return kExternalDoubleArrayMapRootIndex;
Steve Block44f0eee2011-05-26 01:26:41 +01002699 case kExternalPixelArray:
2700 return kExternalPixelArrayMapRootIndex;
Steve Block3ce2e202009-11-05 08:53:23 +00002701 default:
2702 UNREACHABLE();
2703 return kUndefinedValueRootIndex;
2704 }
2705}
2706
2707
John Reck59135872010-11-02 12:39:01 -07002708MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01002709 // We need to distinguish the minus zero value and this cannot be
2710 // done after conversion to int. Doing this by comparing bit
2711 // patterns is faster than using fpclassify() et al.
2712 static const DoubleRepresentation minus_zero(-0.0);
2713
2714 DoubleRepresentation rep(value);
2715 if (rep.bits == minus_zero.bits) {
2716 return AllocateHeapNumber(-0.0, pretenure);
2717 }
2718
2719 int int_value = FastD2I(value);
2720 if (value == int_value && Smi::IsValid(int_value)) {
2721 return Smi::FromInt(int_value);
2722 }
2723
2724 // Materialize the value in the heap.
2725 return AllocateHeapNumber(value, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00002726}
2727
2728
Ben Murdoch257744e2011-11-30 15:57:28 +00002729MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2730 // Statically ensure that it is safe to allocate foreigns in paged spaces.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002731 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002732 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002733 Foreign* result;
2734 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2735 if (!maybe_result->To(&result)) return maybe_result;
2736 result->set_foreign_address(address);
Steve Blocka7e24c12009-10-30 11:49:00 +00002737 return result;
2738}
2739
2740
John Reck59135872010-11-02 12:39:01 -07002741MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002742 SharedFunctionInfo* share;
2743 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2744 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
Steve Blocka7e24c12009-10-30 11:49:00 +00002745
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002746 // Set pointer fields.
Steve Blocka7e24c12009-10-30 11:49:00 +00002747 share->set_name(name);
Steve Block44f0eee2011-05-26 01:26:41 +01002748 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
Steve Blocka7e24c12009-10-30 11:49:00 +00002749 share->set_code(illegal);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002750 share->set_scope_info(ScopeInfo::Empty());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002751 Code* construct_stub =
2752 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
Steve Blocka7e24c12009-10-30 11:49:00 +00002753 share->set_construct_stub(construct_stub);
Steve Blocka7e24c12009-10-30 11:49:00 +00002754 share->set_instance_class_name(Object_symbol());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002755 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
2756 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
2757 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
2758 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
2759 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
2760 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002761 share->set_deopt_counter(Smi::FromInt(FLAG_deopt_every_n_times));
2762
2763 // Set integer fields (smi or int, depending on the architecture).
2764 share->set_length(0);
2765 share->set_formal_parameter_count(0);
2766 share->set_expected_nof_properties(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002767 share->set_num_literals(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002768 share->set_start_position_and_type(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002769 share->set_end_position(0);
2770 share->set_function_token_position(0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002771 // All compiler hints default to false or 0.
2772 share->set_compiler_hints(0);
2773 share->set_this_property_assignments_count(0);
2774 share->set_opt_count(0);
2775
2776 return share;
Steve Blocka7e24c12009-10-30 11:49:00 +00002777}
2778
2779
Steve Block1e0659c2011-05-24 12:43:12 +01002780MaybeObject* Heap::AllocateJSMessageObject(String* type,
2781 JSArray* arguments,
2782 int start_position,
2783 int end_position,
2784 Object* script,
2785 Object* stack_trace,
2786 Object* stack_frames) {
2787 Object* result;
2788 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2789 if (!maybe_result->ToObject(&result)) return maybe_result;
2790 }
2791 JSMessageObject* message = JSMessageObject::cast(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002792 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2793 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
Steve Block1e0659c2011-05-24 12:43:12 +01002794 message->set_type(type);
2795 message->set_arguments(arguments);
2796 message->set_start_position(start_position);
2797 message->set_end_position(end_position);
2798 message->set_script(script);
2799 message->set_stack_trace(stack_trace);
2800 message->set_stack_frames(stack_frames);
2801 return result;
2802}
2803
2804
2805
Steve Blockd0582a62009-12-15 09:54:21 +00002806// Returns true for a character in a range. Both limits are inclusive.
2807static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2808 // This makes uses of the the unsigned wraparound.
2809 return character - from <= to - from;
2810}
2811
2812
John Reck59135872010-11-02 12:39:01 -07002813MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
Steve Block44f0eee2011-05-26 01:26:41 +01002814 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07002815 uint32_t c1,
2816 uint32_t c2) {
Steve Blockd0582a62009-12-15 09:54:21 +00002817 String* symbol;
2818 // Numeric strings have a different hash algorithm not known by
2819 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2820 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
Steve Block44f0eee2011-05-26 01:26:41 +01002821 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
Steve Blockd0582a62009-12-15 09:54:21 +00002822 return symbol;
2823 // Now we know the length is 2, we might as well make use of that fact
2824 // when building the new string.
2825 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2826 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
John Reck59135872010-11-02 12:39:01 -07002827 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002828 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
John Reck59135872010-11-02 12:39:01 -07002829 if (!maybe_result->ToObject(&result)) return maybe_result;
2830 }
Steve Blockd0582a62009-12-15 09:54:21 +00002831 char* dest = SeqAsciiString::cast(result)->GetChars();
2832 dest[0] = c1;
2833 dest[1] = c2;
2834 return result;
2835 } else {
John Reck59135872010-11-02 12:39:01 -07002836 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01002837 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
John Reck59135872010-11-02 12:39:01 -07002838 if (!maybe_result->ToObject(&result)) return maybe_result;
2839 }
Steve Blockd0582a62009-12-15 09:54:21 +00002840 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2841 dest[0] = c1;
2842 dest[1] = c2;
2843 return result;
2844 }
2845}
2846
2847
John Reck59135872010-11-02 12:39:01 -07002848MaybeObject* Heap::AllocateConsString(String* first, String* second) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002849 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002850 if (first_length == 0) {
2851 return second;
2852 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002853
2854 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002855 if (second_length == 0) {
2856 return first;
2857 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002858
2859 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00002860
2861 // Optimization for 2-byte strings often used as keys in a decompression
2862 // dictionary. Check whether we already have the string in the symbol
2863 // table to prevent creation of many unneccesary strings.
2864 if (length == 2) {
2865 unsigned c1 = first->Get(0);
2866 unsigned c2 = second->Get(0);
Steve Block44f0eee2011-05-26 01:26:41 +01002867 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blockd0582a62009-12-15 09:54:21 +00002868 }
2869
Steve Block6ded16b2010-05-10 14:33:55 +01002870 bool first_is_ascii = first->IsAsciiRepresentation();
2871 bool second_is_ascii = second->IsAsciiRepresentation();
2872 bool is_ascii = first_is_ascii && second_is_ascii;
Steve Blocka7e24c12009-10-30 11:49:00 +00002873
2874 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00002875 // of the new cons string is too large.
2876 if (length > String::kMaxLength || length < 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01002877 isolate()->context()->mark_out_of_memory();
Steve Blocka7e24c12009-10-30 11:49:00 +00002878 return Failure::OutOfMemoryException();
2879 }
2880
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002881 bool is_ascii_data_in_two_byte_string = false;
2882 if (!is_ascii) {
2883 // At least one of the strings uses two-byte representation so we
2884 // can't use the fast case code for short ascii strings below, but
2885 // we can try to save memory if all chars actually fit in ascii.
2886 is_ascii_data_in_two_byte_string =
2887 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
2888 if (is_ascii_data_in_two_byte_string) {
Steve Block44f0eee2011-05-26 01:26:41 +01002889 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002890 }
2891 }
2892
Steve Blocka7e24c12009-10-30 11:49:00 +00002893 // If the resulting string is small make a flat string.
2894 if (length < String::kMinNonFlatLength) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002895 // Note that neither of the two inputs can be a slice because:
2896 STATIC_ASSERT(String::kMinNonFlatLength <= SlicedString::kMinLength);
Steve Blocka7e24c12009-10-30 11:49:00 +00002897 ASSERT(first->IsFlat());
2898 ASSERT(second->IsFlat());
2899 if (is_ascii) {
John Reck59135872010-11-02 12:39:01 -07002900 Object* result;
2901 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2902 if (!maybe_result->ToObject(&result)) return maybe_result;
2903 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002904 // Copy the characters into the new object.
2905 char* dest = SeqAsciiString::cast(result)->GetChars();
2906 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00002907 const char* src;
2908 if (first->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002909 src = ExternalAsciiString::cast(first)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00002910 } else {
2911 src = SeqAsciiString::cast(first)->GetChars();
2912 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002913 for (int i = 0; i < first_length; i++) *dest++ = src[i];
2914 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00002915 if (second->IsExternalString()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002916 src = ExternalAsciiString::cast(second)->GetChars();
Steve Blockd0582a62009-12-15 09:54:21 +00002917 } else {
2918 src = SeqAsciiString::cast(second)->GetChars();
2919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002920 for (int i = 0; i < second_length; i++) *dest++ = src[i];
2921 return result;
2922 } else {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002923 if (is_ascii_data_in_two_byte_string) {
John Reck59135872010-11-02 12:39:01 -07002924 Object* result;
2925 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2926 if (!maybe_result->ToObject(&result)) return maybe_result;
2927 }
Steve Block6ded16b2010-05-10 14:33:55 +01002928 // Copy the characters into the new object.
2929 char* dest = SeqAsciiString::cast(result)->GetChars();
2930 String::WriteToFlat(first, dest, 0, first_length);
2931 String::WriteToFlat(second, dest + first_length, 0, second_length);
Steve Block44f0eee2011-05-26 01:26:41 +01002932 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002933 return result;
2934 }
2935
John Reck59135872010-11-02 12:39:01 -07002936 Object* result;
2937 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
2938 if (!maybe_result->ToObject(&result)) return maybe_result;
2939 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002940 // Copy the characters into the new object.
2941 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2942 String::WriteToFlat(first, dest, 0, first_length);
2943 String::WriteToFlat(second, dest + first_length, 0, second_length);
2944 return result;
2945 }
2946 }
2947
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002948 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
2949 cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002950
John Reck59135872010-11-02 12:39:01 -07002951 Object* result;
2952 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2953 if (!maybe_result->ToObject(&result)) return maybe_result;
2954 }
Leon Clarke4515c472010-02-03 11:58:03 +00002955
2956 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00002957 ConsString* cons_string = ConsString::cast(result);
Leon Clarke4515c472010-02-03 11:58:03 +00002958 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002959 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002960 cons_string->set_hash_field(String::kEmptyHashField);
2961 cons_string->set_first(first, mode);
2962 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002963 return result;
2964}
2965
2966
John Reck59135872010-11-02 12:39:01 -07002967MaybeObject* Heap::AllocateSubString(String* buffer,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002968 int start,
2969 int end,
2970 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002971 int length = end - start;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002972 if (length == 0) {
2973 return empty_string();
2974 } else if (length == 1) {
Steve Block44f0eee2011-05-26 01:26:41 +01002975 return LookupSingleCharacterStringFromCode(buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00002976 } else if (length == 2) {
2977 // Optimization for 2-byte strings often used as keys in a decompression
2978 // dictionary. Check whether we already have the string in the symbol
2979 // table to prevent creation of many unneccesary strings.
2980 unsigned c1 = buffer->Get(start);
2981 unsigned c2 = buffer->Get(start + 1);
Steve Block44f0eee2011-05-26 01:26:41 +01002982 return MakeOrFindTwoCharacterString(this, c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00002983 }
2984
2985 // Make an attempt to flatten the buffer to reduce access time.
Leon Clarkef7060e22010-06-03 12:02:55 +01002986 buffer = buffer->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00002987
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002988 if (!FLAG_string_slices ||
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002989 !buffer->IsFlat() ||
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002990 length < SlicedString::kMinLength ||
2991 pretenure == TENURED) {
2992 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002993 // WriteToFlat takes care of the case when an indirect string has a
2994 // different encoding from its underlying string. These encodings may
2995 // differ because of externalization.
2996 bool is_ascii = buffer->IsAsciiRepresentation();
2997 { MaybeObject* maybe_result = is_ascii
2998 ? AllocateRawAsciiString(length, pretenure)
2999 : AllocateRawTwoByteString(length, pretenure);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003000 if (!maybe_result->ToObject(&result)) return maybe_result;
3001 }
3002 String* string_result = String::cast(result);
3003 // Copy the characters into the new object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003004 if (is_ascii) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003005 ASSERT(string_result->IsAsciiRepresentation());
3006 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3007 String::WriteToFlat(buffer, dest, start, end);
3008 } else {
3009 ASSERT(string_result->IsTwoByteRepresentation());
3010 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3011 String::WriteToFlat(buffer, dest, start, end);
3012 }
3013 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003014 }
Steve Blockd0582a62009-12-15 09:54:21 +00003015
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003016 ASSERT(buffer->IsFlat());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003017#if DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003018 if (FLAG_verify_heap) {
3019 buffer->StringVerify();
3020 }
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003021#endif
3022
3023 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003024 // When slicing an indirect string we use its encoding for a newly created
3025 // slice and don't check the encoding of the underlying string. This is safe
3026 // even if the encodings are different because of externalization. If an
3027 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3028 // codes of the underlying string must still fit into ASCII (because
3029 // externalization must not change char codes).
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003030 { Map* map = buffer->IsAsciiRepresentation()
3031 ? sliced_ascii_string_map()
3032 : sliced_string_map();
3033 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3034 if (!maybe_result->ToObject(&result)) return maybe_result;
3035 }
3036
3037 AssertNoAllocation no_gc;
3038 SlicedString* sliced_string = SlicedString::cast(result);
3039 sliced_string->set_length(length);
3040 sliced_string->set_hash_field(String::kEmptyHashField);
3041 if (buffer->IsConsString()) {
3042 ConsString* cons = ConsString::cast(buffer);
3043 ASSERT(cons->second()->length() == 0);
3044 sliced_string->set_parent(cons->first());
3045 sliced_string->set_offset(start);
3046 } else if (buffer->IsSlicedString()) {
3047 // Prevent nesting sliced strings.
3048 SlicedString* parent_slice = SlicedString::cast(buffer);
3049 sliced_string->set_parent(parent_slice->parent());
3050 sliced_string->set_offset(start + parent_slice->offset());
3051 } else {
3052 sliced_string->set_parent(buffer);
3053 sliced_string->set_offset(start);
3054 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003055 ASSERT(sliced_string->parent()->IsSeqString() ||
3056 sliced_string->parent()->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +00003057 return result;
3058}
3059
3060
John Reck59135872010-11-02 12:39:01 -07003061MaybeObject* Heap::AllocateExternalStringFromAscii(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003062 const ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003063 size_t length = resource->length();
3064 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003065 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003066 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00003067 }
3068
Steve Blockd0582a62009-12-15 09:54:21 +00003069 Map* map = external_ascii_string_map();
John Reck59135872010-11-02 12:39:01 -07003070 Object* result;
3071 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3072 if (!maybe_result->ToObject(&result)) return maybe_result;
3073 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003074
3075 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003076 external_string->set_length(static_cast<int>(length));
3077 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003078 external_string->set_resource(resource);
3079
3080 return result;
3081}
3082
3083
John Reck59135872010-11-02 12:39:01 -07003084MaybeObject* Heap::AllocateExternalStringFromTwoByte(
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003085 const ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00003086 size_t length = resource->length();
3087 if (length > static_cast<size_t>(String::kMaxLength)) {
Steve Block44f0eee2011-05-26 01:26:41 +01003088 isolate()->context()->mark_out_of_memory();
Steve Blockd0582a62009-12-15 09:54:21 +00003089 return Failure::OutOfMemoryException();
3090 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003091
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003092 // For small strings we check whether the resource contains only
Steve Block9fac8402011-05-12 15:51:54 +01003093 // ASCII characters. If yes, we use a different string map.
3094 static const size_t kAsciiCheckLengthLimit = 32;
3095 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3096 String::IsAscii(resource->data(), static_cast<int>(length));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003097 Map* map = is_ascii ?
Steve Block44f0eee2011-05-26 01:26:41 +01003098 external_string_with_ascii_data_map() : external_string_map();
John Reck59135872010-11-02 12:39:01 -07003099 Object* result;
3100 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3101 if (!maybe_result->ToObject(&result)) return maybe_result;
3102 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003103
3104 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003105 external_string->set_length(static_cast<int>(length));
3106 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003107 external_string->set_resource(resource);
3108
3109 return result;
3110}
3111
3112
John Reck59135872010-11-02 12:39:01 -07003113MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003114 if (code <= String::kMaxAsciiCharCode) {
Steve Block44f0eee2011-05-26 01:26:41 +01003115 Object* value = single_character_string_cache()->get(code);
3116 if (value != undefined_value()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00003117
3118 char buffer[1];
3119 buffer[0] = static_cast<char>(code);
John Reck59135872010-11-02 12:39:01 -07003120 Object* result;
3121 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00003122
John Reck59135872010-11-02 12:39:01 -07003123 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003124 single_character_string_cache()->set(code, result);
Steve Blocka7e24c12009-10-30 11:49:00 +00003125 return result;
3126 }
3127
John Reck59135872010-11-02 12:39:01 -07003128 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01003129 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
John Reck59135872010-11-02 12:39:01 -07003130 if (!maybe_result->ToObject(&result)) return maybe_result;
3131 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003132 String* answer = String::cast(result);
3133 answer->Set(0, code);
3134 return answer;
3135}
3136
3137
John Reck59135872010-11-02 12:39:01 -07003138MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003139 if (length < 0 || length > ByteArray::kMaxLength) {
3140 return Failure::OutOfMemoryException();
3141 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003142 if (pretenure == NOT_TENURED) {
3143 return AllocateByteArray(length);
3144 }
3145 int size = ByteArray::SizeFor(length);
John Reck59135872010-11-02 12:39:01 -07003146 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003147 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
John Reck59135872010-11-02 12:39:01 -07003148 ? old_data_space_->AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003149 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
John Reck59135872010-11-02 12:39:01 -07003150 if (!maybe_result->ToObject(&result)) return maybe_result;
3151 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003152
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003153 reinterpret_cast<ByteArray*>(result)->set_map_unsafe(byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003154 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003155 return result;
3156}
3157
3158
John Reck59135872010-11-02 12:39:01 -07003159MaybeObject* Heap::AllocateByteArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00003160 if (length < 0 || length > ByteArray::kMaxLength) {
3161 return Failure::OutOfMemoryException();
3162 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003163 int size = ByteArray::SizeFor(length);
3164 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003165 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003166 Object* result;
3167 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3168 if (!maybe_result->ToObject(&result)) return maybe_result;
3169 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003170
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003171 reinterpret_cast<ByteArray*>(result)->set_map_unsafe(byte_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003172 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003173 return result;
3174}
3175
3176
3177void Heap::CreateFillerObjectAt(Address addr, int size) {
3178 if (size == 0) return;
3179 HeapObject* filler = HeapObject::FromAddress(addr);
3180 if (size == kPointerSize) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003181 filler->set_map_unsafe(one_pointer_filler_map());
Steve Block6ded16b2010-05-10 14:33:55 +01003182 } else if (size == 2 * kPointerSize) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003183 filler->set_map_unsafe(two_pointer_filler_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003184 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003185 filler->set_map_unsafe(free_space_map());
3186 FreeSpace::cast(filler)->set_size(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003187 }
3188}
3189
3190
John Reck59135872010-11-02 12:39:01 -07003191MaybeObject* Heap::AllocateExternalArray(int length,
3192 ExternalArrayType array_type,
3193 void* external_pointer,
3194 PretenureFlag pretenure) {
Steve Block3ce2e202009-11-05 08:53:23 +00003195 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003196 Object* result;
3197 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3198 space,
3199 OLD_DATA_SPACE);
3200 if (!maybe_result->ToObject(&result)) return maybe_result;
3201 }
Steve Block3ce2e202009-11-05 08:53:23 +00003202
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003203 reinterpret_cast<ExternalArray*>(result)->set_map_unsafe(
Steve Block3ce2e202009-11-05 08:53:23 +00003204 MapForExternalArrayType(array_type));
3205 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3206 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3207 external_pointer);
3208
3209 return result;
3210}
3211
3212
John Reck59135872010-11-02 12:39:01 -07003213MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3214 Code::Flags flags,
Steve Block44f0eee2011-05-26 01:26:41 +01003215 Handle<Object> self_reference,
3216 bool immovable) {
Leon Clarkeac952652010-07-15 11:15:24 +01003217 // Allocate ByteArray before the Code object, so that we do not risk
3218 // leaving uninitialized Code object (and breaking the heap).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003219 ByteArray* reloc_info;
3220 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3221 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
Leon Clarkeac952652010-07-15 11:15:24 +01003222
Steve Block44f0eee2011-05-26 01:26:41 +01003223 // Compute size.
Leon Clarkeac952652010-07-15 11:15:24 +01003224 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003225 int obj_size = Code::SizeFor(body_size);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003226 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
John Reck59135872010-11-02 12:39:01 -07003227 MaybeObject* maybe_result;
Steve Block44f0eee2011-05-26 01:26:41 +01003228 // Large code objects and code objects which should stay at a fixed address
3229 // are allocated in large object space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003230 if (obj_size > code_space()->AreaSize() || immovable) {
3231 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003232 } else {
John Reck59135872010-11-02 12:39:01 -07003233 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003234 }
3235
John Reck59135872010-11-02 12:39:01 -07003236 Object* result;
3237 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003238
3239 // Initialize the object
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003240 HeapObject::cast(result)->set_map_unsafe(code_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003241 Code* code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003242 ASSERT(!isolate_->code_range()->exists() ||
3243 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003244 code->set_instruction_size(desc.instr_size);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003245 code->set_relocation_info(reloc_info);
Steve Blocka7e24c12009-10-30 11:49:00 +00003246 code->set_flags(flags);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003247 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3248 code->set_check_type(RECEIVER_MAP_CHECK);
3249 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003250 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3251 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
Ben Murdoch257744e2011-11-30 15:57:28 +00003252 code->set_next_code_flushing_candidate(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00003253 // Allow self references to created code object by patching the handle to
3254 // point to the newly allocated Code object.
3255 if (!self_reference.is_null()) {
3256 *(self_reference.location()) = code;
3257 }
3258 // Migrate generated code.
3259 // The generated code can contain Object** values (typically from handles)
3260 // that are dereferenced during the copy to point directly to the actual heap
3261 // objects. These pointers can include references to the code object itself,
3262 // through the self_reference parameter.
3263 code->CopyFrom(desc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003264
3265#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003266 if (FLAG_verify_heap) {
3267 code->Verify();
3268 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003269#endif
3270 return code;
3271}
3272
3273
John Reck59135872010-11-02 12:39:01 -07003274MaybeObject* Heap::CopyCode(Code* code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003275 // Allocate an object the same size as the code object.
3276 int obj_size = code->Size();
John Reck59135872010-11-02 12:39:01 -07003277 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003278 if (obj_size > code_space()->AreaSize()) {
3279 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003280 } else {
John Reck59135872010-11-02 12:39:01 -07003281 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003282 }
3283
John Reck59135872010-11-02 12:39:01 -07003284 Object* result;
3285 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003286
3287 // Copy code object.
3288 Address old_addr = code->address();
3289 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003290 CopyBlock(new_addr, old_addr, obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003291 // Relocate the copy.
3292 Code* new_code = Code::cast(result);
Steve Block44f0eee2011-05-26 01:26:41 +01003293 ASSERT(!isolate_->code_range()->exists() ||
3294 isolate_->code_range()->contains(code->address()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003295 new_code->Relocate(new_addr - old_addr);
3296 return new_code;
3297}
3298
3299
John Reck59135872010-11-02 12:39:01 -07003300MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
Leon Clarkeac952652010-07-15 11:15:24 +01003301 // Allocate ByteArray before the Code object, so that we do not risk
3302 // leaving uninitialized Code object (and breaking the heap).
John Reck59135872010-11-02 12:39:01 -07003303 Object* reloc_info_array;
3304 { MaybeObject* maybe_reloc_info_array =
3305 AllocateByteArray(reloc_info.length(), TENURED);
3306 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3307 return maybe_reloc_info_array;
3308 }
3309 }
Leon Clarkeac952652010-07-15 11:15:24 +01003310
3311 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
Steve Block6ded16b2010-05-10 14:33:55 +01003312
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003313 int new_obj_size = Code::SizeFor(new_body_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003314
3315 Address old_addr = code->address();
3316
3317 size_t relocation_offset =
Leon Clarkeac952652010-07-15 11:15:24 +01003318 static_cast<size_t>(code->instruction_end() - old_addr);
Steve Block6ded16b2010-05-10 14:33:55 +01003319
John Reck59135872010-11-02 12:39:01 -07003320 MaybeObject* maybe_result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003321 if (new_obj_size > code_space()->AreaSize()) {
3322 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
Steve Block6ded16b2010-05-10 14:33:55 +01003323 } else {
John Reck59135872010-11-02 12:39:01 -07003324 maybe_result = code_space_->AllocateRaw(new_obj_size);
Steve Block6ded16b2010-05-10 14:33:55 +01003325 }
3326
John Reck59135872010-11-02 12:39:01 -07003327 Object* result;
3328 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block6ded16b2010-05-10 14:33:55 +01003329
3330 // Copy code object.
3331 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3332
3333 // Copy header and instructions.
3334 memcpy(new_addr, old_addr, relocation_offset);
3335
Steve Block6ded16b2010-05-10 14:33:55 +01003336 Code* new_code = Code::cast(result);
Leon Clarkeac952652010-07-15 11:15:24 +01003337 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
Steve Block6ded16b2010-05-10 14:33:55 +01003338
Leon Clarkeac952652010-07-15 11:15:24 +01003339 // Copy patched rinfo.
3340 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
Steve Block6ded16b2010-05-10 14:33:55 +01003341
3342 // Relocate the copy.
Steve Block44f0eee2011-05-26 01:26:41 +01003343 ASSERT(!isolate_->code_range()->exists() ||
3344 isolate_->code_range()->contains(code->address()));
Steve Block6ded16b2010-05-10 14:33:55 +01003345 new_code->Relocate(new_addr - old_addr);
3346
3347#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003348 if (FLAG_verify_heap) {
3349 code->Verify();
3350 }
Steve Block6ded16b2010-05-10 14:33:55 +01003351#endif
3352 return new_code;
3353}
3354
3355
John Reck59135872010-11-02 12:39:01 -07003356MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003357 ASSERT(gc_state_ == NOT_IN_GC);
3358 ASSERT(map->instance_type() != MAP_TYPE);
Leon Clarkee46be812010-01-19 14:06:41 +00003359 // If allocation failures are disallowed, we may allocate in a different
3360 // space when new space is full and the object is not a large object.
3361 AllocationSpace retry_space =
3362 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
John Reck59135872010-11-02 12:39:01 -07003363 Object* result;
3364 { MaybeObject* maybe_result =
3365 AllocateRaw(map->instance_size(), space, retry_space);
3366 if (!maybe_result->ToObject(&result)) return maybe_result;
3367 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003368 // No need for write barrier since object is white and map is in old space.
3369 HeapObject::cast(result)->set_map_unsafe(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00003370 return result;
3371}
3372
3373
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003374void Heap::InitializeFunction(JSFunction* function,
3375 SharedFunctionInfo* shared,
3376 Object* prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003377 ASSERT(!prototype->IsMap());
3378 function->initialize_properties();
3379 function->initialize_elements();
3380 function->set_shared(shared);
Iain Merrick75681382010-08-19 15:07:18 +01003381 function->set_code(shared->code());
Steve Blocka7e24c12009-10-30 11:49:00 +00003382 function->set_prototype_or_initial_map(prototype);
3383 function->set_context(undefined_value());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003384 function->set_literals_or_bindings(empty_fixed_array());
Ben Murdochb0fe1622011-05-05 13:52:32 +01003385 function->set_next_function_link(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00003386}
3387
3388
John Reck59135872010-11-02 12:39:01 -07003389MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003390 // Allocate the prototype. Make sure to use the object function
3391 // from the function's context, since the function can be from a
3392 // different context.
3393 JSFunction* object_function =
3394 function->context()->global_context()->object_function();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003395
3396 // Each function prototype gets a copy of the object function map.
3397 // This avoid unwanted sharing of maps between prototypes of different
3398 // constructors.
3399 Map* new_map;
3400 ASSERT(object_function->has_initial_map());
3401 { MaybeObject* maybe_map =
3402 object_function->initial_map()->CopyDropTransitions();
3403 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3404 }
John Reck59135872010-11-02 12:39:01 -07003405 Object* prototype;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003406 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
John Reck59135872010-11-02 12:39:01 -07003407 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3408 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003409 // When creating the prototype for the function we must set its
3410 // constructor to the function.
John Reck59135872010-11-02 12:39:01 -07003411 Object* result;
3412 { MaybeObject* maybe_result =
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003413 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3414 constructor_symbol(), function, DONT_ENUM);
John Reck59135872010-11-02 12:39:01 -07003415 if (!maybe_result->ToObject(&result)) return maybe_result;
3416 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003417 return prototype;
3418}
3419
3420
John Reck59135872010-11-02 12:39:01 -07003421MaybeObject* Heap::AllocateFunction(Map* function_map,
3422 SharedFunctionInfo* shared,
3423 Object* prototype,
3424 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003425 AllocationSpace space =
3426 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07003427 Object* result;
3428 { MaybeObject* maybe_result = Allocate(function_map, space);
3429 if (!maybe_result->ToObject(&result)) return maybe_result;
3430 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003431 InitializeFunction(JSFunction::cast(result), shared, prototype);
3432 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003433}
3434
3435
John Reck59135872010-11-02 12:39:01 -07003436MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003437 // To get fast allocation and map sharing for arguments objects we
3438 // allocate them based on an arguments boilerplate.
3439
Steve Block44f0eee2011-05-26 01:26:41 +01003440 JSObject* boilerplate;
3441 int arguments_object_size;
3442 bool strict_mode_callee = callee->IsJSFunction() &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003443 !JSFunction::cast(callee)->shared()->is_classic_mode();
Steve Block44f0eee2011-05-26 01:26:41 +01003444 if (strict_mode_callee) {
3445 boilerplate =
3446 isolate()->context()->global_context()->
3447 strict_mode_arguments_boilerplate();
3448 arguments_object_size = kArgumentsObjectSizeStrict;
3449 } else {
3450 boilerplate =
3451 isolate()->context()->global_context()->arguments_boilerplate();
3452 arguments_object_size = kArgumentsObjectSize;
3453 }
3454
Steve Blocka7e24c12009-10-30 11:49:00 +00003455 // This calls Copy directly rather than using Heap::AllocateRaw so we
3456 // duplicate the check here.
3457 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3458
Leon Clarkee46be812010-01-19 14:06:41 +00003459 // Check that the size of the boilerplate matches our
3460 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3461 // on the size being a known constant.
Steve Block44f0eee2011-05-26 01:26:41 +01003462 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
Leon Clarkee46be812010-01-19 14:06:41 +00003463
3464 // Do the allocation.
John Reck59135872010-11-02 12:39:01 -07003465 Object* result;
3466 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01003467 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
John Reck59135872010-11-02 12:39:01 -07003468 if (!maybe_result->ToObject(&result)) return maybe_result;
3469 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003470
3471 // Copy the content. The arguments boilerplate doesn't have any
3472 // fields that point to new space so it's safe to skip the write
3473 // barrier here.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003474 CopyBlock(HeapObject::cast(result)->address(),
3475 boilerplate->address(),
Steve Block44f0eee2011-05-26 01:26:41 +01003476 JSObject::kHeaderSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003477
Steve Block44f0eee2011-05-26 01:26:41 +01003478 // Set the length property.
3479 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
Steve Blocka7e24c12009-10-30 11:49:00 +00003480 Smi::FromInt(length),
3481 SKIP_WRITE_BARRIER);
Steve Block44f0eee2011-05-26 01:26:41 +01003482 // Set the callee property for non-strict mode arguments object only.
3483 if (!strict_mode_callee) {
3484 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3485 callee);
3486 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003487
3488 // Check the state of the object
3489 ASSERT(JSObject::cast(result)->HasFastProperties());
3490 ASSERT(JSObject::cast(result)->HasFastElements());
3491
3492 return result;
3493}
3494
3495
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003496static bool HasDuplicates(DescriptorArray* descriptors) {
3497 int count = descriptors->number_of_descriptors();
3498 if (count > 1) {
3499 String* prev_key = descriptors->GetKey(0);
3500 for (int i = 1; i != count; i++) {
3501 String* current_key = descriptors->GetKey(i);
3502 if (prev_key == current_key) return true;
3503 prev_key = current_key;
3504 }
3505 }
3506 return false;
3507}
3508
3509
John Reck59135872010-11-02 12:39:01 -07003510MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003511 ASSERT(!fun->has_initial_map());
3512
3513 // First create a new map with the size and number of in-object properties
3514 // suggested by the function.
3515 int instance_size = fun->shared()->CalculateInstanceSize();
3516 int in_object_properties = fun->shared()->CalculateInObjectProperties();
John Reck59135872010-11-02 12:39:01 -07003517 Object* map_obj;
Steve Block44f0eee2011-05-26 01:26:41 +01003518 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
John Reck59135872010-11-02 12:39:01 -07003519 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3520 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003521
3522 // Fetch or allocate prototype.
3523 Object* prototype;
3524 if (fun->has_instance_prototype()) {
3525 prototype = fun->instance_prototype();
3526 } else {
John Reck59135872010-11-02 12:39:01 -07003527 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3528 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3529 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003530 }
3531 Map* map = Map::cast(map_obj);
3532 map->set_inobject_properties(in_object_properties);
3533 map->set_unused_property_fields(in_object_properties);
3534 map->set_prototype(prototype);
Steve Block8defd9f2010-07-08 12:39:36 +01003535 ASSERT(map->has_fast_elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003536
Andrei Popescu402d9372010-02-26 13:31:12 +00003537 // If the function has only simple this property assignments add
3538 // field descriptors for these to the initial map as the object
3539 // cannot be constructed without having these properties. Guard by
3540 // the inline_new flag so we only change the map if we generate a
3541 // specialized construct stub.
Steve Blocka7e24c12009-10-30 11:49:00 +00003542 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Andrei Popescu402d9372010-02-26 13:31:12 +00003543 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003544 int count = fun->shared()->this_property_assignments_count();
3545 if (count > in_object_properties) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003546 // Inline constructor can only handle inobject properties.
3547 fun->shared()->ForbidInlineConstructor();
3548 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003549 DescriptorArray* descriptors;
John Reck59135872010-11-02 12:39:01 -07003550 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003551 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
John Reck59135872010-11-02 12:39:01 -07003552 return maybe_descriptors_obj;
3553 }
3554 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003555 DescriptorArray::WhitenessWitness witness(descriptors);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003556 for (int i = 0; i < count; i++) {
3557 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3558 ASSERT(name->IsSymbol());
3559 FieldDescriptor field(name, i, NONE);
3560 field.SetEnumerationIndex(i);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003561 descriptors->Set(i, &field, witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003562 }
3563 descriptors->SetNextEnumerationIndex(count);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003564 descriptors->SortUnchecked(witness);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003565
3566 // The descriptors may contain duplicates because the compiler does not
3567 // guarantee the uniqueness of property names (it would have required
3568 // quadratic time). Once the descriptors are sorted we can check for
3569 // duplicates in linear time.
3570 if (HasDuplicates(descriptors)) {
3571 fun->shared()->ForbidInlineConstructor();
3572 } else {
3573 map->set_instance_descriptors(descriptors);
3574 map->set_pre_allocated_property_fields(count);
3575 map->set_unused_property_fields(in_object_properties - count);
3576 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003577 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003578 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003579
3580 fun->shared()->StartInobjectSlackTracking(map);
3581
Steve Blocka7e24c12009-10-30 11:49:00 +00003582 return map;
3583}
3584
3585
3586void Heap::InitializeJSObjectFromMap(JSObject* obj,
3587 FixedArray* properties,
3588 Map* map) {
3589 obj->set_properties(properties);
3590 obj->initialize_elements();
3591 // TODO(1240798): Initialize the object's body using valid initial values
3592 // according to the object's initial map. For example, if the map's
3593 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3594 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
3595 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
3596 // verification code has to cope with (temporarily) invalid objects. See
3597 // for example, JSArray::JSArrayVerify).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003598 Object* filler;
3599 // We cannot always fill with one_pointer_filler_map because objects
3600 // created from API functions expect their internal fields to be initialized
3601 // with undefined_value.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003602 // Pre-allocated fields need to be initialized with undefined_value as well
3603 // so that object accesses before the constructor completes (e.g. in the
3604 // debugger) will not cause a crash.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003605 if (map->constructor()->IsJSFunction() &&
3606 JSFunction::cast(map->constructor())->shared()->
3607 IsInobjectSlackTrackingInProgress()) {
3608 // We might want to shrink the object later.
3609 ASSERT(obj->GetInternalFieldCount() == 0);
3610 filler = Heap::one_pointer_filler_map();
3611 } else {
3612 filler = Heap::undefined_value();
3613 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003614 obj->InitializeBody(map, Heap::undefined_value(), filler);
Steve Blocka7e24c12009-10-30 11:49:00 +00003615}
3616
3617
John Reck59135872010-11-02 12:39:01 -07003618MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003619 // JSFunctions should be allocated using AllocateFunction to be
3620 // properly initialized.
3621 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3622
Steve Block8defd9f2010-07-08 12:39:36 +01003623 // Both types of global objects should be allocated using
3624 // AllocateGlobalObject to be properly initialized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003625 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3626 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3627
3628 // Allocate the backing storage for the properties.
3629 int prop_size =
3630 map->pre_allocated_property_fields() +
3631 map->unused_property_fields() -
3632 map->inobject_properties();
3633 ASSERT(prop_size >= 0);
John Reck59135872010-11-02 12:39:01 -07003634 Object* properties;
3635 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3636 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3637 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003638
3639 // Allocate the JSObject.
3640 AllocationSpace space =
3641 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003642 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
John Reck59135872010-11-02 12:39:01 -07003643 Object* obj;
3644 { MaybeObject* maybe_obj = Allocate(map, space);
3645 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3646 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003647
3648 // Initialize the JSObject.
3649 InitializeJSObjectFromMap(JSObject::cast(obj),
3650 FixedArray::cast(properties),
3651 map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003652 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3653 JSObject::cast(obj)->HasFastElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003654 return obj;
3655}
3656
3657
John Reck59135872010-11-02 12:39:01 -07003658MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3659 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003660 // Allocate the initial map if absent.
3661 if (!constructor->has_initial_map()) {
John Reck59135872010-11-02 12:39:01 -07003662 Object* initial_map;
3663 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3664 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3665 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003666 constructor->set_initial_map(Map::cast(initial_map));
3667 Map::cast(initial_map)->set_constructor(constructor);
3668 }
3669 // Allocate the object based on the constructors initial map.
John Reck59135872010-11-02 12:39:01 -07003670 MaybeObject* result =
Steve Blocka7e24c12009-10-30 11:49:00 +00003671 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
John Reck59135872010-11-02 12:39:01 -07003672#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00003673 // Make sure result is NOT a global object if valid.
John Reck59135872010-11-02 12:39:01 -07003674 Object* non_failure;
3675 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3676#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003677 return result;
3678}
3679
3680
Ben Murdoch257744e2011-11-30 15:57:28 +00003681MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3682 // Allocate map.
3683 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3684 // maps. Will probably depend on the identity of the handler object, too.
3685 Map* map;
3686 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3687 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3688 map->set_prototype(prototype);
Ben Murdoch257744e2011-11-30 15:57:28 +00003689
3690 // Allocate the proxy object.
Ben Murdoch589d6972011-11-30 16:04:58 +00003691 JSProxy* result;
Ben Murdoch257744e2011-11-30 15:57:28 +00003692 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
Ben Murdoch589d6972011-11-30 16:04:58 +00003693 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3694 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3695 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003696 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003697 return result;
3698}
3699
3700
3701MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3702 Object* call_trap,
3703 Object* construct_trap,
3704 Object* prototype) {
3705 // Allocate map.
3706 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3707 // maps. Will probably depend on the identity of the handler object, too.
3708 Map* map;
3709 MaybeObject* maybe_map_obj =
3710 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3711 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3712 map->set_prototype(prototype);
3713
3714 // Allocate the proxy object.
3715 JSFunctionProxy* result;
3716 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3717 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3718 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3719 result->set_handler(handler);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003720 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
Ben Murdoch589d6972011-11-30 16:04:58 +00003721 result->set_call_trap(call_trap);
3722 result->set_construct_trap(construct_trap);
Ben Murdoch257744e2011-11-30 15:57:28 +00003723 return result;
3724}
3725
3726
John Reck59135872010-11-02 12:39:01 -07003727MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003728 ASSERT(constructor->has_initial_map());
3729 Map* map = constructor->initial_map();
3730
3731 // Make sure no field properties are described in the initial map.
3732 // This guarantees us that normalizing the properties does not
3733 // require us to change property values to JSGlobalPropertyCells.
3734 ASSERT(map->NextFreePropertyIndex() == 0);
3735
3736 // Make sure we don't have a ton of pre-allocated slots in the
3737 // global objects. They will be unused once we normalize the object.
3738 ASSERT(map->unused_property_fields() == 0);
3739 ASSERT(map->inobject_properties() == 0);
3740
3741 // Initial size of the backing store to avoid resize of the storage during
3742 // bootstrapping. The size differs between the JS global object ad the
3743 // builtins object.
3744 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3745
3746 // Allocate a dictionary object for backing storage.
John Reck59135872010-11-02 12:39:01 -07003747 Object* obj;
3748 { MaybeObject* maybe_obj =
3749 StringDictionary::Allocate(
3750 map->NumberOfDescribedProperties() * 2 + initial_size);
3751 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3752 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003753 StringDictionary* dictionary = StringDictionary::cast(obj);
3754
3755 // The global object might be created from an object template with accessors.
3756 // Fill these accessors into the dictionary.
3757 DescriptorArray* descs = map->instance_descriptors();
3758 for (int i = 0; i < descs->number_of_descriptors(); i++) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01003759 PropertyDetails details(descs->GetDetails(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00003760 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3761 PropertyDetails d =
3762 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3763 Object* value = descs->GetCallbacksObject(i);
Steve Block44f0eee2011-05-26 01:26:41 +01003764 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
John Reck59135872010-11-02 12:39:01 -07003765 if (!maybe_value->ToObject(&value)) return maybe_value;
3766 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003767
John Reck59135872010-11-02 12:39:01 -07003768 Object* result;
3769 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3770 if (!maybe_result->ToObject(&result)) return maybe_result;
3771 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003772 dictionary = StringDictionary::cast(result);
3773 }
3774
3775 // Allocate the global object and initialize it with the backing store.
John Reck59135872010-11-02 12:39:01 -07003776 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3777 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3778 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003779 JSObject* global = JSObject::cast(obj);
3780 InitializeJSObjectFromMap(global, dictionary, map);
3781
3782 // Create a new map for the global object.
John Reck59135872010-11-02 12:39:01 -07003783 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3784 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3785 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003786 Map* new_map = Map::cast(obj);
3787
3788 // Setup the global object as a normalized object.
3789 global->set_map(new_map);
Ben Murdoch257744e2011-11-30 15:57:28 +00003790 global->map()->clear_instance_descriptors();
Steve Blocka7e24c12009-10-30 11:49:00 +00003791 global->set_properties(dictionary);
3792
3793 // Make sure result is a global object with properties in dictionary.
3794 ASSERT(global->IsGlobalObject());
3795 ASSERT(!global->HasFastProperties());
3796 return global;
3797}
3798
3799
John Reck59135872010-11-02 12:39:01 -07003800MaybeObject* Heap::CopyJSObject(JSObject* source) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003801 // Never used to copy functions. If functions need to be copied we
3802 // have to be careful to clear the literals array.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003803 SLOW_ASSERT(!source->IsJSFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00003804
3805 // Make the clone.
3806 Map* map = source->map();
3807 int object_size = map->instance_size();
3808 Object* clone;
3809
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003810 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
3811
Steve Blocka7e24c12009-10-30 11:49:00 +00003812 // If we're forced to always allocate, we use the general allocation
3813 // functions which may leave us with an object in old space.
3814 if (always_allocate()) {
John Reck59135872010-11-02 12:39:01 -07003815 { MaybeObject* maybe_clone =
3816 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
3817 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3818 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003819 Address clone_address = HeapObject::cast(clone)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003820 CopyBlock(clone_address,
3821 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003822 object_size);
3823 // Update write barrier for all fields that lie beyond the header.
Steve Block6ded16b2010-05-10 14:33:55 +01003824 RecordWrites(clone_address,
3825 JSObject::kHeaderSize,
3826 (object_size - JSObject::kHeaderSize) / kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003827 } else {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003828 wb_mode = SKIP_WRITE_BARRIER;
John Reck59135872010-11-02 12:39:01 -07003829 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
3830 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3831 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003832 SLOW_ASSERT(InNewSpace(clone));
Steve Blocka7e24c12009-10-30 11:49:00 +00003833 // Since we know the clone is allocated in new space, we can copy
3834 // the contents without worrying about updating the write barrier.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003835 CopyBlock(HeapObject::cast(clone)->address(),
3836 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003837 object_size);
3838 }
3839
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003840 SLOW_ASSERT(
3841 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003842 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003843 FixedArray* properties = FixedArray::cast(source->properties());
3844 // Update elements if necessary.
Steve Block6ded16b2010-05-10 14:33:55 +01003845 if (elements->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003846 Object* elem;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003847 { MaybeObject* maybe_elem;
3848 if (elements->map() == fixed_cow_array_map()) {
3849 maybe_elem = FixedArray::cast(elements);
3850 } else if (source->HasFastDoubleElements()) {
3851 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
3852 } else {
3853 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
3854 }
John Reck59135872010-11-02 12:39:01 -07003855 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
3856 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003857 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003858 }
3859 // Update properties if necessary.
3860 if (properties->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003861 Object* prop;
3862 { MaybeObject* maybe_prop = CopyFixedArray(properties);
3863 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
3864 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003865 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003866 }
3867 // Return the new clone.
3868 return clone;
3869}
3870
3871
Ben Murdoch589d6972011-11-30 16:04:58 +00003872MaybeObject* Heap::ReinitializeJSReceiver(
3873 JSReceiver* object, InstanceType type, int size) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003874 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
Ben Murdoch589d6972011-11-30 16:04:58 +00003875
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003876 // Allocate fresh map.
3877 // TODO(rossberg): Once we optimize proxies, cache these maps.
3878 Map* map;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003879 MaybeObject* maybe = AllocateMap(type, size);
3880 if (!maybe->To<Map>(&map)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003881
Ben Murdoch589d6972011-11-30 16:04:58 +00003882 // Check that the receiver has at least the size of the fresh object.
3883 int size_difference = object->map()->instance_size() - map->instance_size();
3884 ASSERT(size_difference >= 0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003885
3886 map->set_prototype(object->map()->prototype());
3887
3888 // Allocate the backing storage for the properties.
3889 int prop_size = map->unused_property_fields() - map->inobject_properties();
3890 Object* properties;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003891 maybe = AllocateFixedArray(prop_size, TENURED);
3892 if (!maybe->ToObject(&properties)) return maybe;
3893
3894 // Functions require some allocation, which might fail here.
3895 SharedFunctionInfo* shared = NULL;
3896 if (type == JS_FUNCTION_TYPE) {
3897 String* name;
3898 maybe = LookupAsciiSymbol("<freezing call trap>");
3899 if (!maybe->To<String>(&name)) return maybe;
3900 maybe = AllocateSharedFunctionInfo(name);
3901 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003902 }
3903
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003904 // Because of possible retries of this function after failure,
3905 // we must NOT fail after this point, where we have changed the type!
3906
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003907 // Reset the map for the object.
3908 object->set_map(map);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003909 JSObject* jsobj = JSObject::cast(object);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003910
3911 // Reinitialize the object from the constructor map.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003912 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
Ben Murdoch589d6972011-11-30 16:04:58 +00003913
3914 // Functions require some minimal initialization.
3915 if (type == JS_FUNCTION_TYPE) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003916 map->set_function_with_prototype(true);
3917 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
3918 JSFunction::cast(object)->set_context(
3919 isolate()->context()->global_context());
Ben Murdoch589d6972011-11-30 16:04:58 +00003920 }
3921
3922 // Put in filler if the new object is smaller than the old.
3923 if (size_difference > 0) {
3924 CreateFillerObjectAt(
3925 object->address() + map->instance_size(), size_difference);
3926 }
3927
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003928 return object;
3929}
3930
3931
John Reck59135872010-11-02 12:39:01 -07003932MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
3933 JSGlobalProxy* object) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003934 ASSERT(constructor->has_initial_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003935 Map* map = constructor->initial_map();
3936
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003937 // Check that the already allocated object has the same size and type as
Steve Blocka7e24c12009-10-30 11:49:00 +00003938 // objects allocated using the constructor.
3939 ASSERT(map->instance_size() == object->map()->instance_size());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003940 ASSERT(map->instance_type() == object->map()->instance_type());
Steve Blocka7e24c12009-10-30 11:49:00 +00003941
3942 // Allocate the backing storage for the properties.
3943 int prop_size = map->unused_property_fields() - map->inobject_properties();
John Reck59135872010-11-02 12:39:01 -07003944 Object* properties;
3945 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
3946 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3947 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003948
3949 // Reset the map for the object.
3950 object->set_map(constructor->initial_map());
3951
3952 // Reinitialize the object from the constructor map.
3953 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
3954 return object;
3955}
3956
3957
John Reck59135872010-11-02 12:39:01 -07003958MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
3959 PretenureFlag pretenure) {
Ben Murdoch589d6972011-11-30 16:04:58 +00003960 if (string.length() == 1) {
3961 return Heap::LookupSingleCharacterStringFromCode(string[0]);
3962 }
John Reck59135872010-11-02 12:39:01 -07003963 Object* result;
3964 { MaybeObject* maybe_result =
3965 AllocateRawAsciiString(string.length(), pretenure);
3966 if (!maybe_result->ToObject(&result)) return maybe_result;
3967 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003968
3969 // Copy the characters into the new object.
3970 SeqAsciiString* string_result = SeqAsciiString::cast(result);
3971 for (int i = 0; i < string.length(); i++) {
3972 string_result->SeqAsciiStringSet(i, string[i]);
3973 }
3974 return result;
3975}
3976
3977
Steve Block9fac8402011-05-12 15:51:54 +01003978MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
3979 PretenureFlag pretenure) {
Leon Clarkeac952652010-07-15 11:15:24 +01003980 // V8 only supports characters in the Basic Multilingual Plane.
3981 const uc32 kMaxSupportedChar = 0xFFFF;
Steve Blocka7e24c12009-10-30 11:49:00 +00003982 // Count the number of characters in the UTF-8 string and check if
3983 // it is an ASCII string.
Ben Murdoch8b112d22011-06-08 16:22:53 +01003984 Access<UnicodeCache::Utf8Decoder>
3985 decoder(isolate_->unicode_cache()->utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00003986 decoder->Reset(string.start(), string.length());
3987 int chars = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003988 while (decoder->has_more()) {
Steve Block9fac8402011-05-12 15:51:54 +01003989 decoder->GetNext();
Steve Blocka7e24c12009-10-30 11:49:00 +00003990 chars++;
3991 }
3992
John Reck59135872010-11-02 12:39:01 -07003993 Object* result;
3994 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
3995 if (!maybe_result->ToObject(&result)) return maybe_result;
3996 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003997
3998 // Convert and copy the characters into the new object.
3999 String* string_result = String::cast(result);
4000 decoder->Reset(string.start(), string.length());
4001 for (int i = 0; i < chars; i++) {
4002 uc32 r = decoder->GetNext();
Leon Clarkeac952652010-07-15 11:15:24 +01004003 if (r > kMaxSupportedChar) { r = unibrow::Utf8::kBadChar; }
Steve Blocka7e24c12009-10-30 11:49:00 +00004004 string_result->Set(i, r);
4005 }
4006 return result;
4007}
4008
4009
John Reck59135872010-11-02 12:39:01 -07004010MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4011 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004012 // Check if the string is an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004013 MaybeObject* maybe_result;
Steve Block9fac8402011-05-12 15:51:54 +01004014 if (String::IsAscii(string.start(), string.length())) {
John Reck59135872010-11-02 12:39:01 -07004015 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004016 } else { // It's not an ASCII string.
John Reck59135872010-11-02 12:39:01 -07004017 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00004018 }
John Reck59135872010-11-02 12:39:01 -07004019 Object* result;
4020 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004021
4022 // Copy the characters into the new object, which may be either ASCII or
4023 // UTF-16.
4024 String* string_result = String::cast(result);
4025 for (int i = 0; i < string.length(); i++) {
4026 string_result->Set(i, string[i]);
4027 }
4028 return result;
4029}
4030
4031
4032Map* Heap::SymbolMapForString(String* string) {
4033 // If the string is in new space it cannot be used as a symbol.
4034 if (InNewSpace(string)) return NULL;
4035
4036 // Find the corresponding symbol map for strings.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004037 switch (string->map()->instance_type()) {
4038 case STRING_TYPE: return symbol_map();
4039 case ASCII_STRING_TYPE: return ascii_symbol_map();
4040 case CONS_STRING_TYPE: return cons_symbol_map();
4041 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4042 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4043 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4044 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4045 return external_symbol_with_ascii_data_map();
4046 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4047 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4048 return short_external_ascii_symbol_map();
4049 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4050 return short_external_symbol_with_ascii_data_map();
4051 default: return NULL; // No match found.
Steve Block44f0eee2011-05-26 01:26:41 +01004052 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004053}
4054
4055
John Reck59135872010-11-02 12:39:01 -07004056MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4057 int chars,
4058 uint32_t hash_field) {
Leon Clarkee46be812010-01-19 14:06:41 +00004059 ASSERT(chars >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004060 // Ensure the chars matches the number of characters in the buffer.
4061 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
4062 // Determine whether the string is ascii.
4063 bool is_ascii = true;
Leon Clarkee46be812010-01-19 14:06:41 +00004064 while (buffer->has_more()) {
4065 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4066 is_ascii = false;
4067 break;
4068 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004069 }
4070 buffer->Rewind();
4071
4072 // Compute map and object size.
4073 int size;
4074 Map* map;
4075
4076 if (is_ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +00004077 if (chars > SeqAsciiString::kMaxLength) {
4078 return Failure::OutOfMemoryException();
4079 }
Steve Blockd0582a62009-12-15 09:54:21 +00004080 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004081 size = SeqAsciiString::SizeFor(chars);
4082 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00004083 if (chars > SeqTwoByteString::kMaxLength) {
4084 return Failure::OutOfMemoryException();
4085 }
Steve Blockd0582a62009-12-15 09:54:21 +00004086 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00004087 size = SeqTwoByteString::SizeFor(chars);
4088 }
4089
4090 // Allocate string.
John Reck59135872010-11-02 12:39:01 -07004091 Object* result;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004092 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4093 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
John Reck59135872010-11-02 12:39:01 -07004094 : old_data_space_->AllocateRaw(size);
4095 if (!maybe_result->ToObject(&result)) return maybe_result;
4096 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004097
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004098 reinterpret_cast<HeapObject*>(result)->set_map_unsafe(map);
Steve Blockd0582a62009-12-15 09:54:21 +00004099 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00004100 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00004101 answer->set_length(chars);
4102 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004103
4104 ASSERT_EQ(size, answer->Size());
4105
4106 // Fill in the characters.
4107 for (int i = 0; i < chars; i++) {
4108 answer->Set(i, buffer->GetNext());
4109 }
4110 return answer;
4111}
4112
4113
John Reck59135872010-11-02 12:39:01 -07004114MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004115 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4116 return Failure::OutOfMemoryException();
4117 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004118
4119 int size = SeqAsciiString::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004120 ASSERT(size <= SeqAsciiString::kMaxSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004121
Leon Clarkee46be812010-01-19 14:06:41 +00004122 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4123 AllocationSpace retry_space = OLD_DATA_SPACE;
4124
Steve Blocka7e24c12009-10-30 11:49:00 +00004125 if (space == NEW_SPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00004126 if (size > kMaxObjectSizeInNewSpace) {
4127 // Allocate in large object space, retry space will be ignored.
4128 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004129 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004130 // Allocate in new space, retry in large object space.
4131 retry_space = LO_SPACE;
4132 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004133 } else if (space == OLD_DATA_SPACE &&
4134 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004135 space = LO_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004136 }
John Reck59135872010-11-02 12:39:01 -07004137 Object* result;
4138 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4139 if (!maybe_result->ToObject(&result)) return maybe_result;
4140 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004141
Steve Blocka7e24c12009-10-30 11:49:00 +00004142 // Partially initialize the object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004143 HeapObject::cast(result)->set_map_unsafe(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004144 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004145 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004146 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4147 return result;
4148}
4149
4150
John Reck59135872010-11-02 12:39:01 -07004151MaybeObject* Heap::AllocateRawTwoByteString(int length,
4152 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004153 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4154 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00004155 }
Leon Clarkee46be812010-01-19 14:06:41 +00004156 int size = SeqTwoByteString::SizeFor(length);
4157 ASSERT(size <= SeqTwoByteString::kMaxSize);
4158 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4159 AllocationSpace retry_space = OLD_DATA_SPACE;
4160
4161 if (space == NEW_SPACE) {
4162 if (size > kMaxObjectSizeInNewSpace) {
4163 // Allocate in large object space, retry space will be ignored.
4164 space = LO_SPACE;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004165 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004166 // Allocate in new space, retry in large object space.
4167 retry_space = LO_SPACE;
4168 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004169 } else if (space == OLD_DATA_SPACE &&
4170 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004171 space = LO_SPACE;
4172 }
John Reck59135872010-11-02 12:39:01 -07004173 Object* result;
4174 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4175 if (!maybe_result->ToObject(&result)) return maybe_result;
4176 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004177
Steve Blocka7e24c12009-10-30 11:49:00 +00004178 // Partially initialize the object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004179 HeapObject::cast(result)->set_map_unsafe(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004180 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00004181 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00004182 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4183 return result;
4184}
4185
4186
John Reck59135872010-11-02 12:39:01 -07004187MaybeObject* Heap::AllocateEmptyFixedArray() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004188 int size = FixedArray::SizeFor(0);
John Reck59135872010-11-02 12:39:01 -07004189 Object* result;
4190 { MaybeObject* maybe_result =
4191 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4192 if (!maybe_result->ToObject(&result)) return maybe_result;
4193 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004194 // Initialize the object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004195 reinterpret_cast<FixedArray*>(result)->set_map_unsafe(fixed_array_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004196 reinterpret_cast<FixedArray*>(result)->set_length(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004197 return result;
4198}
4199
4200
John Reck59135872010-11-02 12:39:01 -07004201MaybeObject* Heap::AllocateRawFixedArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00004202 if (length < 0 || length > FixedArray::kMaxLength) {
4203 return Failure::OutOfMemoryException();
4204 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004205 ASSERT(length > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004206 // Use the general function if we're forced to always allocate.
4207 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4208 // Allocate the raw data for a fixed array.
4209 int size = FixedArray::SizeFor(length);
4210 return size <= kMaxObjectSizeInNewSpace
4211 ? new_space_.AllocateRaw(size)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004212 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004213}
4214
4215
John Reck59135872010-11-02 12:39:01 -07004216MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004217 int len = src->length();
John Reck59135872010-11-02 12:39:01 -07004218 Object* obj;
4219 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4220 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4221 }
Steve Block44f0eee2011-05-26 01:26:41 +01004222 if (InNewSpace(obj)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004223 HeapObject* dst = HeapObject::cast(obj);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004224 dst->set_map_unsafe(map);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004225 CopyBlock(dst->address() + kPointerSize,
4226 src->address() + kPointerSize,
4227 FixedArray::SizeFor(len) - kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004228 return obj;
4229 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004230 HeapObject::cast(obj)->set_map_unsafe(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00004231 FixedArray* result = FixedArray::cast(obj);
4232 result->set_length(len);
Leon Clarke4515c472010-02-03 11:58:03 +00004233
Steve Blocka7e24c12009-10-30 11:49:00 +00004234 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00004235 AssertNoAllocation no_gc;
4236 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00004237 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4238 return result;
4239}
4240
4241
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004242MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4243 Map* map) {
4244 int len = src->length();
4245 Object* obj;
4246 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4247 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4248 }
4249 HeapObject* dst = HeapObject::cast(obj);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004250 dst->set_map_unsafe(map);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004251 CopyBlock(
4252 dst->address() + FixedDoubleArray::kLengthOffset,
4253 src->address() + FixedDoubleArray::kLengthOffset,
4254 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4255 return obj;
4256}
4257
4258
John Reck59135872010-11-02 12:39:01 -07004259MaybeObject* Heap::AllocateFixedArray(int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004260 ASSERT(length >= 0);
4261 if (length == 0) return empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07004262 Object* result;
4263 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4264 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004265 }
John Reck59135872010-11-02 12:39:01 -07004266 // Initialize header.
4267 FixedArray* array = reinterpret_cast<FixedArray*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004268 array->set_map_unsafe(fixed_array_map());
John Reck59135872010-11-02 12:39:01 -07004269 array->set_length(length);
4270 // Initialize body.
Steve Block44f0eee2011-05-26 01:26:41 +01004271 ASSERT(!InNewSpace(undefined_value()));
John Reck59135872010-11-02 12:39:01 -07004272 MemsetPointer(array->data_start(), undefined_value(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00004273 return result;
4274}
4275
4276
John Reck59135872010-11-02 12:39:01 -07004277MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00004278 if (length < 0 || length > FixedArray::kMaxLength) {
4279 return Failure::OutOfMemoryException();
4280 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004281
Leon Clarkee46be812010-01-19 14:06:41 +00004282 AllocationSpace space =
4283 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00004284 int size = FixedArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00004285 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4286 // Too big for new space.
4287 space = LO_SPACE;
4288 } else if (space == OLD_POINTER_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004289 size > Page::kMaxNonCodeHeapObjectSize) {
Leon Clarkee46be812010-01-19 14:06:41 +00004290 // Too big for old pointer space.
4291 space = LO_SPACE;
4292 }
4293
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004294 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004295 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004296
4297 return AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00004298}
4299
4300
John Reck59135872010-11-02 12:39:01 -07004301MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
Steve Block44f0eee2011-05-26 01:26:41 +01004302 Heap* heap,
John Reck59135872010-11-02 12:39:01 -07004303 int length,
4304 PretenureFlag pretenure,
4305 Object* filler) {
Steve Block6ded16b2010-05-10 14:33:55 +01004306 ASSERT(length >= 0);
Steve Block44f0eee2011-05-26 01:26:41 +01004307 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4308 if (length == 0) return heap->empty_fixed_array();
Steve Block6ded16b2010-05-10 14:33:55 +01004309
Steve Block44f0eee2011-05-26 01:26:41 +01004310 ASSERT(!heap->InNewSpace(filler));
John Reck59135872010-11-02 12:39:01 -07004311 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004312 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004313 if (!maybe_result->ToObject(&result)) return maybe_result;
4314 }
Steve Block6ded16b2010-05-10 14:33:55 +01004315
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004316 HeapObject::cast(result)->set_map_unsafe(heap->fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004317 FixedArray* array = FixedArray::cast(result);
4318 array->set_length(length);
4319 MemsetPointer(array->data_start(), filler, length);
4320 return array;
4321}
4322
4323
John Reck59135872010-11-02 12:39:01 -07004324MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004325 return AllocateFixedArrayWithFiller(this,
4326 length,
4327 pretenure,
4328 undefined_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004329}
4330
4331
John Reck59135872010-11-02 12:39:01 -07004332MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4333 PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01004334 return AllocateFixedArrayWithFiller(this,
4335 length,
4336 pretenure,
4337 the_hole_value());
Steve Block6ded16b2010-05-10 14:33:55 +01004338}
4339
4340
John Reck59135872010-11-02 12:39:01 -07004341MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
Steve Block6ded16b2010-05-10 14:33:55 +01004342 if (length == 0) return empty_fixed_array();
4343
John Reck59135872010-11-02 12:39:01 -07004344 Object* obj;
4345 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4346 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4347 }
Steve Block6ded16b2010-05-10 14:33:55 +01004348
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004349 reinterpret_cast<FixedArray*>(obj)->set_map_unsafe(fixed_array_map());
Steve Block6ded16b2010-05-10 14:33:55 +01004350 FixedArray::cast(obj)->set_length(length);
4351 return obj;
4352}
4353
4354
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004355MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4356 int size = FixedDoubleArray::SizeFor(0);
4357 Object* result;
4358 { MaybeObject* maybe_result =
4359 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4360 if (!maybe_result->ToObject(&result)) return maybe_result;
4361 }
4362 // Initialize the object.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004363 reinterpret_cast<FixedDoubleArray*>(result)->set_map_unsafe(
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004364 fixed_double_array_map());
4365 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4366 return result;
4367}
4368
4369
4370MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4371 int length,
4372 PretenureFlag pretenure) {
4373 if (length == 0) return empty_fixed_double_array();
4374
4375 Object* obj;
4376 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4377 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4378 }
4379
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004380 reinterpret_cast<FixedDoubleArray*>(obj)->set_map_unsafe(
4381 fixed_double_array_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004382 FixedDoubleArray::cast(obj)->set_length(length);
4383 return obj;
4384}
4385
4386
4387MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4388 PretenureFlag pretenure) {
4389 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4390 return Failure::OutOfMemoryException();
4391 }
4392
4393 AllocationSpace space =
4394 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4395 int size = FixedDoubleArray::SizeFor(length);
4396 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4397 // Too big for new space.
4398 space = LO_SPACE;
4399 } else if (space == OLD_DATA_SPACE &&
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004400 size > Page::kMaxNonCodeHeapObjectSize) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004401 // Too big for old data space.
4402 space = LO_SPACE;
4403 }
4404
4405 AllocationSpace retry_space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004406 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004407
4408 return AllocateRaw(size, space, retry_space);
4409}
4410
4411
John Reck59135872010-11-02 12:39:01 -07004412MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4413 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004414 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
John Reck59135872010-11-02 12:39:01 -07004415 if (!maybe_result->ToObject(&result)) return maybe_result;
4416 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004417 reinterpret_cast<HeapObject*>(result)->set_map_unsafe(hash_table_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004418 ASSERT(result->IsHashTable());
4419 return result;
4420}
4421
4422
John Reck59135872010-11-02 12:39:01 -07004423MaybeObject* Heap::AllocateGlobalContext() {
4424 Object* result;
4425 { MaybeObject* maybe_result =
Steve Block44f0eee2011-05-26 01:26:41 +01004426 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004427 if (!maybe_result->ToObject(&result)) return maybe_result;
4428 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004429 Context* context = reinterpret_cast<Context*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004430 context->set_map_unsafe(global_context_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004431 ASSERT(context->IsGlobalContext());
4432 ASSERT(result->IsContext());
4433 return result;
4434}
4435
4436
John Reck59135872010-11-02 12:39:01 -07004437MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004438 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004439 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004440 { MaybeObject* maybe_result = AllocateFixedArray(length);
John Reck59135872010-11-02 12:39:01 -07004441 if (!maybe_result->ToObject(&result)) return maybe_result;
4442 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004443 Context* context = reinterpret_cast<Context*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004444 context->set_map_unsafe(function_context_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004445 context->set_closure(function);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004446 context->set_previous(function->context());
Steve Blocka7e24c12009-10-30 11:49:00 +00004447 context->set_extension(NULL);
4448 context->set_global(function->context()->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004449 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004450}
4451
4452
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004453MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4454 Context* previous,
4455 String* name,
4456 Object* thrown_object) {
4457 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4458 Object* result;
4459 { MaybeObject* maybe_result =
4460 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4461 if (!maybe_result->ToObject(&result)) return maybe_result;
4462 }
4463 Context* context = reinterpret_cast<Context*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004464 context->set_map_unsafe(catch_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004465 context->set_closure(function);
4466 context->set_previous(previous);
4467 context->set_extension(name);
4468 context->set_global(previous->global());
4469 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4470 return context;
4471}
4472
4473
4474MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4475 Context* previous,
4476 JSObject* extension) {
John Reck59135872010-11-02 12:39:01 -07004477 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004478 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07004479 if (!maybe_result->ToObject(&result)) return maybe_result;
4480 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004481 Context* context = reinterpret_cast<Context*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004482 context->set_map_unsafe(with_context_map());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004483 context->set_closure(function);
Steve Blocka7e24c12009-10-30 11:49:00 +00004484 context->set_previous(previous);
4485 context->set_extension(extension);
4486 context->set_global(previous->global());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004487 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +00004488}
4489
4490
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004491MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4492 Context* previous,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004493 ScopeInfo* scope_info) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004494 Object* result;
4495 { MaybeObject* maybe_result =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004496 AllocateFixedArrayWithHoles(scope_info->ContextLength());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004497 if (!maybe_result->ToObject(&result)) return maybe_result;
4498 }
4499 Context* context = reinterpret_cast<Context*>(result);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004500 context->set_map_unsafe(block_context_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004501 context->set_closure(function);
4502 context->set_previous(previous);
4503 context->set_extension(scope_info);
4504 context->set_global(previous->global());
4505 return context;
4506}
4507
4508
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004509MaybeObject* Heap::AllocateScopeInfo(int length) {
4510 FixedArray* scope_info;
4511 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4512 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4513 scope_info->set_map_unsafe(scope_info_map());
Ben Murdoch69a99ed2011-11-30 16:03:39 +00004514 return scope_info;
4515}
4516
4517
John Reck59135872010-11-02 12:39:01 -07004518MaybeObject* Heap::AllocateStruct(InstanceType type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004519 Map* map;
4520 switch (type) {
Steve Block44f0eee2011-05-26 01:26:41 +01004521#define MAKE_CASE(NAME, Name, name) \
4522 case NAME##_TYPE: map = name##_map(); break;
Steve Blocka7e24c12009-10-30 11:49:00 +00004523STRUCT_LIST(MAKE_CASE)
4524#undef MAKE_CASE
4525 default:
4526 UNREACHABLE();
4527 return Failure::InternalError();
4528 }
4529 int size = map->instance_size();
4530 AllocationSpace space =
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004531 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
John Reck59135872010-11-02 12:39:01 -07004532 Object* result;
Steve Block44f0eee2011-05-26 01:26:41 +01004533 { MaybeObject* maybe_result = Allocate(map, space);
John Reck59135872010-11-02 12:39:01 -07004534 if (!maybe_result->ToObject(&result)) return maybe_result;
4535 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004536 Struct::cast(result)->InitializeBody(size);
4537 return result;
4538}
4539
4540
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004541bool Heap::IsHeapIterable() {
4542 return (!old_pointer_space()->was_swept_conservatively() &&
4543 !old_data_space()->was_swept_conservatively());
4544}
4545
4546
4547void Heap::EnsureHeapIsIterable() {
4548 ASSERT(IsAllocationAllowed());
4549 if (!IsHeapIterable()) {
4550 CollectAllGarbage(kMakeHeapIterableMask);
4551 }
4552 ASSERT(IsHeapIterable());
4553}
4554
4555
Steve Blocka7e24c12009-10-30 11:49:00 +00004556bool Heap::IdleNotification() {
4557 static const int kIdlesBeforeScavenge = 4;
4558 static const int kIdlesBeforeMarkSweep = 7;
4559 static const int kIdlesBeforeMarkCompact = 8;
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004560 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
Ben Murdoche0cee9b2011-05-25 10:26:03 +01004561 static const unsigned int kGCsBetweenCleanup = 4;
Steve Block44f0eee2011-05-26 01:26:41 +01004562
4563 if (!last_idle_notification_gc_count_init_) {
4564 last_idle_notification_gc_count_ = gc_count_;
4565 last_idle_notification_gc_count_init_ = true;
4566 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004567
Steve Block6ded16b2010-05-10 14:33:55 +01004568 bool uncommit = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004569 bool finished = false;
4570
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004571 // Reset the number of idle notifications received when a number of
4572 // GCs have taken place. This allows another round of cleanup based
4573 // on idle notifications if enough work has been carried out to
4574 // provoke a number of garbage collections.
Steve Block44f0eee2011-05-26 01:26:41 +01004575 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4576 number_idle_notifications_ =
4577 Min(number_idle_notifications_ + 1, kMaxIdleCount);
Steve Blocka7e24c12009-10-30 11:49:00 +00004578 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01004579 number_idle_notifications_ = 0;
4580 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004581 }
4582
Steve Block44f0eee2011-05-26 01:26:41 +01004583 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
Steve Block6ded16b2010-05-10 14:33:55 +01004584 if (contexts_disposed_ > 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01004585 HistogramTimerScope scope(isolate_->counters()->gc_context());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004586 CollectAllGarbage(kNoGCFlags);
Steve Block6ded16b2010-05-10 14:33:55 +01004587 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +01004588 CollectGarbage(NEW_SPACE);
Steve Block6ded16b2010-05-10 14:33:55 +01004589 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004590 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004591 last_idle_notification_gc_count_ = gc_count_;
4592 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00004593 // Before doing the mark-sweep collections we clear the
4594 // compilation cache to avoid hanging on to source code and
4595 // generated code for cached functions.
Steve Block44f0eee2011-05-26 01:26:41 +01004596 isolate_->compilation_cache()->Clear();
Steve Blockd0582a62009-12-15 09:54:21 +00004597
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004598 CollectAllGarbage(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +00004599 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004600 last_idle_notification_gc_count_ = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004601
Steve Block44f0eee2011-05-26 01:26:41 +01004602 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004603 CollectAllGarbage(kNoGCFlags);
Steve Blocka7e24c12009-10-30 11:49:00 +00004604 new_space_.Shrink();
Steve Block44f0eee2011-05-26 01:26:41 +01004605 last_idle_notification_gc_count_ = gc_count_;
4606 number_idle_notifications_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00004607 finished = true;
Steve Block6ded16b2010-05-10 14:33:55 +01004608 } else if (contexts_disposed_ > 0) {
4609 if (FLAG_expose_gc) {
4610 contexts_disposed_ = 0;
4611 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01004612 HistogramTimerScope scope(isolate_->counters()->gc_context());
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004613 CollectAllGarbage(kNoGCFlags);
Steve Block44f0eee2011-05-26 01:26:41 +01004614 last_idle_notification_gc_count_ = gc_count_;
Steve Block6ded16b2010-05-10 14:33:55 +01004615 }
4616 // If this is the first idle notification, we reset the
4617 // notification count to avoid letting idle notifications for
4618 // context disposal garbage collections start a potentially too
4619 // aggressive idle GC cycle.
Steve Block44f0eee2011-05-26 01:26:41 +01004620 if (number_idle_notifications_ <= 1) {
4621 number_idle_notifications_ = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01004622 uncommit = false;
4623 }
Steve Block44f0eee2011-05-26 01:26:41 +01004624 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
Ben Murdochdb5a90a2011-01-06 18:27:03 +00004625 // If we have received more than kIdlesBeforeMarkCompact idle
4626 // notifications we do not perform any cleanup because we don't
4627 // expect to gain much by doing so.
4628 finished = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004629 }
4630
Steve Block6ded16b2010-05-10 14:33:55 +01004631 // Make sure that we have no pending context disposals and
4632 // conditionally uncommit from space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004633 // Take into account that we might have decided to delay full collection
4634 // because incremental marking is in progress.
4635 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
Steve Block44f0eee2011-05-26 01:26:41 +01004636 if (uncommit) UncommitFromSpace();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004637
Steve Blocka7e24c12009-10-30 11:49:00 +00004638 return finished;
4639}
4640
4641
4642#ifdef DEBUG
4643
4644void Heap::Print() {
4645 if (!HasBeenSetup()) return;
Steve Block44f0eee2011-05-26 01:26:41 +01004646 isolate()->PrintStack();
Steve Blocka7e24c12009-10-30 11:49:00 +00004647 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004648 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4649 space->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +00004650}
4651
4652
4653void Heap::ReportCodeStatistics(const char* title) {
4654 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4655 PagedSpace::ResetCodeStatistics();
4656 // We do not look for code in new space, map space, or old space. If code
4657 // somehow ends up in those spaces, we would miss it here.
4658 code_space_->CollectCodeStatistics();
4659 lo_space_->CollectCodeStatistics();
4660 PagedSpace::ReportCodeStatistics();
4661}
4662
4663
4664// This function expects that NewSpace's allocated objects histogram is
4665// populated (via a call to CollectStatistics or else as a side effect of a
4666// just-completed scavenge collection).
4667void Heap::ReportHeapStatistics(const char* title) {
4668 USE(title);
4669 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
4670 title, gc_count_);
Ben Murdochf87a2032010-10-22 12:50:53 +01004671 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
4672 old_gen_promotion_limit_);
4673 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
4674 old_gen_allocation_limit_);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004675 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004676
4677 PrintF("\n");
4678 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
Steve Block44f0eee2011-05-26 01:26:41 +01004679 isolate_->global_handles()->PrintStats();
Steve Blocka7e24c12009-10-30 11:49:00 +00004680 PrintF("\n");
4681
4682 PrintF("Heap statistics : ");
Steve Block44f0eee2011-05-26 01:26:41 +01004683 isolate_->memory_allocator()->ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00004684 PrintF("To space : ");
4685 new_space_.ReportStatistics();
4686 PrintF("Old pointer space : ");
4687 old_pointer_space_->ReportStatistics();
4688 PrintF("Old data space : ");
4689 old_data_space_->ReportStatistics();
4690 PrintF("Code space : ");
4691 code_space_->ReportStatistics();
4692 PrintF("Map space : ");
4693 map_space_->ReportStatistics();
4694 PrintF("Cell space : ");
4695 cell_space_->ReportStatistics();
4696 PrintF("Large object space : ");
4697 lo_space_->ReportStatistics();
4698 PrintF(">>>>>> ========================================= >>>>>>\n");
4699}
4700
4701#endif // DEBUG
4702
4703bool Heap::Contains(HeapObject* value) {
4704 return Contains(value->address());
4705}
4706
4707
4708bool Heap::Contains(Address addr) {
4709 if (OS::IsOutsideAllocatedSpace(addr)) return false;
4710 return HasBeenSetup() &&
4711 (new_space_.ToSpaceContains(addr) ||
4712 old_pointer_space_->Contains(addr) ||
4713 old_data_space_->Contains(addr) ||
4714 code_space_->Contains(addr) ||
4715 map_space_->Contains(addr) ||
4716 cell_space_->Contains(addr) ||
4717 lo_space_->SlowContains(addr));
4718}
4719
4720
4721bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
4722 return InSpace(value->address(), space);
4723}
4724
4725
4726bool Heap::InSpace(Address addr, AllocationSpace space) {
4727 if (OS::IsOutsideAllocatedSpace(addr)) return false;
4728 if (!HasBeenSetup()) return false;
4729
4730 switch (space) {
4731 case NEW_SPACE:
4732 return new_space_.ToSpaceContains(addr);
4733 case OLD_POINTER_SPACE:
4734 return old_pointer_space_->Contains(addr);
4735 case OLD_DATA_SPACE:
4736 return old_data_space_->Contains(addr);
4737 case CODE_SPACE:
4738 return code_space_->Contains(addr);
4739 case MAP_SPACE:
4740 return map_space_->Contains(addr);
4741 case CELL_SPACE:
4742 return cell_space_->Contains(addr);
4743 case LO_SPACE:
4744 return lo_space_->SlowContains(addr);
4745 }
4746
4747 return false;
4748}
4749
4750
4751#ifdef DEBUG
4752void Heap::Verify() {
4753 ASSERT(HasBeenSetup());
4754
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004755 store_buffer()->Verify();
4756
Steve Blocka7e24c12009-10-30 11:49:00 +00004757 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00004758 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00004759
4760 new_space_.Verify();
4761
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004762 old_pointer_space_->Verify(&visitor);
4763 map_space_->Verify(&visitor);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004764
4765 VerifyPointersVisitor no_dirty_regions_visitor;
4766 old_data_space_->Verify(&no_dirty_regions_visitor);
4767 code_space_->Verify(&no_dirty_regions_visitor);
4768 cell_space_->Verify(&no_dirty_regions_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00004769
4770 lo_space_->Verify();
4771}
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004772
Steve Blocka7e24c12009-10-30 11:49:00 +00004773#endif // DEBUG
4774
4775
John Reck59135872010-11-02 12:39:01 -07004776MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004777 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004778 Object* new_table;
4779 { MaybeObject* maybe_new_table =
4780 symbol_table()->LookupSymbol(string, &symbol);
4781 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4782 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004783 // Can't use set_symbol_table because SymbolTable::cast knows that
4784 // SymbolTable is a singleton and checks for identity.
4785 roots_[kSymbolTableRootIndex] = new_table;
4786 ASSERT(symbol != NULL);
4787 return symbol;
4788}
4789
4790
Steve Block9fac8402011-05-12 15:51:54 +01004791MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
4792 Object* symbol = NULL;
4793 Object* new_table;
4794 { MaybeObject* maybe_new_table =
4795 symbol_table()->LookupAsciiSymbol(string, &symbol);
4796 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4797 }
4798 // Can't use set_symbol_table because SymbolTable::cast knows that
4799 // SymbolTable is a singleton and checks for identity.
4800 roots_[kSymbolTableRootIndex] = new_table;
4801 ASSERT(symbol != NULL);
4802 return symbol;
4803}
4804
4805
Ben Murdoch257744e2011-11-30 15:57:28 +00004806MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
4807 int from,
4808 int length) {
4809 Object* symbol = NULL;
4810 Object* new_table;
4811 { MaybeObject* maybe_new_table =
4812 symbol_table()->LookupSubStringAsciiSymbol(string,
4813 from,
4814 length,
4815 &symbol);
4816 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4817 }
4818 // Can't use set_symbol_table because SymbolTable::cast knows that
4819 // SymbolTable is a singleton and checks for identity.
4820 roots_[kSymbolTableRootIndex] = new_table;
4821 ASSERT(symbol != NULL);
4822 return symbol;
4823}
4824
4825
Steve Block9fac8402011-05-12 15:51:54 +01004826MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
4827 Object* symbol = NULL;
4828 Object* new_table;
4829 { MaybeObject* maybe_new_table =
4830 symbol_table()->LookupTwoByteSymbol(string, &symbol);
4831 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4832 }
4833 // Can't use set_symbol_table because SymbolTable::cast knows that
4834 // SymbolTable is a singleton and checks for identity.
4835 roots_[kSymbolTableRootIndex] = new_table;
4836 ASSERT(symbol != NULL);
4837 return symbol;
4838}
4839
4840
John Reck59135872010-11-02 12:39:01 -07004841MaybeObject* Heap::LookupSymbol(String* string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004842 if (string->IsSymbol()) return string;
4843 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004844 Object* new_table;
4845 { MaybeObject* maybe_new_table =
4846 symbol_table()->LookupString(string, &symbol);
4847 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4848 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004849 // Can't use set_symbol_table because SymbolTable::cast knows that
4850 // SymbolTable is a singleton and checks for identity.
4851 roots_[kSymbolTableRootIndex] = new_table;
4852 ASSERT(symbol != NULL);
4853 return symbol;
4854}
4855
4856
4857bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
4858 if (string->IsSymbol()) {
4859 *symbol = string;
4860 return true;
4861 }
4862 return symbol_table()->LookupSymbolIfExists(string, symbol);
4863}
4864
4865
4866#ifdef DEBUG
4867void Heap::ZapFromSpace() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004868 NewSpacePageIterator it(new_space_.FromSpaceStart(),
4869 new_space_.FromSpaceEnd());
4870 while (it.has_next()) {
4871 NewSpacePage* page = it.next();
4872 for (Address cursor = page->area_start(), limit = page->area_end();
4873 cursor < limit;
4874 cursor += kPointerSize) {
4875 Memory::Address_at(cursor) = kFromSpaceZapValue;
4876 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004877 }
4878}
4879#endif // DEBUG
4880
4881
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004882void Heap::IterateAndMarkPointersToFromSpace(Address start,
4883 Address end,
4884 ObjectSlotCallback callback) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004885 Address slot_address = start;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004886
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004887 // We are not collecting slots on new space objects during mutation
4888 // thus we have to scan for pointers to evacuation candidates when we
4889 // promote objects. But we should not record any slots in non-black
4890 // objects. Grey object's slots would be rescanned.
4891 // White object might not survive until the end of collection
4892 // it would be a violation of the invariant to record it's slots.
4893 bool record_slots = false;
4894 if (incremental_marking()->IsCompacting()) {
4895 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
4896 record_slots = Marking::IsBlack(mark_bit);
4897 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004898
4899 while (slot_address < end) {
4900 Object** slot = reinterpret_cast<Object**>(slot_address);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004901 Object* object = *slot;
4902 // If the store buffer becomes overfull we mark pages as being exempt from
4903 // the store buffer. These pages are scanned to find pointers that point
4904 // to the new space. In that case we may hit newly promoted objects and
4905 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
4906 if (object->IsHeapObject()) {
4907 if (Heap::InFromSpace(object)) {
4908 callback(reinterpret_cast<HeapObject**>(slot),
4909 HeapObject::cast(object));
4910 Object* new_object = *slot;
4911 if (InNewSpace(new_object)) {
4912 SLOW_ASSERT(Heap::InToSpace(new_object));
4913 SLOW_ASSERT(new_object->IsHeapObject());
4914 store_buffer_.EnterDirectlyIntoStoreBuffer(
4915 reinterpret_cast<Address>(slot));
4916 }
4917 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
4918 } else if (record_slots &&
4919 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
4920 mark_compact_collector()->RecordSlot(slot, slot, object);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004921 }
4922 }
4923 slot_address += kPointerSize;
4924 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004925}
4926
4927
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004928#ifdef DEBUG
4929typedef bool (*CheckStoreBufferFilter)(Object** addr);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004930
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004931
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004932bool IsAMapPointerAddress(Object** addr) {
4933 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
4934 int mod = a % Map::kSize;
4935 return mod >= Map::kPointerFieldsBeginOffset &&
4936 mod < Map::kPointerFieldsEndOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004937}
4938
4939
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004940bool EverythingsAPointer(Object** addr) {
4941 return true;
4942}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004943
Steve Blocka7e24c12009-10-30 11:49:00 +00004944
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004945static void CheckStoreBuffer(Heap* heap,
4946 Object** current,
4947 Object** limit,
4948 Object**** store_buffer_position,
4949 Object*** store_buffer_top,
4950 CheckStoreBufferFilter filter,
4951 Address special_garbage_start,
4952 Address special_garbage_end) {
4953 Map* free_space_map = heap->free_space_map();
4954 for ( ; current < limit; current++) {
4955 Object* o = *current;
4956 Address current_address = reinterpret_cast<Address>(current);
4957 // Skip free space.
4958 if (o == free_space_map) {
4959 Address current_address = reinterpret_cast<Address>(current);
4960 FreeSpace* free_space =
4961 FreeSpace::cast(HeapObject::FromAddress(current_address));
4962 int skip = free_space->Size();
4963 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
4964 ASSERT(skip > 0);
4965 current_address += skip - kPointerSize;
4966 current = reinterpret_cast<Object**>(current_address);
4967 continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00004968 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00004969 // Skip the current linear allocation space between top and limit which is
4970 // unmarked with the free space map, but can contain junk.
4971 if (current_address == special_garbage_start &&
4972 special_garbage_end != special_garbage_start) {
4973 current_address = special_garbage_end - kPointerSize;
4974 current = reinterpret_cast<Object**>(current_address);
4975 continue;
4976 }
4977 if (!(*filter)(current)) continue;
4978 ASSERT(current_address < special_garbage_start ||
4979 current_address >= special_garbage_end);
4980 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
4981 // We have to check that the pointer does not point into new space
4982 // without trying to cast it to a heap object since the hash field of
4983 // a string can contain values like 1 and 3 which are tagged null
4984 // pointers.
4985 if (!heap->InNewSpace(o)) continue;
4986 while (**store_buffer_position < current &&
4987 *store_buffer_position < store_buffer_top) {
4988 (*store_buffer_position)++;
4989 }
4990 if (**store_buffer_position != current ||
4991 *store_buffer_position == store_buffer_top) {
4992 Object** obj_start = current;
4993 while (!(*obj_start)->IsMap()) obj_start--;
4994 UNREACHABLE();
4995 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004996 }
4997}
4998
4999
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005000// Check that the store buffer contains all intergenerational pointers by
5001// scanning a page and ensuring that all pointers to young space are in the
5002// store buffer.
5003void Heap::OldPointerSpaceCheckStoreBuffer() {
5004 OldSpace* space = old_pointer_space();
5005 PageIterator pages(space);
5006
5007 store_buffer()->SortUniq();
5008
5009 while (pages.has_next()) {
5010 Page* page = pages.next();
5011 Object** current = reinterpret_cast<Object**>(page->area_start());
5012
5013 Address end = page->area_end();
5014
5015 Object*** store_buffer_position = store_buffer()->Start();
5016 Object*** store_buffer_top = store_buffer()->Top();
5017
5018 Object** limit = reinterpret_cast<Object**>(end);
5019 CheckStoreBuffer(this,
5020 current,
5021 limit,
5022 &store_buffer_position,
5023 store_buffer_top,
5024 &EverythingsAPointer,
5025 space->top(),
5026 space->limit());
5027 }
5028}
5029
5030
5031void Heap::MapSpaceCheckStoreBuffer() {
5032 MapSpace* space = map_space();
5033 PageIterator pages(space);
5034
5035 store_buffer()->SortUniq();
5036
5037 while (pages.has_next()) {
5038 Page* page = pages.next();
5039 Object** current = reinterpret_cast<Object**>(page->area_start());
5040
5041 Address end = page->area_end();
5042
5043 Object*** store_buffer_position = store_buffer()->Start();
5044 Object*** store_buffer_top = store_buffer()->Top();
5045
5046 Object** limit = reinterpret_cast<Object**>(end);
5047 CheckStoreBuffer(this,
5048 current,
5049 limit,
5050 &store_buffer_position,
5051 store_buffer_top,
5052 &IsAMapPointerAddress,
5053 space->top(),
5054 space->limit());
5055 }
5056}
5057
5058
5059void Heap::LargeObjectSpaceCheckStoreBuffer() {
5060 LargeObjectIterator it(lo_space());
5061 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5062 // We only have code, sequential strings, or fixed arrays in large
5063 // object space, and only fixed arrays can possibly contain pointers to
5064 // the young generation.
5065 if (object->IsFixedArray()) {
5066 Object*** store_buffer_position = store_buffer()->Start();
5067 Object*** store_buffer_top = store_buffer()->Top();
5068 Object** current = reinterpret_cast<Object**>(object->address());
5069 Object** limit =
5070 reinterpret_cast<Object**>(object->address() + object->Size());
5071 CheckStoreBuffer(this,
5072 current,
5073 limit,
5074 &store_buffer_position,
5075 store_buffer_top,
5076 &EverythingsAPointer,
5077 NULL,
5078 NULL);
5079 }
5080 }
5081}
5082#endif
5083
5084
Steve Blockd0582a62009-12-15 09:54:21 +00005085void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5086 IterateStrongRoots(v, mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00005087 IterateWeakRoots(v, mode);
5088}
5089
5090
5091void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005092 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Steve Blockd0582a62009-12-15 09:54:21 +00005093 v->Synchronize("symbol_table");
Ben Murdoch257744e2011-11-30 15:57:28 +00005094 if (mode != VISIT_ALL_IN_SCAVENGE &&
5095 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00005096 // Scavenge collections have special processing for this.
Steve Block44f0eee2011-05-26 01:26:41 +01005097 external_string_table_.Iterate(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005098 }
5099 v->Synchronize("external_string_table");
Steve Blocka7e24c12009-10-30 11:49:00 +00005100}
5101
5102
Steve Blockd0582a62009-12-15 09:54:21 +00005103void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005104 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Steve Blockd0582a62009-12-15 09:54:21 +00005105 v->Synchronize("strong_root_list");
Steve Blocka7e24c12009-10-30 11:49:00 +00005106
Iain Merrick75681382010-08-19 15:07:18 +01005107 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
Steve Blockd0582a62009-12-15 09:54:21 +00005108 v->Synchronize("symbol");
Steve Blocka7e24c12009-10-30 11:49:00 +00005109
Steve Block44f0eee2011-05-26 01:26:41 +01005110 isolate_->bootstrapper()->Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005111 v->Synchronize("bootstrapper");
Steve Block44f0eee2011-05-26 01:26:41 +01005112 isolate_->Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005113 v->Synchronize("top");
Steve Blocka7e24c12009-10-30 11:49:00 +00005114 Relocatable::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005115 v->Synchronize("relocatable");
Steve Blocka7e24c12009-10-30 11:49:00 +00005116
5117#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +01005118 isolate_->debug()->Iterate(v);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005119 if (isolate_->deoptimizer_data() != NULL) {
5120 isolate_->deoptimizer_data()->Iterate(v);
5121 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005122#endif
Steve Blockd0582a62009-12-15 09:54:21 +00005123 v->Synchronize("debug");
Steve Block44f0eee2011-05-26 01:26:41 +01005124 isolate_->compilation_cache()->Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005125 v->Synchronize("compilationcache");
Steve Blocka7e24c12009-10-30 11:49:00 +00005126
5127 // Iterate over local handles in handle scopes.
Steve Block44f0eee2011-05-26 01:26:41 +01005128 isolate_->handle_scope_implementer()->Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005129 v->Synchronize("handlescope");
Steve Blocka7e24c12009-10-30 11:49:00 +00005130
Leon Clarkee46be812010-01-19 14:06:41 +00005131 // Iterate over the builtin code objects and code stubs in the
5132 // heap. Note that it is not necessary to iterate over code objects
5133 // on scavenge collections.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005134 if (mode != VISIT_ALL_IN_SCAVENGE) {
Steve Block44f0eee2011-05-26 01:26:41 +01005135 isolate_->builtins()->IterateBuiltins(v);
Leon Clarkee46be812010-01-19 14:06:41 +00005136 }
Steve Blockd0582a62009-12-15 09:54:21 +00005137 v->Synchronize("builtins");
Steve Blocka7e24c12009-10-30 11:49:00 +00005138
5139 // Iterate over global handles.
Ben Murdoch257744e2011-11-30 15:57:28 +00005140 switch (mode) {
5141 case VISIT_ONLY_STRONG:
5142 isolate_->global_handles()->IterateStrongRoots(v);
5143 break;
5144 case VISIT_ALL_IN_SCAVENGE:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00005145 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
Ben Murdoch257744e2011-11-30 15:57:28 +00005146 break;
5147 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5148 case VISIT_ALL:
5149 isolate_->global_handles()->IterateAllRoots(v);
5150 break;
Steve Blockd0582a62009-12-15 09:54:21 +00005151 }
5152 v->Synchronize("globalhandles");
Steve Blocka7e24c12009-10-30 11:49:00 +00005153
5154 // Iterate over pointers being held by inactive threads.
Steve Block44f0eee2011-05-26 01:26:41 +01005155 isolate_->thread_manager()->Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00005156 v->Synchronize("threadmanager");
Leon Clarked91b9f72010-01-27 17:25:45 +00005157
5158 // Iterate over the pointers the Serialization/Deserialization code is
5159 // holding.
5160 // During garbage collection this keeps the partial snapshot cache alive.
5161 // During deserialization of the startup snapshot this creates the partial
5162 // snapshot cache and deserializes the objects it refers to. During
5163 // serialization this does nothing, since the partial snapshot cache is
5164 // empty. However the next thing we do is create the partial snapshot,
5165 // filling up the partial snapshot cache with objects it needs as we go.
5166 SerializerDeserializer::Iterate(v);
5167 // We don't do a v->Synchronize call here, because in debug mode that will
5168 // output a flag to the snapshot. However at this point the serializer and
5169 // deserializer are deliberately a little unsynchronized (see above) so the
5170 // checking of the sync flag in the snapshot would fail.
Steve Blocka7e24c12009-10-30 11:49:00 +00005171}
Steve Blocka7e24c12009-10-30 11:49:00 +00005172
5173
Steve Blocka7e24c12009-10-30 11:49:00 +00005174// TODO(1236194): Since the heap size is configurable on the command line
5175// and through the API, we should gracefully handle the case that the heap
5176// size is not big enough to fit all the initial objects.
Russell Brenner90bac252010-11-18 13:33:46 -08005177bool Heap::ConfigureHeap(int max_semispace_size,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005178 intptr_t max_old_gen_size,
5179 intptr_t max_executable_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005180 if (HasBeenSetup()) return false;
5181
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005182 if (max_semispace_size > 0) {
5183 if (max_semispace_size < Page::kPageSize) {
5184 max_semispace_size = Page::kPageSize;
5185 if (FLAG_trace_gc) {
5186 PrintF("Max semispace size cannot be less than %dkbytes\n",
5187 Page::kPageSize >> 10);
5188 }
5189 }
5190 max_semispace_size_ = max_semispace_size;
5191 }
Steve Block3ce2e202009-11-05 08:53:23 +00005192
5193 if (Snapshot::IsEnabled()) {
5194 // If we are using a snapshot we always reserve the default amount
5195 // of memory for each semispace because code in the snapshot has
5196 // write-barrier code that relies on the size and alignment of new
5197 // space. We therefore cannot use a larger max semispace size
5198 // than the default reserved semispace size.
5199 if (max_semispace_size_ > reserved_semispace_size_) {
5200 max_semispace_size_ = reserved_semispace_size_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005201 if (FLAG_trace_gc) {
5202 PrintF("Max semispace size cannot be more than %dkbytes\n",
5203 reserved_semispace_size_ >> 10);
5204 }
Steve Block3ce2e202009-11-05 08:53:23 +00005205 }
5206 } else {
5207 // If we are not using snapshots we reserve space for the actual
5208 // max semispace size.
5209 reserved_semispace_size_ = max_semispace_size_;
5210 }
5211
5212 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Russell Brenner90bac252010-11-18 13:33:46 -08005213 if (max_executable_size > 0) {
5214 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5215 }
5216
5217 // The max executable size must be less than or equal to the max old
5218 // generation size.
5219 if (max_executable_size_ > max_old_generation_size_) {
5220 max_executable_size_ = max_old_generation_size_;
5221 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005222
5223 // The new space size must be a power of two to support single-bit testing
5224 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00005225 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5226 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5227 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5228 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00005229
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005230 // The old generation is paged and needs at least one page for each space.
5231 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5232 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5233 Page::kPageSize),
5234 RoundUp(max_old_generation_size_,
5235 Page::kPageSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00005236
Steve Block44f0eee2011-05-26 01:26:41 +01005237 configured_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00005238 return true;
5239}
5240
5241
5242bool Heap::ConfigureHeapDefault() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005243 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5244 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5245 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
Steve Blocka7e24c12009-10-30 11:49:00 +00005246}
5247
5248
Ben Murdochbb769b22010-08-11 14:56:33 +01005249void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
Iain Merrick75681382010-08-19 15:07:18 +01005250 *stats->start_marker = HeapStats::kStartMarker;
5251 *stats->end_marker = HeapStats::kEndMarker;
Ben Murdochf87a2032010-10-22 12:50:53 +01005252 *stats->new_space_size = new_space_.SizeAsInt();
5253 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
Steve Blockd0582a62009-12-15 09:54:21 +00005254 *stats->old_pointer_space_size = old_pointer_space_->Size();
5255 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5256 *stats->old_data_space_size = old_data_space_->Size();
5257 *stats->old_data_space_capacity = old_data_space_->Capacity();
5258 *stats->code_space_size = code_space_->Size();
5259 *stats->code_space_capacity = code_space_->Capacity();
5260 *stats->map_space_size = map_space_->Size();
5261 *stats->map_space_capacity = map_space_->Capacity();
5262 *stats->cell_space_size = cell_space_->Size();
5263 *stats->cell_space_capacity = cell_space_->Capacity();
5264 *stats->lo_space_size = lo_space_->Size();
Steve Block44f0eee2011-05-26 01:26:41 +01005265 isolate_->global_handles()->RecordStats(stats);
5266 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
Ben Murdochbb769b22010-08-11 14:56:33 +01005267 *stats->memory_allocator_capacity =
Steve Block44f0eee2011-05-26 01:26:41 +01005268 isolate()->memory_allocator()->Size() +
5269 isolate()->memory_allocator()->Available();
Iain Merrick75681382010-08-19 15:07:18 +01005270 *stats->os_error = OS::GetLastError();
Steve Block44f0eee2011-05-26 01:26:41 +01005271 isolate()->memory_allocator()->Available();
Ben Murdochbb769b22010-08-11 14:56:33 +01005272 if (take_snapshot) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005273 HeapIterator iterator;
Ben Murdochbb769b22010-08-11 14:56:33 +01005274 for (HeapObject* obj = iterator.next();
5275 obj != NULL;
5276 obj = iterator.next()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005277 InstanceType type = obj->map()->instance_type();
5278 ASSERT(0 <= type && type <= LAST_TYPE);
5279 stats->objects_per_type[type]++;
5280 stats->size_per_type[type] += obj->Size();
5281 }
5282 }
Steve Blockd0582a62009-12-15 09:54:21 +00005283}
5284
5285
Ben Murdochf87a2032010-10-22 12:50:53 +01005286intptr_t Heap::PromotedSpaceSize() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005287 return old_pointer_space_->Size()
5288 + old_data_space_->Size()
5289 + code_space_->Size()
5290 + map_space_->Size()
5291 + cell_space_->Size()
5292 + lo_space_->Size();
5293}
5294
5295
5296int Heap::PromotedExternalMemorySize() {
5297 if (amount_of_external_allocated_memory_
5298 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5299 return amount_of_external_allocated_memory_
5300 - amount_of_external_allocated_memory_at_last_global_gc_;
5301}
5302
Steve Block44f0eee2011-05-26 01:26:41 +01005303#ifdef DEBUG
5304
5305// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5306static const int kMarkTag = 2;
5307
5308
5309class HeapDebugUtils {
5310 public:
5311 explicit HeapDebugUtils(Heap* heap)
5312 : search_for_any_global_(false),
5313 search_target_(NULL),
5314 found_target_(false),
5315 object_stack_(20),
5316 heap_(heap) {
5317 }
5318
5319 class MarkObjectVisitor : public ObjectVisitor {
5320 public:
5321 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5322
5323 void VisitPointers(Object** start, Object** end) {
5324 // Copy all HeapObject pointers in [start, end)
5325 for (Object** p = start; p < end; p++) {
5326 if ((*p)->IsHeapObject())
5327 utils_->MarkObjectRecursively(p);
5328 }
5329 }
5330
5331 HeapDebugUtils* utils_;
5332 };
5333
5334 void MarkObjectRecursively(Object** p) {
5335 if (!(*p)->IsHeapObject()) return;
5336
5337 HeapObject* obj = HeapObject::cast(*p);
5338
5339 Object* map = obj->map();
5340
5341 if (!map->IsHeapObject()) return; // visited before
5342
5343 if (found_target_) return; // stop if target found
5344 object_stack_.Add(obj);
5345 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5346 (!search_for_any_global_ && (obj == search_target_))) {
5347 found_target_ = true;
5348 return;
5349 }
5350
5351 // not visited yet
5352 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5353
5354 Address map_addr = map_p->address();
5355
5356 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
5357
5358 MarkObjectRecursively(&map);
5359
5360 MarkObjectVisitor mark_visitor(this);
5361
5362 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5363 &mark_visitor);
5364
5365 if (!found_target_) // don't pop if found the target
5366 object_stack_.RemoveLast();
5367 }
5368
5369
5370 class UnmarkObjectVisitor : public ObjectVisitor {
5371 public:
5372 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5373
5374 void VisitPointers(Object** start, Object** end) {
5375 // Copy all HeapObject pointers in [start, end)
5376 for (Object** p = start; p < end; p++) {
5377 if ((*p)->IsHeapObject())
5378 utils_->UnmarkObjectRecursively(p);
5379 }
5380 }
5381
5382 HeapDebugUtils* utils_;
5383 };
5384
5385
5386 void UnmarkObjectRecursively(Object** p) {
5387 if (!(*p)->IsHeapObject()) return;
5388
5389 HeapObject* obj = HeapObject::cast(*p);
5390
5391 Object* map = obj->map();
5392
5393 if (map->IsHeapObject()) return; // unmarked already
5394
5395 Address map_addr = reinterpret_cast<Address>(map);
5396
5397 map_addr -= kMarkTag;
5398
5399 ASSERT_TAG_ALIGNED(map_addr);
5400
5401 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5402
5403 obj->set_map(reinterpret_cast<Map*>(map_p));
5404
5405 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5406
5407 UnmarkObjectVisitor unmark_visitor(this);
5408
5409 obj->IterateBody(Map::cast(map_p)->instance_type(),
5410 obj->SizeFromMap(Map::cast(map_p)),
5411 &unmark_visitor);
5412 }
5413
5414
5415 void MarkRootObjectRecursively(Object** root) {
5416 if (search_for_any_global_) {
5417 ASSERT(search_target_ == NULL);
5418 } else {
5419 ASSERT(search_target_->IsHeapObject());
5420 }
5421 found_target_ = false;
5422 object_stack_.Clear();
5423
5424 MarkObjectRecursively(root);
5425 UnmarkObjectRecursively(root);
5426
5427 if (found_target_) {
5428 PrintF("=====================================\n");
5429 PrintF("==== Path to object ====\n");
5430 PrintF("=====================================\n\n");
5431
5432 ASSERT(!object_stack_.is_empty());
5433 for (int i = 0; i < object_stack_.length(); i++) {
5434 if (i > 0) PrintF("\n |\n |\n V\n\n");
5435 Object* obj = object_stack_[i];
5436 obj->Print();
5437 }
5438 PrintF("=====================================\n");
5439 }
5440 }
5441
5442 // Helper class for visiting HeapObjects recursively.
5443 class MarkRootVisitor: public ObjectVisitor {
5444 public:
5445 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5446
5447 void VisitPointers(Object** start, Object** end) {
5448 // Visit all HeapObject pointers in [start, end)
5449 for (Object** p = start; p < end; p++) {
5450 if ((*p)->IsHeapObject())
5451 utils_->MarkRootObjectRecursively(p);
5452 }
5453 }
5454
5455 HeapDebugUtils* utils_;
5456 };
5457
5458 bool search_for_any_global_;
5459 Object* search_target_;
5460 bool found_target_;
5461 List<Object*> object_stack_;
5462 Heap* heap_;
5463
5464 friend class Heap;
5465};
5466
5467#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005468
5469bool Heap::Setup(bool create_heap_objects) {
Steve Block44f0eee2011-05-26 01:26:41 +01005470#ifdef DEBUG
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005471 allocation_timeout_ = FLAG_gc_interval;
Steve Block44f0eee2011-05-26 01:26:41 +01005472 debug_utils_ = new HeapDebugUtils(this);
5473#endif
5474
Steve Blocka7e24c12009-10-30 11:49:00 +00005475 // Initialize heap spaces and initial maps and objects. Whenever something
5476 // goes wrong, just return false. The caller should check the results and
5477 // call Heap::TearDown() to release allocated memory.
5478 //
5479 // If the heap is not yet configured (eg, through the API), configure it.
5480 // Configuration is based on the flags new-space-size (really the semispace
5481 // size) and old-space-size if set or the initial values of semispace_size_
5482 // and old_generation_size_ otherwise.
Steve Block44f0eee2011-05-26 01:26:41 +01005483 if (!configured_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005484 if (!ConfigureHeapDefault()) return false;
5485 }
5486
Steve Block44f0eee2011-05-26 01:26:41 +01005487 gc_initializer_mutex->Lock();
5488 static bool initialized_gc = false;
5489 if (!initialized_gc) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005490 initialized_gc = true;
5491 InitializeScavengingVisitorsTables();
5492 NewSpaceScavenger::Initialize();
5493 MarkCompactCollector::Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01005494 }
5495 gc_initializer_mutex->Unlock();
Iain Merrick75681382010-08-19 15:07:18 +01005496
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005497 MarkMapPointersAsEncoded(false);
5498
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005499 // Setup memory allocator.
Steve Block44f0eee2011-05-26 01:26:41 +01005500 if (!isolate_->memory_allocator()->Setup(MaxReserved(), MaxExecutableSize()))
5501 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005502
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005503 // Setup new space.
5504 if (!new_space_.Setup(reserved_semispace_size_, max_semispace_size_)) {
Steve Block3ce2e202009-11-05 08:53:23 +00005505 return false;
5506 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005507
5508 // Initialize old pointer space.
5509 old_pointer_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005510 new OldSpace(this,
5511 max_old_generation_size_,
5512 OLD_POINTER_SPACE,
5513 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005514 if (old_pointer_space_ == NULL) return false;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005515 if (!old_pointer_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005516
5517 // Initialize old data space.
5518 old_data_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005519 new OldSpace(this,
5520 max_old_generation_size_,
5521 OLD_DATA_SPACE,
5522 NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005523 if (old_data_space_ == NULL) return false;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005524 if (!old_data_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005525
5526 // Initialize the code space, set its maximum capacity to the old
5527 // generation size. It needs executable memory.
5528 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5529 // virtual address space, so that they can call each other with near calls.
5530 if (code_range_size_ > 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01005531 if (!isolate_->code_range()->Setup(code_range_size_)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005532 return false;
5533 }
5534 }
5535
5536 code_space_ =
Steve Block44f0eee2011-05-26 01:26:41 +01005537 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005538 if (code_space_ == NULL) return false;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005539 if (!code_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005540
5541 // Initialize map space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005542 map_space_ = new MapSpace(this,
5543 max_old_generation_size_,
5544 FLAG_max_map_space_pages,
5545 MAP_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005546 if (map_space_ == NULL) return false;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005547 if (!map_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005548
5549 // Initialize global property cell space.
Steve Block44f0eee2011-05-26 01:26:41 +01005550 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005551 if (cell_space_ == NULL) return false;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005552 if (!cell_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005553
5554 // The large object code space may contain code or data. We set the memory
5555 // to be non-executable here for safety, but this means we need to enable it
5556 // explicitly when allocating large code objects.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005557 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005558 if (lo_space_ == NULL) return false;
5559 if (!lo_space_->Setup()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00005560 if (create_heap_objects) {
5561 // Create initial maps.
5562 if (!CreateInitialMaps()) return false;
5563 if (!CreateApiObjects()) return false;
5564
5565 // Create initial objects
5566 if (!CreateInitialObjects()) return false;
Ben Murdochf87a2032010-10-22 12:50:53 +01005567
5568 global_contexts_list_ = undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005569 }
5570
Steve Block44f0eee2011-05-26 01:26:41 +01005571 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5572 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005573
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005574 store_buffer()->Setup();
5575
Steve Blocka7e24c12009-10-30 11:49:00 +00005576 return true;
5577}
5578
5579
Steve Blockd0582a62009-12-15 09:54:21 +00005580void Heap::SetStackLimits() {
Steve Block44f0eee2011-05-26 01:26:41 +01005581 ASSERT(isolate_ != NULL);
5582 ASSERT(isolate_ == isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00005583 // On 64 bit machines, pointers are generally out of range of Smis. We write
5584 // something that looks like an out of range Smi to the GC.
5585
Steve Blockd0582a62009-12-15 09:54:21 +00005586 // Set up the special root array entries containing the stack limits.
5587 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00005588 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00005589 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005590 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blockd0582a62009-12-15 09:54:21 +00005591 roots_[kRealStackLimitRootIndex] =
5592 reinterpret_cast<Object*>(
Steve Block44f0eee2011-05-26 01:26:41 +01005593 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00005594}
5595
5596
5597void Heap::TearDown() {
Leon Clarkef7060e22010-06-03 12:02:55 +01005598 if (FLAG_print_cumulative_gc_stat) {
5599 PrintF("\n\n");
5600 PrintF("gc_count=%d ", gc_count_);
5601 PrintF("mark_sweep_count=%d ", ms_count_);
Steve Block44f0eee2011-05-26 01:26:41 +01005602 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5603 PrintF("min_in_mutator=%d ", get_min_in_mutator());
Ben Murdochf87a2032010-10-22 12:50:53 +01005604 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
Steve Block44f0eee2011-05-26 01:26:41 +01005605 get_max_alive_after_gc());
Leon Clarkef7060e22010-06-03 12:02:55 +01005606 PrintF("\n\n");
5607 }
5608
Steve Block44f0eee2011-05-26 01:26:41 +01005609 isolate_->global_handles()->TearDown();
Steve Blocka7e24c12009-10-30 11:49:00 +00005610
Steve Block44f0eee2011-05-26 01:26:41 +01005611 external_string_table_.TearDown();
Leon Clarkee46be812010-01-19 14:06:41 +00005612
Steve Blocka7e24c12009-10-30 11:49:00 +00005613 new_space_.TearDown();
5614
5615 if (old_pointer_space_ != NULL) {
5616 old_pointer_space_->TearDown();
5617 delete old_pointer_space_;
5618 old_pointer_space_ = NULL;
5619 }
5620
5621 if (old_data_space_ != NULL) {
5622 old_data_space_->TearDown();
5623 delete old_data_space_;
5624 old_data_space_ = NULL;
5625 }
5626
5627 if (code_space_ != NULL) {
5628 code_space_->TearDown();
5629 delete code_space_;
5630 code_space_ = NULL;
5631 }
5632
5633 if (map_space_ != NULL) {
5634 map_space_->TearDown();
5635 delete map_space_;
5636 map_space_ = NULL;
5637 }
5638
5639 if (cell_space_ != NULL) {
5640 cell_space_->TearDown();
5641 delete cell_space_;
5642 cell_space_ = NULL;
5643 }
5644
5645 if (lo_space_ != NULL) {
5646 lo_space_->TearDown();
5647 delete lo_space_;
5648 lo_space_ = NULL;
5649 }
5650
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005651 store_buffer()->TearDown();
5652 incremental_marking()->TearDown();
5653
Steve Block44f0eee2011-05-26 01:26:41 +01005654 isolate_->memory_allocator()->TearDown();
5655
5656#ifdef DEBUG
5657 delete debug_utils_;
5658 debug_utils_ = NULL;
5659#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005660}
5661
5662
5663void Heap::Shrink() {
5664 // Try to shrink all paged spaces.
5665 PagedSpaces spaces;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005666 for (PagedSpace* space = spaces.next();
5667 space != NULL;
5668 space = spaces.next()) {
5669 space->ReleaseAllUnusedPages();
5670 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005671}
5672
5673
Steve Block6ded16b2010-05-10 14:33:55 +01005674void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5675 ASSERT(callback != NULL);
5676 GCPrologueCallbackPair pair(callback, gc_type);
5677 ASSERT(!gc_prologue_callbacks_.Contains(pair));
5678 return gc_prologue_callbacks_.Add(pair);
5679}
5680
5681
5682void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5683 ASSERT(callback != NULL);
5684 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
5685 if (gc_prologue_callbacks_[i].callback == callback) {
5686 gc_prologue_callbacks_.Remove(i);
5687 return;
5688 }
5689 }
5690 UNREACHABLE();
5691}
5692
5693
5694void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5695 ASSERT(callback != NULL);
5696 GCEpilogueCallbackPair pair(callback, gc_type);
5697 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
5698 return gc_epilogue_callbacks_.Add(pair);
5699}
5700
5701
5702void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5703 ASSERT(callback != NULL);
5704 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
5705 if (gc_epilogue_callbacks_[i].callback == callback) {
5706 gc_epilogue_callbacks_.Remove(i);
5707 return;
5708 }
5709 }
5710 UNREACHABLE();
5711}
5712
5713
Steve Blocka7e24c12009-10-30 11:49:00 +00005714#ifdef DEBUG
5715
5716class PrintHandleVisitor: public ObjectVisitor {
5717 public:
5718 void VisitPointers(Object** start, Object** end) {
5719 for (Object** p = start; p < end; p++)
Ben Murdochf87a2032010-10-22 12:50:53 +01005720 PrintF(" handle %p to %p\n",
5721 reinterpret_cast<void*>(p),
5722 reinterpret_cast<void*>(*p));
Steve Blocka7e24c12009-10-30 11:49:00 +00005723 }
5724};
5725
5726void Heap::PrintHandles() {
5727 PrintF("Handles:\n");
5728 PrintHandleVisitor v;
Steve Block44f0eee2011-05-26 01:26:41 +01005729 isolate_->handle_scope_implementer()->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +00005730}
5731
5732#endif
5733
5734
5735Space* AllSpaces::next() {
5736 switch (counter_++) {
5737 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005738 return HEAP->new_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005739 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005740 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005741 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005742 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005743 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005744 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005745 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005746 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005747 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005748 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005749 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005750 return HEAP->lo_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005751 default:
5752 return NULL;
5753 }
5754}
5755
5756
5757PagedSpace* PagedSpaces::next() {
5758 switch (counter_++) {
5759 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005760 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005761 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005762 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005763 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005764 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005765 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005766 return HEAP->map_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005767 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005768 return HEAP->cell_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005769 default:
5770 return NULL;
5771 }
5772}
5773
5774
5775
5776OldSpace* OldSpaces::next() {
5777 switch (counter_++) {
5778 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005779 return HEAP->old_pointer_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005780 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005781 return HEAP->old_data_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005782 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005783 return HEAP->code_space();
Steve Blocka7e24c12009-10-30 11:49:00 +00005784 default:
5785 return NULL;
5786 }
5787}
5788
5789
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005790SpaceIterator::SpaceIterator()
5791 : current_space_(FIRST_SPACE),
5792 iterator_(NULL),
5793 size_func_(NULL) {
5794}
5795
5796
5797SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
5798 : current_space_(FIRST_SPACE),
5799 iterator_(NULL),
5800 size_func_(size_func) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005801}
5802
5803
5804SpaceIterator::~SpaceIterator() {
5805 // Delete active iterator if any.
5806 delete iterator_;
5807}
5808
5809
5810bool SpaceIterator::has_next() {
5811 // Iterate until no more spaces.
5812 return current_space_ != LAST_SPACE;
5813}
5814
5815
5816ObjectIterator* SpaceIterator::next() {
5817 if (iterator_ != NULL) {
5818 delete iterator_;
5819 iterator_ = NULL;
5820 // Move to the next space
5821 current_space_++;
5822 if (current_space_ > LAST_SPACE) {
5823 return NULL;
5824 }
5825 }
5826
5827 // Return iterator for the new current space.
5828 return CreateIterator();
5829}
5830
5831
5832// Create an iterator for the space to iterate.
5833ObjectIterator* SpaceIterator::CreateIterator() {
5834 ASSERT(iterator_ == NULL);
5835
5836 switch (current_space_) {
5837 case NEW_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005838 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005839 break;
5840 case OLD_POINTER_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005841 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005842 break;
5843 case OLD_DATA_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005844 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005845 break;
5846 case CODE_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005847 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005848 break;
5849 case MAP_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005850 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005851 break;
5852 case CELL_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005853 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005854 break;
5855 case LO_SPACE:
Steve Block44f0eee2011-05-26 01:26:41 +01005856 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005857 break;
5858 }
5859
5860 // Return the newly allocated iterator;
5861 ASSERT(iterator_ != NULL);
5862 return iterator_;
5863}
5864
5865
Ben Murdochb0fe1622011-05-05 13:52:32 +01005866class HeapObjectsFilter {
5867 public:
5868 virtual ~HeapObjectsFilter() {}
5869 virtual bool SkipObject(HeapObject* object) = 0;
5870};
5871
5872
Ben Murdochb0fe1622011-05-05 13:52:32 +01005873class UnreachableObjectsFilter : public HeapObjectsFilter {
5874 public:
5875 UnreachableObjectsFilter() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005876 MarkReachableObjects();
5877 }
5878
5879 ~UnreachableObjectsFilter() {
5880 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005881 }
5882
5883 bool SkipObject(HeapObject* object) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005884 MarkBit mark_bit = Marking::MarkBitFrom(object);
5885 return !mark_bit.Get();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005886 }
5887
5888 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005889 class MarkingVisitor : public ObjectVisitor {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005890 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005891 MarkingVisitor() : marking_stack_(10) {}
Ben Murdochb0fe1622011-05-05 13:52:32 +01005892
5893 void VisitPointers(Object** start, Object** end) {
5894 for (Object** p = start; p < end; p++) {
5895 if (!(*p)->IsHeapObject()) continue;
5896 HeapObject* obj = HeapObject::cast(*p);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005897 MarkBit mark_bit = Marking::MarkBitFrom(obj);
5898 if (!mark_bit.Get()) {
5899 mark_bit.Set();
5900 marking_stack_.Add(obj);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005901 }
5902 }
5903 }
5904
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005905 void TransitiveClosure() {
5906 while (!marking_stack_.is_empty()) {
5907 HeapObject* obj = marking_stack_.RemoveLast();
5908 obj->Iterate(this);
5909 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01005910 }
5911
5912 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005913 List<HeapObject*> marking_stack_;
Ben Murdochb0fe1622011-05-05 13:52:32 +01005914 };
5915
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005916 void MarkReachableObjects() {
5917 Heap* heap = Isolate::Current()->heap();
5918 MarkingVisitor visitor;
5919 heap->IterateRoots(&visitor, VISIT_ALL);
5920 visitor.TransitiveClosure();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005921 }
5922
5923 AssertNoAllocation no_alloc;
5924};
5925
5926
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005927HeapIterator::HeapIterator()
5928 : filtering_(HeapIterator::kNoFiltering),
5929 filter_(NULL) {
5930 Init();
5931}
5932
5933
Ben Murdochb0fe1622011-05-05 13:52:32 +01005934HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005935 : filtering_(filtering),
5936 filter_(NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005937 Init();
5938}
5939
5940
5941HeapIterator::~HeapIterator() {
5942 Shutdown();
5943}
5944
5945
5946void HeapIterator::Init() {
5947 // Start the iteration.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00005948 space_iterator_ = new SpaceIterator;
Ben Murdochb0fe1622011-05-05 13:52:32 +01005949 switch (filtering_) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005950 case kFilterUnreachable:
5951 filter_ = new UnreachableObjectsFilter;
5952 break;
5953 default:
5954 break;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005955 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005956 object_iterator_ = space_iterator_->next();
5957}
5958
5959
5960void HeapIterator::Shutdown() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005961#ifdef DEBUG
Ben Murdochb0fe1622011-05-05 13:52:32 +01005962 // Assert that in filtering mode we have iterated through all
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005963 // objects. Otherwise, heap will be left in an inconsistent state.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005964 if (filtering_ != kNoFiltering) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005965 ASSERT(object_iterator_ == NULL);
5966 }
5967#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005968 // Make sure the last iterator is deallocated.
5969 delete space_iterator_;
5970 space_iterator_ = NULL;
5971 object_iterator_ = NULL;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005972 delete filter_;
5973 filter_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00005974}
5975
5976
Leon Clarked91b9f72010-01-27 17:25:45 +00005977HeapObject* HeapIterator::next() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005978 if (filter_ == NULL) return NextObject();
5979
5980 HeapObject* obj = NextObject();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005981 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005982 return obj;
5983}
5984
5985
5986HeapObject* HeapIterator::NextObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005987 // No iterator means we are done.
Leon Clarked91b9f72010-01-27 17:25:45 +00005988 if (object_iterator_ == NULL) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00005989
Leon Clarked91b9f72010-01-27 17:25:45 +00005990 if (HeapObject* obj = object_iterator_->next_object()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005991 // If the current iterator has more objects we are fine.
Leon Clarked91b9f72010-01-27 17:25:45 +00005992 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005993 } else {
5994 // Go though the spaces looking for one that has objects.
5995 while (space_iterator_->has_next()) {
5996 object_iterator_ = space_iterator_->next();
Leon Clarked91b9f72010-01-27 17:25:45 +00005997 if (HeapObject* obj = object_iterator_->next_object()) {
5998 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005999 }
6000 }
6001 }
6002 // Done with the last space.
6003 object_iterator_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00006004 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00006005}
6006
6007
6008void HeapIterator::reset() {
6009 // Restart the iterator.
6010 Shutdown();
6011 Init();
6012}
6013
6014
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006015#if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
Steve Blocka7e24c12009-10-30 11:49:00 +00006016
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006017Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00006018
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006019class PathTracer::MarkVisitor: public ObjectVisitor {
Steve Blocka7e24c12009-10-30 11:49:00 +00006020 public:
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006021 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00006022 void VisitPointers(Object** start, Object** end) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006023 // Scan all HeapObject pointers in [start, end)
6024 for (Object** p = start; !tracer_->found() && (p < end); p++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006025 if ((*p)->IsHeapObject())
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006026 tracer_->MarkRecursively(p, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006027 }
6028 }
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006029
6030 private:
6031 PathTracer* tracer_;
Steve Blocka7e24c12009-10-30 11:49:00 +00006032};
6033
Steve Blocka7e24c12009-10-30 11:49:00 +00006034
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006035class PathTracer::UnmarkVisitor: public ObjectVisitor {
6036 public:
6037 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6038 void VisitPointers(Object** start, Object** end) {
6039 // Scan all HeapObject pointers in [start, end)
6040 for (Object** p = start; p < end; p++) {
6041 if ((*p)->IsHeapObject())
6042 tracer_->UnmarkRecursively(p, this);
6043 }
6044 }
6045
6046 private:
6047 PathTracer* tracer_;
6048};
6049
6050
6051void PathTracer::VisitPointers(Object** start, Object** end) {
6052 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6053 // Visit all HeapObject pointers in [start, end)
6054 for (Object** p = start; !done && (p < end); p++) {
6055 if ((*p)->IsHeapObject()) {
6056 TracePathFrom(p);
6057 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6058 }
6059 }
6060}
6061
6062
6063void PathTracer::Reset() {
6064 found_target_ = false;
6065 object_stack_.Clear();
6066}
6067
6068
6069void PathTracer::TracePathFrom(Object** root) {
6070 ASSERT((search_target_ == kAnyGlobalObject) ||
6071 search_target_->IsHeapObject());
6072 found_target_in_trace_ = false;
6073 object_stack_.Clear();
6074
6075 MarkVisitor mark_visitor(this);
6076 MarkRecursively(root, &mark_visitor);
6077
6078 UnmarkVisitor unmark_visitor(this);
6079 UnmarkRecursively(root, &unmark_visitor);
6080
6081 ProcessResults();
6082}
6083
6084
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006085static bool SafeIsGlobalContext(HeapObject* obj) {
6086 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6087}
6088
6089
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006090void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006091 if (!(*p)->IsHeapObject()) return;
6092
6093 HeapObject* obj = HeapObject::cast(*p);
6094
6095 Object* map = obj->map();
6096
6097 if (!map->IsHeapObject()) return; // visited before
6098
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006099 if (found_target_in_trace_) return; // stop if target found
6100 object_stack_.Add(obj);
6101 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6102 (obj == search_target_)) {
6103 found_target_in_trace_ = true;
6104 found_target_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00006105 return;
6106 }
6107
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006108 bool is_global_context = SafeIsGlobalContext(obj);
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006109
Steve Blocka7e24c12009-10-30 11:49:00 +00006110 // not visited yet
6111 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6112
6113 Address map_addr = map_p->address();
6114
6115 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
6116
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006117 // Scan the object body.
6118 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6119 // This is specialized to scan Context's properly.
6120 Object** start = reinterpret_cast<Object**>(obj->address() +
6121 Context::kHeaderSize);
6122 Object** end = reinterpret_cast<Object**>(obj->address() +
6123 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6124 mark_visitor->VisitPointers(start, end);
6125 } else {
6126 obj->IterateBody(map_p->instance_type(),
6127 obj->SizeFromMap(map_p),
6128 mark_visitor);
6129 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006130
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006131 // Scan the map after the body because the body is a lot more interesting
6132 // when doing leak detection.
6133 MarkRecursively(&map, mark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006134
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006135 if (!found_target_in_trace_) // don't pop if found the target
6136 object_stack_.RemoveLast();
Steve Blocka7e24c12009-10-30 11:49:00 +00006137}
6138
6139
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006140void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006141 if (!(*p)->IsHeapObject()) return;
6142
6143 HeapObject* obj = HeapObject::cast(*p);
6144
6145 Object* map = obj->map();
6146
6147 if (map->IsHeapObject()) return; // unmarked already
6148
6149 Address map_addr = reinterpret_cast<Address>(map);
6150
6151 map_addr -= kMarkTag;
6152
6153 ASSERT_TAG_ALIGNED(map_addr);
6154
6155 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6156
6157 obj->set_map(reinterpret_cast<Map*>(map_p));
6158
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006159 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006160
6161 obj->IterateBody(Map::cast(map_p)->instance_type(),
6162 obj->SizeFromMap(Map::cast(map_p)),
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006163 unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00006164}
6165
6166
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006167void PathTracer::ProcessResults() {
6168 if (found_target_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006169 PrintF("=====================================\n");
6170 PrintF("==== Path to object ====\n");
6171 PrintF("=====================================\n\n");
6172
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006173 ASSERT(!object_stack_.is_empty());
6174 for (int i = 0; i < object_stack_.length(); i++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006175 if (i > 0) PrintF("\n |\n |\n V\n\n");
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006176 Object* obj = object_stack_[i];
6177#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00006178 obj->Print();
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006179#else
6180 obj->ShortPrint();
6181#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00006182 }
6183 PrintF("=====================================\n");
6184 }
6185}
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006186#endif // DEBUG || LIVE_OBJECT_LIST
Steve Blocka7e24c12009-10-30 11:49:00 +00006187
6188
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006189#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00006190// Triggers a depth-first traversal of reachable objects from roots
6191// and finds a path to a specific heap object and prints it.
Leon Clarkee46be812010-01-19 14:06:41 +00006192void Heap::TracePathToObject(Object* target) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006193 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6194 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006195}
6196
6197
6198// Triggers a depth-first traversal of reachable objects from roots
6199// and finds a path to any global object and prints it. Useful for
6200// determining the source for leaks of global objects.
6201void Heap::TracePathToGlobal() {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01006202 PathTracer tracer(PathTracer::kAnyGlobalObject,
6203 PathTracer::FIND_ALL,
6204 VISIT_ALL);
6205 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00006206}
6207#endif
6208
6209
Ben Murdochf87a2032010-10-22 12:50:53 +01006210static intptr_t CountTotalHolesSize() {
6211 intptr_t holes_size = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +01006212 OldSpaces spaces;
6213 for (OldSpace* space = spaces.next();
6214 space != NULL;
6215 space = spaces.next()) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006216 holes_size += space->Waste() + space->Available();
Leon Clarkef7060e22010-06-03 12:02:55 +01006217 }
6218 return holes_size;
6219}
6220
6221
Steve Block44f0eee2011-05-26 01:26:41 +01006222GCTracer::GCTracer(Heap* heap)
Steve Blocka7e24c12009-10-30 11:49:00 +00006223 : start_time_(0.0),
Leon Clarkef7060e22010-06-03 12:02:55 +01006224 start_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +00006225 gc_count_(0),
6226 full_gc_count_(0),
Leon Clarkef7060e22010-06-03 12:02:55 +01006227 allocated_since_last_gc_(0),
6228 spent_in_mutator_(0),
Steve Block44f0eee2011-05-26 01:26:41 +01006229 promoted_objects_size_(0),
6230 heap_(heap) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006231 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00006232 start_time_ = OS::TimeCurrentMillis();
Steve Block44f0eee2011-05-26 01:26:41 +01006233 start_size_ = heap_->SizeOfObjects();
Leon Clarkef7060e22010-06-03 12:02:55 +01006234
6235 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6236 scopes_[i] = 0;
6237 }
6238
6239 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6240
Steve Block44f0eee2011-05-26 01:26:41 +01006241 allocated_since_last_gc_ =
6242 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
Leon Clarkef7060e22010-06-03 12:02:55 +01006243
Steve Block44f0eee2011-05-26 01:26:41 +01006244 if (heap_->last_gc_end_timestamp_ > 0) {
6245 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006246 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006247
6248 steps_count_ = heap_->incremental_marking()->steps_count();
6249 steps_took_ = heap_->incremental_marking()->steps_took();
6250 longest_step_ = heap_->incremental_marking()->longest_step();
6251 steps_count_since_last_gc_ =
6252 heap_->incremental_marking()->steps_count_since_last_gc();
6253 steps_took_since_last_gc_ =
6254 heap_->incremental_marking()->steps_took_since_last_gc();
Steve Blocka7e24c12009-10-30 11:49:00 +00006255}
6256
6257
6258GCTracer::~GCTracer() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006259 // Printf ONE line iff flag is set.
Leon Clarkef7060e22010-06-03 12:02:55 +01006260 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6261
Steve Block44f0eee2011-05-26 01:26:41 +01006262 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
Leon Clarkef7060e22010-06-03 12:02:55 +01006263
Steve Block44f0eee2011-05-26 01:26:41 +01006264 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6265 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
Leon Clarkef7060e22010-06-03 12:02:55 +01006266
Steve Block44f0eee2011-05-26 01:26:41 +01006267 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006268
6269 // Update cumulative GC statistics if required.
6270 if (FLAG_print_cumulative_gc_stat) {
Steve Block44f0eee2011-05-26 01:26:41 +01006271 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6272 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6273 heap_->alive_after_last_gc_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006274 if (!first_gc) {
Steve Block44f0eee2011-05-26 01:26:41 +01006275 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6276 static_cast<int>(spent_in_mutator_));
Leon Clarkef7060e22010-06-03 12:02:55 +01006277 }
6278 }
6279
6280 if (!FLAG_trace_gc_nvp) {
6281 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6282
6283 PrintF("%s %.1f -> %.1f MB, ",
6284 CollectorString(),
6285 static_cast<double>(start_size_) / MB,
6286 SizeOfHeapObjects());
6287
6288 if (external_time > 0) PrintF("%d / ", external_time);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006289 PrintF("%d ms", time);
6290 if (steps_count_ > 0) {
6291 if (collector_ == SCAVENGER) {
6292 PrintF(" (+ %d ms in %d steps since last GC)",
6293 static_cast<int>(steps_took_since_last_gc_),
6294 steps_count_since_last_gc_);
6295 } else {
6296 PrintF(" (+ %d ms in %d steps since start of marking, "
6297 "biggest step %f ms)",
6298 static_cast<int>(steps_took_),
6299 steps_count_,
6300 longest_step_);
6301 }
6302 }
6303 PrintF(".\n");
Leon Clarkef7060e22010-06-03 12:02:55 +01006304 } else {
6305 PrintF("pause=%d ", time);
6306 PrintF("mutator=%d ",
6307 static_cast<int>(spent_in_mutator_));
6308
6309 PrintF("gc=");
6310 switch (collector_) {
6311 case SCAVENGER:
6312 PrintF("s");
6313 break;
6314 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006315 PrintF("ms");
Leon Clarkef7060e22010-06-03 12:02:55 +01006316 break;
6317 default:
6318 UNREACHABLE();
6319 }
6320 PrintF(" ");
6321
6322 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6323 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6324 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
Iain Merrick75681382010-08-19 15:07:18 +01006325 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006326 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6327 PrintF("new_new=%d ",
6328 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6329 PrintF("root_new=%d ",
6330 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6331 PrintF("old_new=%d ",
6332 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6333 PrintF("compaction_ptrs=%d ",
6334 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6335 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6336 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6337 PrintF("misc_compaction=%d ",
6338 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
Leon Clarkef7060e22010-06-03 12:02:55 +01006339
Ben Murdochf87a2032010-10-22 12:50:53 +01006340 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_size_);
Steve Block44f0eee2011-05-26 01:26:41 +01006341 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
Ben Murdochf87a2032010-10-22 12:50:53 +01006342 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6343 in_free_list_or_wasted_before_gc_);
6344 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
Leon Clarkef7060e22010-06-03 12:02:55 +01006345
Ben Murdochf87a2032010-10-22 12:50:53 +01006346 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6347 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
Leon Clarkef7060e22010-06-03 12:02:55 +01006348
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006349 if (collector_ == SCAVENGER) {
6350 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6351 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6352 } else {
6353 PrintF("stepscount=%d ", steps_count_);
6354 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6355 }
6356
Leon Clarkef7060e22010-06-03 12:02:55 +01006357 PrintF("\n");
6358 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006359
Steve Block44f0eee2011-05-26 01:26:41 +01006360 heap_->PrintShortHeapStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00006361}
6362
6363
6364const char* GCTracer::CollectorString() {
6365 switch (collector_) {
6366 case SCAVENGER:
6367 return "Scavenge";
6368 case MARK_COMPACTOR:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006369 return "Mark-sweep";
Steve Blocka7e24c12009-10-30 11:49:00 +00006370 }
6371 return "Unknown GC";
6372}
6373
6374
6375int KeyedLookupCache::Hash(Map* map, String* name) {
6376 // Uses only lower 32 bits if pointers are larger.
6377 uintptr_t addr_hash =
Leon Clarkee46be812010-01-19 14:06:41 +00006378 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
Andrei Popescu402d9372010-02-26 13:31:12 +00006379 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
Steve Blocka7e24c12009-10-30 11:49:00 +00006380}
6381
6382
6383int KeyedLookupCache::Lookup(Map* map, String* name) {
6384 int index = Hash(map, name);
6385 Key& key = keys_[index];
6386 if ((key.map == map) && key.name->Equals(name)) {
6387 return field_offsets_[index];
6388 }
Steve Block44f0eee2011-05-26 01:26:41 +01006389 return kNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00006390}
6391
6392
6393void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6394 String* symbol;
Steve Block44f0eee2011-05-26 01:26:41 +01006395 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006396 int index = Hash(map, symbol);
6397 Key& key = keys_[index];
6398 key.map = map;
6399 key.name = symbol;
6400 field_offsets_[index] = field_offset;
6401 }
6402}
6403
6404
6405void KeyedLookupCache::Clear() {
6406 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6407}
6408
6409
Steve Blocka7e24c12009-10-30 11:49:00 +00006410void DescriptorLookupCache::Clear() {
6411 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6412}
6413
6414
Steve Blocka7e24c12009-10-30 11:49:00 +00006415#ifdef DEBUG
Ben Murdochf87a2032010-10-22 12:50:53 +01006416void Heap::GarbageCollectionGreedyCheck() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006417 ASSERT(FLAG_gc_greedy);
Steve Block44f0eee2011-05-26 01:26:41 +01006418 if (isolate_->bootstrapper()->IsActive()) return;
Ben Murdochf87a2032010-10-22 12:50:53 +01006419 if (disallow_allocation_failure()) return;
6420 CollectGarbage(NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00006421}
6422#endif
6423
6424
Steve Block44f0eee2011-05-26 01:26:41 +01006425TranscendentalCache::SubCache::SubCache(Type t)
6426 : type_(t),
6427 isolate_(Isolate::Current()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006428 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6429 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6430 for (int i = 0; i < kCacheSize; i++) {
6431 elements_[i].in[0] = in0;
6432 elements_[i].in[1] = in1;
6433 elements_[i].output = NULL;
6434 }
6435}
6436
6437
Steve Blocka7e24c12009-10-30 11:49:00 +00006438void TranscendentalCache::Clear() {
6439 for (int i = 0; i < kNumberOfCaches; i++) {
6440 if (caches_[i] != NULL) {
6441 delete caches_[i];
6442 caches_[i] = NULL;
6443 }
6444 }
6445}
6446
6447
Leon Clarkee46be812010-01-19 14:06:41 +00006448void ExternalStringTable::CleanUp() {
6449 int last = 0;
6450 for (int i = 0; i < new_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006451 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6452 continue;
6453 }
Steve Block44f0eee2011-05-26 01:26:41 +01006454 if (heap_->InNewSpace(new_space_strings_[i])) {
Leon Clarkee46be812010-01-19 14:06:41 +00006455 new_space_strings_[last++] = new_space_strings_[i];
6456 } else {
6457 old_space_strings_.Add(new_space_strings_[i]);
6458 }
6459 }
6460 new_space_strings_.Rewind(last);
6461 last = 0;
6462 for (int i = 0; i < old_space_strings_.length(); ++i) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006463 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6464 continue;
6465 }
Steve Block44f0eee2011-05-26 01:26:41 +01006466 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
Leon Clarkee46be812010-01-19 14:06:41 +00006467 old_space_strings_[last++] = old_space_strings_[i];
6468 }
6469 old_space_strings_.Rewind(last);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006470 if (FLAG_verify_heap) {
6471 Verify();
6472 }
Leon Clarkee46be812010-01-19 14:06:41 +00006473}
6474
6475
6476void ExternalStringTable::TearDown() {
6477 new_space_strings_.Free();
6478 old_space_strings_.Free();
6479}
6480
6481
Ben Murdoch592a9fc2012-03-05 11:04:45 +00006482void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6483 chunk->set_next_chunk(chunks_queued_for_free_);
6484 chunks_queued_for_free_ = chunk;
6485}
6486
6487
6488void Heap::FreeQueuedChunks() {
6489 if (chunks_queued_for_free_ == NULL) return;
6490 MemoryChunk* next;
6491 MemoryChunk* chunk;
6492 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6493 next = chunk->next_chunk();
6494 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6495
6496 if (chunk->owner()->identity() == LO_SPACE) {
6497 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6498 // If FromAnyPointerAddress encounters a slot that belongs to a large
6499 // chunk queued for deletion it will fail to find the chunk because
6500 // it try to perform a search in the list of pages owned by of the large
6501 // object space and queued chunks were detached from that list.
6502 // To work around this we split large chunk into normal kPageSize aligned
6503 // pieces and initialize size, owner and flags field of every piece.
6504 // If FromAnyPointerAddress encounters a slot that belongs to one of
6505 // these smaller pieces it will treat it as a slot on a normal Page.
6506 MemoryChunk* inner = MemoryChunk::FromAddress(
6507 chunk->address() + Page::kPageSize);
6508 MemoryChunk* inner_last = MemoryChunk::FromAddress(
6509 chunk->address() + chunk->size() - 1);
6510 while (inner <= inner_last) {
6511 // Size of a large chunk is always a multiple of
6512 // OS::AllocateAlignment() so there is always
6513 // enough space for a fake MemoryChunk header.
6514 inner->set_size(Page::kPageSize);
6515 inner->set_owner(lo_space());
6516 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6517 inner = MemoryChunk::FromAddress(
6518 inner->address() + Page::kPageSize);
6519 }
6520 }
6521 }
6522 isolate_->heap()->store_buffer()->Compact();
6523 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6524 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6525 next = chunk->next_chunk();
6526 isolate_->memory_allocator()->Free(chunk);
6527 }
6528 chunks_queued_for_free_ = NULL;
6529}
6530
Steve Blocka7e24c12009-10-30 11:49:00 +00006531} } // namespace v8::internal