blob: 5f4d81501b17e7131286674948fdddb716db7bd4 [file] [log] [blame]
ager@chromium.org71daaf62009-04-01 07:22:49 +00001// Copyright 2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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"
33#include "codegen-inl.h"
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "debug.h"
christian.plesner.hansen@gmail.com2bc58ef2009-09-22 10:00:30 +000036#include "heap-profiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "global-handles.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000038#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
ager@chromium.org3811b432009-10-28 14:53:37 +000042#include "snapshot.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043#include "v8threads.h"
ager@chromium.org18ad94b2009-09-02 08:22:29 +000044#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
45#include "regexp-macro-assembler.h"
ager@chromium.org3811b432009-10-28 14:53:37 +000046#include "arm/regexp-macro-assembler-arm.h"
ager@chromium.org18ad94b2009-09-02 08:22:29 +000047#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000048
kasperl@chromium.org71affb52009-05-26 05:44:31 +000049namespace v8 {
50namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052
ager@chromium.org3b45ab52009-03-19 22:21:34 +000053String* Heap::hidden_symbol_;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000054Object* Heap::roots_[Heap::kRootListLength];
55
ager@chromium.org3b45ab52009-03-19 22:21:34 +000056
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000057NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000058OldSpace* Heap::old_pointer_space_ = NULL;
59OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060OldSpace* Heap::code_space_ = NULL;
61MapSpace* Heap::map_space_ = NULL;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +000062CellSpace* Heap::cell_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063LargeObjectSpace* Heap::lo_space_ = NULL;
64
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000065static const int kMinimumPromotionLimit = 2*MB;
66static const int kMinimumAllocationLimit = 8*MB;
67
68int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
69int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
70
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000071int Heap::old_gen_exhausted_ = false;
72
kasper.lund7276f142008-07-30 08:49:36 +000073int Heap::amount_of_external_allocated_memory_ = 0;
74int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
75
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000076// semispace_size_ should be a power of 2 and old_generation_size_ should be
77// a multiple of Page::kPageSize.
kasperl@chromium.orge959c182009-07-27 08:59:04 +000078#if defined(ANDROID)
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000079int Heap::max_semispace_size_ = 2*MB;
80int Heap::max_old_generation_size_ = 192*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000081int Heap::initial_semispace_size_ = 128*KB;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000082size_t Heap::code_range_size_ = 0;
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +000083#elif defined(V8_TARGET_ARCH_X64)
ager@chromium.org3811b432009-10-28 14:53:37 +000084int Heap::max_semispace_size_ = 16*MB;
85int Heap::max_old_generation_size_ = 1*GB;
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000086int Heap::initial_semispace_size_ = 1*MB;
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +000087size_t Heap::code_range_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000088#else
ager@chromium.org3811b432009-10-28 14:53:37 +000089int Heap::max_semispace_size_ = 8*MB;
90int Heap::max_old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000091int Heap::initial_semispace_size_ = 512*KB;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000092size_t Heap::code_range_size_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000093#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000094
ager@chromium.org3811b432009-10-28 14:53:37 +000095// The snapshot semispace size will be the default semispace size if
96// snapshotting is used and will be the requested semispace size as
97// set up by ConfigureHeap otherwise.
98int Heap::reserved_semispace_size_ = Heap::max_semispace_size_;
99
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000100GCCallback Heap::global_gc_prologue_callback_ = NULL;
101GCCallback Heap::global_gc_epilogue_callback_ = NULL;
102
103// Variables set based on semispace_size_ and old_generation_size_ in
104// ConfigureHeap.
ager@chromium.org3811b432009-10-28 14:53:37 +0000105
106// Will be 4 * reserved_semispace_size_ to ensure that young
107// generation can be aligned to its size.
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000108int Heap::survived_since_last_expansion_ = 0;
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000109int Heap::external_allocation_limit_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000110
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000111Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
112
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000113int Heap::mc_count_ = 0;
114int Heap::gc_count_ = 0;
115
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000116int Heap::always_allocate_scope_depth_ = 0;
ager@chromium.org3811b432009-10-28 14:53:37 +0000117int Heap::linear_allocation_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000118bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000119
kasper.lund7276f142008-07-30 08:49:36 +0000120#ifdef DEBUG
121bool Heap::allocation_allowed_ = true;
122
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123int Heap::allocation_timeout_ = 0;
124bool Heap::disallow_allocation_failure_ = false;
125#endif // DEBUG
126
127
128int Heap::Capacity() {
129 if (!HasBeenSetup()) return 0;
130
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000131 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000132 old_pointer_space_->Capacity() +
133 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000134 code_space_->Capacity() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000135 map_space_->Capacity() +
136 cell_space_->Capacity();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000137}
138
139
ager@chromium.org3811b432009-10-28 14:53:37 +0000140int Heap::CommittedMemory() {
141 if (!HasBeenSetup()) return 0;
142
143 return new_space_.CommittedMemory() +
144 old_pointer_space_->CommittedMemory() +
145 old_data_space_->CommittedMemory() +
146 code_space_->CommittedMemory() +
147 map_space_->CommittedMemory() +
148 cell_space_->CommittedMemory() +
149 lo_space_->Size();
150}
151
152
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000153int Heap::Available() {
154 if (!HasBeenSetup()) return 0;
155
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000156 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000157 old_pointer_space_->Available() +
158 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000159 code_space_->Available() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000160 map_space_->Available() +
161 cell_space_->Available();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000162}
163
164
165bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000166 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000167 old_data_space_ != NULL &&
168 code_space_ != NULL &&
169 map_space_ != NULL &&
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000170 cell_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000171 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000172}
173
174
175GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
176 // Is global GC requested?
177 if (space != NEW_SPACE || FLAG_gc_global) {
178 Counters::gc_compactor_caused_by_request.Increment();
179 return MARK_COMPACTOR;
180 }
181
182 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000183 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000184 Counters::gc_compactor_caused_by_promoted_data.Increment();
185 return MARK_COMPACTOR;
186 }
187
188 // Have allocation in OLD and LO failed?
189 if (old_gen_exhausted_) {
190 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
191 return MARK_COMPACTOR;
192 }
193
194 // Is there enough space left in OLD to guarantee that a scavenge can
195 // succeed?
196 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000197 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 // for object promotion. It counts only the bytes that the memory
199 // allocator has not yet allocated from the OS and assigned to any space,
200 // and does not count available bytes already in the old space or code
201 // space. Undercounting is safe---we may get an unrequested full GC when
202 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
205 return MARK_COMPACTOR;
206 }
207
208 // Default
209 return SCAVENGER;
210}
211
212
213// TODO(1238405): Combine the infrastructure for --heap-stats and
214// --log-gc to avoid the complicated preprocessor and flag testing.
215#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
216void Heap::ReportStatisticsBeforeGC() {
217 // Heap::ReportHeapStatistics will also log NewSpace statistics when
218 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
219 // following logic is used to avoid double logging.
220#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000221 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222 if (FLAG_heap_stats) {
223 ReportHeapStatistics("Before GC");
224 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000225 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000227 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228#elif defined(DEBUG)
229 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000230 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000232 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233 }
234#elif defined(ENABLE_LOGGING_AND_PROFILING)
235 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000236 new_space_.CollectStatistics();
237 new_space_.ReportStatistics();
238 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239 }
240#endif
241}
242
243
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000244#if defined(ENABLE_LOGGING_AND_PROFILING)
245void Heap::PrintShortHeapStatistics() {
246 if (!FLAG_trace_gc_verbose) return;
247 PrintF("Memory allocator, used: %8d, available: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000248 MemoryAllocator::Size(),
249 MemoryAllocator::Available());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000250 PrintF("New space, used: %8d, available: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000251 Heap::new_space_.Size(),
252 new_space_.Available());
253 PrintF("Old pointers, used: %8d, available: %8d, waste: %8d\n",
254 old_pointer_space_->Size(),
255 old_pointer_space_->Available(),
256 old_pointer_space_->Waste());
257 PrintF("Old data space, used: %8d, available: %8d, waste: %8d\n",
258 old_data_space_->Size(),
259 old_data_space_->Available(),
260 old_data_space_->Waste());
261 PrintF("Code space, used: %8d, available: %8d, waste: %8d\n",
262 code_space_->Size(),
263 code_space_->Available(),
264 code_space_->Waste());
265 PrintF("Map space, used: %8d, available: %8d, waste: %8d\n",
266 map_space_->Size(),
267 map_space_->Available(),
268 map_space_->Waste());
269 PrintF("Cell space, used: %8d, available: %8d, waste: %8d\n",
270 cell_space_->Size(),
271 cell_space_->Available(),
272 cell_space_->Waste());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000273 PrintF("Large object space, used: %8d, avaialble: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000274 lo_space_->Size(),
275 lo_space_->Available());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000276}
277#endif
278
279
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000280// TODO(1238405): Combine the infrastructure for --heap-stats and
281// --log-gc to avoid the complicated preprocessor and flag testing.
282void Heap::ReportStatisticsAfterGC() {
283 // Similar to the before GC, we use some complicated logic to ensure that
284 // NewSpace statistics are logged exactly once when --log-gc is turned on.
285#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
286 if (FLAG_heap_stats) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000287 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000288 ReportHeapStatistics("After GC");
289 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000290 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000291 }
292#elif defined(DEBUG)
293 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
294#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000295 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000296#endif
297}
298#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
299
300
301void Heap::GarbageCollectionPrologue() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000302 TranscendentalCache::Clear();
kasper.lund7276f142008-07-30 08:49:36 +0000303 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000304#ifdef DEBUG
305 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
306 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307
308 if (FLAG_verify_heap) {
309 Verify();
310 }
311
312 if (FLAG_gc_verbose) Print();
313
314 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000315 // Not all spaces have remembered set bits that we care about.
316 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317 map_space_->PrintRSet();
318 lo_space_->PrintRSet();
319 }
320#endif
321
322#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
323 ReportStatisticsBeforeGC();
324#endif
325}
326
327int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000328 int total = 0;
329 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000330 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000331 total += space->Size();
332 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000333 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334}
335
336void Heap::GarbageCollectionEpilogue() {
337#ifdef DEBUG
338 allow_allocation(true);
339 ZapFromSpace();
340
341 if (FLAG_verify_heap) {
342 Verify();
343 }
344
345 if (FLAG_print_global_handles) GlobalHandles::Print();
346 if (FLAG_print_handles) PrintHandles();
347 if (FLAG_gc_verbose) Print();
348 if (FLAG_code_stats) ReportCodeStatistics("After GC");
349#endif
350
351 Counters::alive_after_last_gc.Set(SizeOfObjects());
352
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000353 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
354 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
356 ReportStatisticsAfterGC();
357#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000358#ifdef ENABLE_DEBUGGER_SUPPORT
359 Debug::AfterGarbageCollection();
360#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361}
362
363
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000364void Heap::CollectAllGarbage(bool force_compaction) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000365 // Since we are ignoring the return value, the exact choice of space does
366 // not matter, so long as we do not specify NEW_SPACE, which would not
367 // cause a full GC.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000368 MarkCompactCollector::SetForceCompaction(force_compaction);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000369 CollectGarbage(0, OLD_POINTER_SPACE);
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000370 MarkCompactCollector::SetForceCompaction(false);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000371}
372
373
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000374void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000375 // If the garbage collector interface is exposed through the global
376 // gc() function, we avoid being clever about forcing GCs when
377 // contexts are disposed and leave it to the embedder to make
378 // informed decisions about when to force a collection.
379 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000380 HistogramTimerScope scope(&Counters::gc_context);
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000381 CollectAllGarbage(false);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000382 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000383 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000384}
385
386
387void Heap::NotifyContextDisposed() {
388 context_disposed_pending_ = true;
389}
390
391
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000392bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
393 // The VM is in the GC state until exiting this function.
394 VMState state(GC);
395
396#ifdef DEBUG
397 // Reset the allocation timeout to the GC interval, but make sure to
398 // allow at least a few allocations after a collection. The reason
399 // for this is that we have a lot of allocation sequences and we
400 // assume that a garbage collection will allow the subsequent
401 // allocation attempts to go through.
402 allocation_timeout_ = Max(6, FLAG_gc_interval);
403#endif
404
405 { GCTracer tracer;
406 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000407 // The GC count was incremented in the prologue. Tell the tracer about
408 // it.
409 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410
411 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000412 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413 tracer.set_collector(collector);
414
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000415 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000416 ? &Counters::gc_scavenger
417 : &Counters::gc_compactor;
418 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000419 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 rate->Stop();
421
422 GarbageCollectionEpilogue();
423 }
424
425
426#ifdef ENABLE_LOGGING_AND_PROFILING
427 if (FLAG_log_gc) HeapProfiler::WriteSample();
428#endif
429
430 switch (space) {
431 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000432 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000433 case OLD_POINTER_SPACE:
434 return old_pointer_space_->Available() >= requested_size;
435 case OLD_DATA_SPACE:
436 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000437 case CODE_SPACE:
438 return code_space_->Available() >= requested_size;
439 case MAP_SPACE:
440 return map_space_->Available() >= requested_size;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000441 case CELL_SPACE:
442 return cell_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443 case LO_SPACE:
444 return lo_space_->Available() >= requested_size;
445 }
446 return false;
447}
448
449
kasper.lund7276f142008-07-30 08:49:36 +0000450void Heap::PerformScavenge() {
451 GCTracer tracer;
452 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
453}
454
455
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000456#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000457// Helper class for verifying the symbol table.
458class SymbolTableVerifier : public ObjectVisitor {
459 public:
460 SymbolTableVerifier() { }
461 void VisitPointers(Object** start, Object** end) {
462 // Visit all HeapObject pointers in [start, end).
463 for (Object** p = start; p < end; p++) {
464 if ((*p)->IsHeapObject()) {
465 // Check that the symbol is actually a symbol.
466 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000467 }
468 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000469 }
470};
471#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000472
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000473
474static void VerifySymbolTable() {
475#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000476 SymbolTableVerifier verifier;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000477 Heap::symbol_table()->IterateElements(&verifier);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000478#endif // DEBUG
479}
480
481
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000482void Heap::ReserveSpace(
483 int new_space_size,
484 int pointer_space_size,
485 int data_space_size,
486 int code_space_size,
487 int map_space_size,
488 int cell_space_size,
489 int large_object_size) {
490 NewSpace* new_space = Heap::new_space();
491 PagedSpace* old_pointer_space = Heap::old_pointer_space();
492 PagedSpace* old_data_space = Heap::old_data_space();
493 PagedSpace* code_space = Heap::code_space();
494 PagedSpace* map_space = Heap::map_space();
495 PagedSpace* cell_space = Heap::cell_space();
496 LargeObjectSpace* lo_space = Heap::lo_space();
497 bool gc_performed = true;
498 while (gc_performed) {
499 gc_performed = false;
500 if (!new_space->ReserveSpace(new_space_size)) {
501 Heap::CollectGarbage(new_space_size, NEW_SPACE);
502 gc_performed = true;
503 }
504 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
505 Heap::CollectGarbage(pointer_space_size, OLD_POINTER_SPACE);
506 gc_performed = true;
507 }
508 if (!(old_data_space->ReserveSpace(data_space_size))) {
509 Heap::CollectGarbage(data_space_size, OLD_DATA_SPACE);
510 gc_performed = true;
511 }
512 if (!(code_space->ReserveSpace(code_space_size))) {
513 Heap::CollectGarbage(code_space_size, CODE_SPACE);
514 gc_performed = true;
515 }
516 if (!(map_space->ReserveSpace(map_space_size))) {
517 Heap::CollectGarbage(map_space_size, MAP_SPACE);
518 gc_performed = true;
519 }
520 if (!(cell_space->ReserveSpace(cell_space_size))) {
521 Heap::CollectGarbage(cell_space_size, CELL_SPACE);
522 gc_performed = true;
523 }
524 // We add a slack-factor of 2 in order to have space for the remembered
525 // set and a series of large-object allocations that are only just larger
526 // than the page size.
527 large_object_size *= 2;
528 // The ReserveSpace method on the large object space checks how much
529 // we can expand the old generation. This includes expansion caused by
530 // allocation in the other spaces.
531 large_object_size += cell_space_size + map_space_size + code_space_size +
532 data_space_size + pointer_space_size;
533 if (!(lo_space->ReserveSpace(large_object_size))) {
534 Heap::CollectGarbage(large_object_size, LO_SPACE);
535 gc_performed = true;
536 }
537 }
538}
539
540
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000541void Heap::EnsureFromSpaceIsCommitted() {
542 if (new_space_.CommitFromSpaceIfNeeded()) return;
543
544 // Committing memory to from space failed.
545 // Try shrinking and try again.
546 Shrink();
547 if (new_space_.CommitFromSpaceIfNeeded()) return;
548
549 // Committing memory to from space failed again.
550 // Memory is exhausted and we will die.
551 V8::FatalProcessOutOfMemory("Committing semi space failed.");
552}
553
554
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000556 GarbageCollector collector,
557 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000558 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000559 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
560 ASSERT(!allocation_allowed_);
561 global_gc_prologue_callback_();
562 }
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000563 EnsureFromSpaceIsCommitted();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000565 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000567 int old_gen_size = PromotedSpaceSize();
568 old_gen_promotion_limit_ =
569 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
570 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000571 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572 old_gen_exhausted_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573 }
ager@chromium.org439e85a2009-08-26 13:15:29 +0000574 Scavenge();
575
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 Counters::objs_since_last_young.Set(0);
577
ager@chromium.org3811b432009-10-28 14:53:37 +0000578 if (collector == MARK_COMPACTOR) {
579 DisableAssertNoAllocation allow_allocation;
580 GlobalHandles::PostGarbageCollectionProcessing();
581 }
582
583 // Update relocatables.
584 Relocatable::PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585
kasper.lund7276f142008-07-30 08:49:36 +0000586 if (collector == MARK_COMPACTOR) {
587 // Register the amount of external allocated memory.
588 amount_of_external_allocated_memory_at_last_global_gc_ =
589 amount_of_external_allocated_memory_;
590 }
591
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000592 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
593 ASSERT(!allocation_allowed_);
594 global_gc_epilogue_callback_();
595 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000596 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597}
598
599
kasper.lund7276f142008-07-30 08:49:36 +0000600void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000601 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000603 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604 LOG(ResourceEvent("markcompact", "begin"));
605
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000606 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000608 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000609
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000610 MarkCompactPrologue(is_compacting);
611
612 MarkCompactCollector::CollectGarbage();
613
614 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615
616 LOG(ResourceEvent("markcompact", "end"));
617
618 gc_state_ = NOT_IN_GC;
619
620 Shrink();
621
622 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000623 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000624}
625
626
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000627void Heap::MarkCompactPrologue(bool is_compacting) {
628 // At any old GC clear the keyed lookup cache to enable collection of unused
629 // maps.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000630 KeyedLookupCache::Clear();
631 ContextSlotCache::Clear();
632 DescriptorLookupCache::Clear();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000633
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000634 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000635
636 Top::MarkCompactPrologue(is_compacting);
637 ThreadManager::MarkCompactPrologue(is_compacting);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000638
639 if (is_compacting) FlushNumberStringCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000640}
641
642
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000643void Heap::MarkCompactEpilogue(bool is_compacting) {
644 Top::MarkCompactEpilogue(is_compacting);
645 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646}
647
648
649Object* Heap::FindCodeObject(Address a) {
650 Object* obj = code_space_->FindObject(a);
651 if (obj->IsFailure()) {
652 obj = lo_space_->FindObject(a);
653 }
kasper.lund7276f142008-07-30 08:49:36 +0000654 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000655 return obj;
656}
657
658
659// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000660class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000661 public:
662
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000663 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000664
665 void VisitPointers(Object** start, Object** end) {
666 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000667 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000668 }
669
670 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000671 void ScavengePointer(Object** p) {
672 Object* object = *p;
673 if (!Heap::InNewSpace(object)) return;
674 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
675 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676 }
677};
678
679
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000680// A queue of pointers and maps of to-be-promoted objects during a
681// scavenge collection.
682class PromotionQueue {
683 public:
684 void Initialize(Address start_address) {
685 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
686 }
687
688 bool is_empty() { return front_ <= rear_; }
689
690 void insert(HeapObject* object, Map* map) {
691 *(--rear_) = object;
692 *(--rear_) = map;
693 // Assert no overflow into live objects.
694 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
695 }
696
697 void remove(HeapObject** object, Map** map) {
698 *object = *(--front_);
699 *map = Map::cast(*(--front_));
700 // Assert no underflow.
701 ASSERT(front_ >= rear_);
702 }
703
704 private:
705 // The front of the queue is higher in memory than the rear.
706 HeapObject** front_;
707 HeapObject** rear_;
708};
709
710
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000711// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000712static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713
714
715#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000716// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000717// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000718class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000719 public:
720 void VisitPointers(Object** start, Object**end) {
721 for (Object** current = start; current < end; current++) {
722 if ((*current)->IsHeapObject()) {
723 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
724 }
725 }
726 }
727};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000728
729
730static void VerifyNonPointerSpacePointers() {
731 // Verify that there are no pointers to new space in spaces where we
732 // do not expect them.
733 VerifyNonPointerSpacePointersVisitor v;
734 HeapObjectIterator code_it(Heap::code_space());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000735 for (HeapObject* object = code_it.next();
736 object != NULL; object = code_it.next())
christian.plesner.hansen@gmail.com2bc58ef2009-09-22 10:00:30 +0000737 object->Iterate(&v);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000738
739 HeapObjectIterator data_it(Heap::old_data_space());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000740 for (HeapObject* object = data_it.next();
741 object != NULL; object = data_it.next())
742 object->Iterate(&v);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000743}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000744#endif
745
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000746
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000747void Heap::Scavenge() {
748#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000749 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000750#endif
751
752 gc_state_ = SCAVENGE;
753
754 // Implements Cheney's copying algorithm
755 LOG(ResourceEvent("scavenge", "begin"));
756
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000757 // Clear descriptor cache.
758 DescriptorLookupCache::Clear();
759
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000760 // Used for updating survived_since_last_expansion_ at function end.
761 int survived_watermark = PromotedSpaceSize();
762
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000763 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000764 survived_since_last_expansion_ > new_space_.Capacity()) {
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000765 // Grow the size of new space if there is room to grow and enough
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000766 // data has survived scavenge since the last expansion.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000767 new_space_.Grow();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000768 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000769 }
770
771 // Flip the semispaces. After flipping, to space is empty, from space has
772 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000773 new_space_.Flip();
774 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000776 // We need to sweep newly copied objects which can be either in the
777 // to space or promoted to the old generation. For to-space
778 // objects, we treat the bottom of the to space as a queue. Newly
779 // copied and unswept objects lie between a 'front' mark and the
780 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000781 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000782 // Promoted objects can go into various old-generation spaces, and
783 // can be allocated internally in the spaces (from the free list).
784 // We treat the top of the to space as a queue of addresses of
785 // promoted objects. The addresses of newly promoted and unswept
786 // objects lie between a 'front' mark and a 'rear' mark that is
787 // updated as a side effect of promoting an object.
788 //
789 // There is guaranteed to be enough room at the top of the to space
790 // for the addresses of promoted objects: every object promoted
791 // frees up its size in bytes from the top of the new space, and
792 // objects are at least one pointer in size.
793 Address new_space_front = new_space_.ToSpaceLow();
794 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000795
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000796 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 // Copy roots.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000798 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000799
800 // Copy objects reachable from the old generation. By definition,
801 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000802 IterateRSet(old_pointer_space_, &ScavengePointer);
803 IterateRSet(map_space_, &ScavengePointer);
804 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000805
806 // Copy objects reachable from cells by scavenging cell values directly.
807 HeapObjectIterator cell_iterator(cell_space_);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000808 for (HeapObject* cell = cell_iterator.next();
809 cell != NULL; cell = cell_iterator.next()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000810 if (cell->IsJSGlobalPropertyCell()) {
811 Address value_address =
812 reinterpret_cast<Address>(cell) +
813 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
814 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
815 }
816 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000818 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
819
820 ScavengeExternalStringTable();
821 ASSERT(new_space_front == new_space_.top());
822
823 // Set age mark.
824 new_space_.set_age_mark(new_space_.top());
825
826 // Update how much has survived scavenge.
827 survived_since_last_expansion_ +=
828 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
829
830 LOG(ResourceEvent("scavenge", "end"));
831
832 gc_state_ = NOT_IN_GC;
833}
834
835
836void Heap::ScavengeExternalStringTable() {
837 ExternalStringTable::Verify();
838
839 if (ExternalStringTable::new_space_strings_.is_empty()) return;
840
841 Object** start = &ExternalStringTable::new_space_strings_[0];
842 Object** end = start + ExternalStringTable::new_space_strings_.length();
843 Object** last = start;
844
845 for (Object** p = start; p < end; ++p) {
846 ASSERT(Heap::InFromSpace(*p));
847 MapWord first_word = HeapObject::cast(*p)->map_word();
848
849 if (!first_word.IsForwardingAddress()) {
850 // Unreachable external string can be finalized.
851 FinalizeExternalString(String::cast(*p));
852 continue;
853 }
854
855 // String is still reachable.
856 String* target = String::cast(first_word.ToForwardingAddress());
857 ASSERT(target->IsExternalString());
858
859 if (Heap::InNewSpace(target)) {
860 // String is still in new space. Update the table entry.
861 *last = target;
862 ++last;
863 } else {
864 // String got promoted. Move it to the old string list.
865 ExternalStringTable::AddOldString(target);
866 }
867 }
868
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000869 ASSERT(last <= end);
870 ExternalStringTable::ShrinkNewStrings(static_cast<int>(last - start));
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000871}
872
873
874Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
875 Address new_space_front) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000876 do {
877 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000879 // The addresses new_space_front and new_space_.top() define a
880 // queue of unprocessed copied objects. Process them until the
881 // queue is empty.
882 while (new_space_front < new_space_.top()) {
883 HeapObject* object = HeapObject::FromAddress(new_space_front);
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000884 object->Iterate(scavenge_visitor);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000885 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886 }
887
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000888 // Promote and process all the to-be-promoted objects.
889 while (!promotion_queue.is_empty()) {
890 HeapObject* source;
891 Map* map;
892 promotion_queue.remove(&source, &map);
893 // Copy the from-space object to its new location (given by the
894 // forwarding address) and fix its map.
895 HeapObject* target = source->map_word().ToForwardingAddress();
896 CopyBlock(reinterpret_cast<Object**>(target->address()),
897 reinterpret_cast<Object**>(source->address()),
898 source->SizeFromMap(map));
899 target->set_map(map);
900
901#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
902 // Update NewSpace stats if necessary.
903 RecordCopiedObject(target);
904#endif
905 // Visit the newly copied object for pointers to new space.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000906 target->Iterate(scavenge_visitor);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000907 UpdateRSet(target);
908 }
909
910 // Take another spin if there are now unswept objects in new space
911 // (there are currently no more unswept promoted objects).
912 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000914 return new_space_front;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000915}
916
917
918void Heap::ClearRSetRange(Address start, int size_in_bytes) {
919 uint32_t start_bit;
920 Address start_word_address =
921 Page::ComputeRSetBitPosition(start, 0, &start_bit);
922 uint32_t end_bit;
923 Address end_word_address =
924 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
925 0,
926 &end_bit);
927
928 // We want to clear the bits in the starting word starting with the
929 // first bit, and in the ending word up to and including the last
930 // bit. Build a pair of bitmasks to do that.
931 uint32_t start_bitmask = start_bit - 1;
932 uint32_t end_bitmask = ~((end_bit << 1) - 1);
933
934 // If the start address and end address are the same, we mask that
935 // word once, otherwise mask the starting and ending word
936 // separately and all the ones in between.
937 if (start_word_address == end_word_address) {
938 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
939 } else {
940 Memory::uint32_at(start_word_address) &= start_bitmask;
941 Memory::uint32_at(end_word_address) &= end_bitmask;
942 start_word_address += kIntSize;
943 memset(start_word_address, 0, end_word_address - start_word_address);
944 }
945}
946
947
948class UpdateRSetVisitor: public ObjectVisitor {
949 public:
950
951 void VisitPointer(Object** p) {
952 UpdateRSet(p);
953 }
954
955 void VisitPointers(Object** start, Object** end) {
956 // Update a store into slots [start, end), used (a) to update remembered
957 // set when promoting a young object to old space or (b) to rebuild
958 // remembered sets after a mark-compact collection.
959 for (Object** p = start; p < end; p++) UpdateRSet(p);
960 }
961 private:
962
963 void UpdateRSet(Object** p) {
964 // The remembered set should not be set. It should be clear for objects
965 // newly copied to old space, and it is cleared before rebuilding in the
966 // mark-compact collector.
967 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
968 if (Heap::InNewSpace(*p)) {
969 Page::SetRSet(reinterpret_cast<Address>(p), 0);
970 }
971 }
972};
973
974
975int Heap::UpdateRSet(HeapObject* obj) {
976 ASSERT(!InNewSpace(obj));
977 // Special handling of fixed arrays to iterate the body based on the start
978 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
979 // will not work because Page::SetRSet needs to have the start of the
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000980 // object for large object pages.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000981 if (obj->IsFixedArray()) {
982 FixedArray* array = FixedArray::cast(obj);
983 int length = array->length();
984 for (int i = 0; i < length; i++) {
985 int offset = FixedArray::kHeaderSize + i * kPointerSize;
986 ASSERT(!Page::IsRSetSet(obj->address(), offset));
987 if (Heap::InNewSpace(array->get(i))) {
988 Page::SetRSet(obj->address(), offset);
989 }
990 }
991 } else if (!obj->IsCode()) {
992 // Skip code object, we know it does not contain inter-generational
993 // pointers.
994 UpdateRSetVisitor v;
995 obj->Iterate(&v);
996 }
997 return obj->Size();
998}
999
1000
1001void Heap::RebuildRSets() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001002 // By definition, we do not care about remembered set bits in code,
1003 // data, or cell spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001004 map_space_->ClearRSet();
1005 RebuildRSets(map_space_);
1006
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001007 old_pointer_space_->ClearRSet();
1008 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001009
1010 Heap::lo_space_->ClearRSet();
1011 RebuildRSets(lo_space_);
1012}
1013
1014
1015void Heap::RebuildRSets(PagedSpace* space) {
1016 HeapObjectIterator it(space);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001017 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1018 Heap::UpdateRSet(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001019}
1020
1021
1022void Heap::RebuildRSets(LargeObjectSpace* space) {
1023 LargeObjectIterator it(space);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001024 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1025 Heap::UpdateRSet(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001026}
1027
1028
1029#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1030void Heap::RecordCopiedObject(HeapObject* obj) {
1031 bool should_record = false;
1032#ifdef DEBUG
1033 should_record = FLAG_heap_stats;
1034#endif
1035#ifdef ENABLE_LOGGING_AND_PROFILING
1036 should_record = should_record || FLAG_log_gc;
1037#endif
1038 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001039 if (new_space_.Contains(obj)) {
1040 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001041 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001042 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001043 }
1044 }
1045}
1046#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1047
1048
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001049
1050HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001051 HeapObject* target,
1052 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001053 // Copy the content of source to target.
1054 CopyBlock(reinterpret_cast<Object**>(target->address()),
1055 reinterpret_cast<Object**>(source->address()),
1056 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001057
kasper.lund7276f142008-07-30 08:49:36 +00001058 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001059 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001062 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001063 RecordCopiedObject(target);
1064#endif
1065
1066 return target;
1067}
1068
1069
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001070static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001071 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001072 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001073 InstanceType type = map->instance_type();
1074 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
1075 ASSERT(object->IsString() && !object->IsSymbol());
1076 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001077}
1078
1079
1080void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1081 ASSERT(InFromSpace(object));
1082 MapWord first_word = object->map_word();
1083 ASSERT(!first_word.IsForwardingAddress());
1084
1085 // Optimization: Bypass flattened ConsString objects.
1086 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001087 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001088 *p = object;
1089 // After patching *p we have to repeat the checks that object is in the
1090 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001091 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +00001092 first_word = object->map_word();
1093 if (first_word.IsForwardingAddress()) {
1094 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001095 return;
1096 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001097 }
1098
kasper.lund7276f142008-07-30 08:49:36 +00001099 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001100 // We rely on live objects in new space to be at least two pointers,
1101 // so we can store the from-space address and map pointer of promoted
1102 // objects in the to space.
1103 ASSERT(object_size >= 2 * kPointerSize);
1104
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001105 // If the object should be promoted, we try to copy it to old space.
1106 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001107 Object* result;
1108 if (object_size > MaxObjectSizeInPagedSpace()) {
1109 result = lo_space_->AllocateRawFixedArray(object_size);
1110 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001111 // Save the from-space object pointer and its map pointer at the
1112 // top of the to space to be swept and copied later. Write the
1113 // forwarding address over the map word of the from-space
1114 // object.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001115 HeapObject* target = HeapObject::cast(result);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001116 promotion_queue.insert(object, first_word.ToMap());
1117 object->set_map_word(MapWord::FromForwardingAddress(target));
1118
1119 // Give the space allocated for the result a proper map by
1120 // treating it as a free list node (not linked into the free
1121 // list).
1122 FreeListNode* node = FreeListNode::FromAddress(target->address());
1123 node->set_size(object_size);
1124
1125 *p = target;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001126 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001127 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001128 } else {
1129 OldSpace* target_space = Heap::TargetSpace(object);
1130 ASSERT(target_space == Heap::old_pointer_space_ ||
1131 target_space == Heap::old_data_space_);
1132 result = target_space->AllocateRaw(object_size);
1133 if (!result->IsFailure()) {
1134 HeapObject* target = HeapObject::cast(result);
1135 if (target_space == Heap::old_pointer_space_) {
1136 // Save the from-space object pointer and its map pointer at the
1137 // top of the to space to be swept and copied later. Write the
1138 // forwarding address over the map word of the from-space
1139 // object.
1140 promotion_queue.insert(object, first_word.ToMap());
1141 object->set_map_word(MapWord::FromForwardingAddress(target));
1142
1143 // Give the space allocated for the result a proper map by
1144 // treating it as a free list node (not linked into the free
1145 // list).
1146 FreeListNode* node = FreeListNode::FromAddress(target->address());
1147 node->set_size(object_size);
1148
1149 *p = target;
1150 } else {
1151 // Objects promoted to the data space can be copied immediately
1152 // and not revisited---we will never sweep that space for
1153 // pointers and the copied objects do not contain pointers to
1154 // new space objects.
1155 *p = MigrateObject(object, target, object_size);
1156#ifdef DEBUG
1157 VerifyNonPointerSpacePointersVisitor v;
1158 (*p)->Iterate(&v);
1159#endif
1160 }
1161 return;
1162 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001163 }
1164 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001165 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001166 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001167 // Failed allocation at this point is utterly unexpected.
1168 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001169 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1170}
1171
1172
1173void Heap::ScavengePointer(HeapObject** p) {
1174 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001175}
1176
1177
1178Object* Heap::AllocatePartialMap(InstanceType instance_type,
1179 int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001180 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001181 if (result->IsFailure()) return result;
1182
1183 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001184 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001185 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1186 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001187 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001188 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001189 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001190 reinterpret_cast<Map*>(result)->set_bit_field(0);
1191 reinterpret_cast<Map*>(result)->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001192 return result;
1193}
1194
1195
1196Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001197 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001198 if (result->IsFailure()) return result;
1199
1200 Map* map = reinterpret_cast<Map*>(result);
1201 map->set_map(meta_map());
1202 map->set_instance_type(instance_type);
1203 map->set_prototype(null_value());
1204 map->set_constructor(null_value());
1205 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001206 map->set_inobject_properties(0);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001207 map->set_pre_allocated_property_fields(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001208 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001209 map->set_code_cache(empty_fixed_array());
1210 map->set_unused_property_fields(0);
1211 map->set_bit_field(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001212 map->set_bit_field2(1 << Map::kIsExtensible);
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00001213
1214 // If the map object is aligned fill the padding area with Smi 0 objects.
1215 if (Map::kPadStart < Map::kSize) {
1216 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1217 0,
1218 Map::kSize - Map::kPadStart);
1219 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001220 return map;
1221}
1222
1223
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001224const Heap::StringTypeTable Heap::string_type_table[] = {
1225#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1226 {type, size, k##camel_name##MapRootIndex},
1227 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1228#undef STRING_TYPE_ELEMENT
1229};
1230
1231
1232const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1233#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1234 {contents, k##name##RootIndex},
1235 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1236#undef CONSTANT_SYMBOL_ELEMENT
1237};
1238
1239
1240const Heap::StructTable Heap::struct_table[] = {
1241#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1242 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1243 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1244#undef STRUCT_TABLE_ELEMENT
1245};
1246
1247
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001248bool Heap::CreateInitialMaps() {
1249 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1250 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001251 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001252 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1253 set_meta_map(new_meta_map);
1254 new_meta_map->set_map(new_meta_map);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001255
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001256 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001257 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001258 set_fixed_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001259
1260 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1261 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001262 set_oddball_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001263
1264 // Allocate the empty array
1265 obj = AllocateEmptyFixedArray();
1266 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001267 set_empty_fixed_array(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001268
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001269 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001270 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001271 set_null_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001272
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001273 // Allocate the empty descriptor array.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001274 obj = AllocateEmptyFixedArray();
1275 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001276 set_empty_descriptor_array(DescriptorArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001277
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001278 // Fix the instance_descriptors for the existing maps.
1279 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001280 meta_map()->set_code_cache(empty_fixed_array());
1281
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001282 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001283 fixed_array_map()->set_code_cache(empty_fixed_array());
1284
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001285 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001286 oddball_map()->set_code_cache(empty_fixed_array());
1287
1288 // Fix prototype object for existing maps.
1289 meta_map()->set_prototype(null_value());
1290 meta_map()->set_constructor(null_value());
1291
1292 fixed_array_map()->set_prototype(null_value());
1293 fixed_array_map()->set_constructor(null_value());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001294
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001295 oddball_map()->set_prototype(null_value());
1296 oddball_map()->set_constructor(null_value());
1297
1298 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1299 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001300 set_heap_number_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001301
1302 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1303 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001304 set_proxy_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001305
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001306 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1307 const StringTypeTable& entry = string_type_table[i];
1308 obj = AllocateMap(entry.type, entry.size);
1309 if (obj->IsFailure()) return false;
1310 roots_[entry.index] = Map::cast(obj);
1311 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001312
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001313 obj = AllocateMap(STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001314 if (obj->IsFailure()) return false;
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001315 set_undetectable_string_map(Map::cast(obj));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001316 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001317
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001318 obj = AllocateMap(ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001319 if (obj->IsFailure()) return false;
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001320 set_undetectable_ascii_string_map(Map::cast(obj));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001321 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001322
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001323 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001324 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001325 set_byte_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001326
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001327 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1328 if (obj->IsFailure()) return false;
1329 set_pixel_array_map(Map::cast(obj));
1330
ager@chromium.org3811b432009-10-28 14:53:37 +00001331 obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1332 ExternalArray::kAlignedSize);
1333 if (obj->IsFailure()) return false;
1334 set_external_byte_array_map(Map::cast(obj));
1335
1336 obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1337 ExternalArray::kAlignedSize);
1338 if (obj->IsFailure()) return false;
1339 set_external_unsigned_byte_array_map(Map::cast(obj));
1340
1341 obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1342 ExternalArray::kAlignedSize);
1343 if (obj->IsFailure()) return false;
1344 set_external_short_array_map(Map::cast(obj));
1345
1346 obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1347 ExternalArray::kAlignedSize);
1348 if (obj->IsFailure()) return false;
1349 set_external_unsigned_short_array_map(Map::cast(obj));
1350
1351 obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1352 ExternalArray::kAlignedSize);
1353 if (obj->IsFailure()) return false;
1354 set_external_int_array_map(Map::cast(obj));
1355
1356 obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1357 ExternalArray::kAlignedSize);
1358 if (obj->IsFailure()) return false;
1359 set_external_unsigned_int_array_map(Map::cast(obj));
1360
1361 obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1362 ExternalArray::kAlignedSize);
1363 if (obj->IsFailure()) return false;
1364 set_external_float_array_map(Map::cast(obj));
1365
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001366 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1367 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001368 set_code_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001369
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001370 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1371 JSGlobalPropertyCell::kSize);
1372 if (obj->IsFailure()) return false;
1373 set_global_property_cell_map(Map::cast(obj));
1374
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001375 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1376 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001377 set_one_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001378
1379 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1380 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001381 set_two_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001382
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001383 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1384 const StructTable& entry = struct_table[i];
1385 obj = AllocateMap(entry.type, entry.size);
1386 if (obj->IsFailure()) return false;
1387 roots_[entry.index] = Map::cast(obj);
1388 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389
ager@chromium.org236ad962008-09-25 09:45:57 +00001390 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001391 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001392 set_hash_table_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001393
ager@chromium.org236ad962008-09-25 09:45:57 +00001394 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001395 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001396 set_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001397
ager@chromium.org236ad962008-09-25 09:45:57 +00001398 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001400 set_catch_context_map(Map::cast(obj));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001401
1402 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1403 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001404 set_global_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405
1406 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1407 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001408 set_boilerplate_function_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409
1410 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1411 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001412 set_shared_function_info_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001413
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001414 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001415 return true;
1416}
1417
1418
1419Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1420 // Statically ensure that it is safe to allocate heap numbers in paged
1421 // spaces.
1422 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001423 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001424
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001425 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001426 if (result->IsFailure()) return result;
1427
1428 HeapObject::cast(result)->set_map(heap_number_map());
1429 HeapNumber::cast(result)->set_value(value);
1430 return result;
1431}
1432
1433
1434Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001435 // Use general version, if we're forced to always allocate.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001436 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1437
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438 // This version of AllocateHeapNumber is optimized for
1439 // allocation in new space.
1440 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1441 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001442 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001443 if (result->IsFailure()) return result;
1444 HeapObject::cast(result)->set_map(heap_number_map());
1445 HeapNumber::cast(result)->set_value(value);
1446 return result;
1447}
1448
1449
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001450Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001451 Object* result = AllocateRawCell();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001452 if (result->IsFailure()) return result;
1453 HeapObject::cast(result)->set_map(global_property_cell_map());
1454 JSGlobalPropertyCell::cast(result)->set_value(value);
1455 return result;
1456}
1457
1458
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001459Object* Heap::CreateOddball(Map* map,
1460 const char* to_string,
1461 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001462 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463 if (result->IsFailure()) return result;
1464 return Oddball::cast(result)->Initialize(to_string, to_number);
1465}
1466
1467
1468bool Heap::CreateApiObjects() {
1469 Object* obj;
1470
1471 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1472 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001473 set_neander_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001474
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001475 obj = Heap::AllocateJSObjectFromMap(neander_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001476 if (obj->IsFailure()) return false;
1477 Object* elements = AllocateFixedArray(2);
1478 if (elements->IsFailure()) return false;
1479 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1480 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001481 set_message_listeners(JSObject::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001482
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001483 return true;
1484}
1485
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001486
1487void Heap::CreateCEntryStub() {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001488 CEntryStub stub(1);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001489 set_c_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001490}
1491
1492
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001493#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1494void Heap::CreateRegExpCEntryStub() {
1495 RegExpCEntryStub stub;
1496 set_re_c_entry_code(*stub.GetCode());
1497}
1498#endif
1499
1500
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001501void Heap::CreateCEntryDebugBreakStub() {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001502 DebuggerStatementStub stub;
1503 set_debugger_statement_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001504}
1505
1506
1507void Heap::CreateJSEntryStub() {
1508 JSEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001509 set_js_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001510}
1511
1512
1513void Heap::CreateJSConstructEntryStub() {
1514 JSConstructEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001515 set_js_construct_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001516}
1517
1518
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001519void Heap::CreateFixedStubs() {
1520 // Here we create roots for fixed stubs. They are needed at GC
1521 // for cooking and uncooking (check out frames.cc).
1522 // The eliminates the need for doing dictionary lookup in the
1523 // stub cache for these stubs.
1524 HandleScope scope;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001525 // gcc-4.4 has problem generating correct code of following snippet:
1526 // { CEntryStub stub;
1527 // c_entry_code_ = *stub.GetCode();
1528 // }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001529 // { DebuggerStatementStub stub;
1530 // debugger_statement_code_ = *stub.GetCode();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001531 // }
1532 // To workaround the problem, make separate functions without inlining.
1533 Heap::CreateCEntryStub();
1534 Heap::CreateCEntryDebugBreakStub();
1535 Heap::CreateJSEntryStub();
1536 Heap::CreateJSConstructEntryStub();
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001537#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1538 Heap::CreateRegExpCEntryStub();
1539#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001540}
1541
1542
1543bool Heap::CreateInitialObjects() {
1544 Object* obj;
1545
1546 // The -0 value must be set before NumberFromDouble works.
1547 obj = AllocateHeapNumber(-0.0, TENURED);
1548 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001549 set_minus_zero_value(obj);
1550 ASSERT(signbit(minus_zero_value()->Number()) != 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001551
1552 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1553 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001554 set_nan_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001555
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001556 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001557 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001558 set_undefined_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559 ASSERT(!InNewSpace(undefined_value()));
1560
1561 // Allocate initial symbol table.
1562 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1563 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001564 // Don't use set_symbol_table() due to asserts.
1565 roots_[kSymbolTableRootIndex] = obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566
1567 // Assign the print strings for oddballs after creating symboltable.
1568 Object* symbol = LookupAsciiSymbol("undefined");
1569 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001570 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1571 Oddball::cast(undefined_value())->set_to_number(nan_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001572
1573 // Assign the print strings for oddballs after creating symboltable.
1574 symbol = LookupAsciiSymbol("null");
1575 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001576 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1577 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001578
1579 // Allocate the null_value
1580 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1581 if (obj->IsFailure()) return false;
1582
1583 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1584 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001585 set_true_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001586
1587 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1588 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001589 set_false_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001590
1591 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1592 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001593 set_the_hole_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001594
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001595 obj = CreateOddball(
1596 oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
1597 if (obj->IsFailure()) return false;
1598 set_no_interceptor_result_sentinel(obj);
1599
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001600 obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
1601 if (obj->IsFailure()) return false;
1602 set_termination_exception(obj);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001603
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001604 // Allocate the empty string.
1605 obj = AllocateRawAsciiString(0, TENURED);
1606 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001607 set_empty_string(String::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001609 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1610 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1611 if (obj->IsFailure()) return false;
1612 roots_[constant_symbol_table[i].index] = String::cast(obj);
1613 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001615 // Allocate the hidden symbol which is used to identify the hidden properties
1616 // in JSObjects. The hash code has a special value so that it will not match
1617 // the empty string when searching for the property. It cannot be part of the
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001618 // loop above because it needs to be allocated manually with the special
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001619 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1620 // that it will always be at the first entry in property descriptors.
1621 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1622 if (obj->IsFailure()) return false;
1623 hidden_symbol_ = String::cast(obj);
1624
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001625 // Allocate the proxy for __proto__.
1626 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1627 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001628 set_prototype_accessors(Proxy::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001630 // Allocate the code_stubs dictionary. The initial size is set to avoid
1631 // expanding the dictionary during bootstrapping.
1632 obj = NumberDictionary::Allocate(128);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001634 set_code_stubs(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001635
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001636 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1637 // is set to avoid expanding the dictionary during bootstrapping.
1638 obj = NumberDictionary::Allocate(64);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001639 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001640 set_non_monomorphic_cache(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001641
1642 CreateFixedStubs();
1643
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001644 if (InitializeNumberStringCache()->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001645
1646 // Allocate cache for single character strings.
1647 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1648 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001649 set_single_character_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001650
1651 // Allocate cache for external strings pointing to native source code.
1652 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1653 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001654 set_natives_source_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001655
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001656 // Handling of script id generation is in Factory::NewScript.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001657 set_last_script_id(undefined_value());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001658
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001659 // Initialize keyed lookup cache.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001660 KeyedLookupCache::Clear();
1661
1662 // Initialize context slot cache.
1663 ContextSlotCache::Clear();
1664
1665 // Initialize descriptor cache.
1666 DescriptorLookupCache::Clear();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001667
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001668 // Initialize compilation cache.
1669 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001670
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001671 return true;
1672}
1673
1674
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001675Object* Heap::InitializeNumberStringCache() {
1676 // Compute the size of the number string cache based on the max heap size.
1677 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
1678 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
1679 int number_string_cache_size = max_semispace_size_ / 512;
1680 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
1681 Object* obj = AllocateFixedArray(number_string_cache_size * 2);
1682 if (!obj->IsFailure()) set_number_string_cache(FixedArray::cast(obj));
1683 return obj;
1684}
1685
1686
1687void Heap::FlushNumberStringCache() {
1688 // Flush the number to string cache.
1689 int len = number_string_cache()->length();
1690 for (int i = 0; i < len; i++) {
1691 number_string_cache()->set_undefined(i);
1692 }
1693}
1694
1695
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001696static inline int double_get_hash(double d) {
1697 DoubleRepresentation rep(d);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001698 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001699}
1700
1701
1702static inline int smi_get_hash(Smi* smi) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001703 return smi->value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001704}
1705
1706
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001707Object* Heap::GetNumberStringCache(Object* number) {
1708 int hash;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001709 int mask = (number_string_cache()->length() >> 1) - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710 if (number->IsSmi()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001711 hash = smi_get_hash(Smi::cast(number)) & mask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001713 hash = double_get_hash(number->Number()) & mask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001714 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001715 Object* key = number_string_cache()->get(hash * 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001716 if (key == number) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001717 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001718 } else if (key->IsHeapNumber() &&
1719 number->IsHeapNumber() &&
1720 key->Number() == number->Number()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001721 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 }
1723 return undefined_value();
1724}
1725
1726
1727void Heap::SetNumberStringCache(Object* number, String* string) {
1728 int hash;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001729 int mask = (number_string_cache()->length() >> 1) - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001730 if (number->IsSmi()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001731 hash = smi_get_hash(Smi::cast(number)) & mask;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001732 number_string_cache()->set(hash * 2, Smi::cast(number));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001733 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001734 hash = double_get_hash(number->Number()) & mask;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001735 number_string_cache()->set(hash * 2, number);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001736 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001737 number_string_cache()->set(hash * 2 + 1, string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001738}
1739
1740
1741Object* Heap::SmiOrNumberFromDouble(double value,
1742 bool new_object,
1743 PretenureFlag pretenure) {
1744 // We need to distinguish the minus zero value and this cannot be
1745 // done after conversion to int. Doing this by comparing bit
1746 // patterns is faster than using fpclassify() et al.
1747 static const DoubleRepresentation plus_zero(0.0);
1748 static const DoubleRepresentation minus_zero(-0.0);
1749 static const DoubleRepresentation nan(OS::nan_value());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001750 ASSERT(minus_zero_value() != NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001751 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1752
1753 DoubleRepresentation rep(value);
1754 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1755 if (rep.bits == minus_zero.bits) {
1756 return new_object ? AllocateHeapNumber(-0.0, pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001757 : minus_zero_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001758 }
1759 if (rep.bits == nan.bits) {
1760 return new_object
1761 ? AllocateHeapNumber(OS::nan_value(), pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001762 : nan_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001763 }
1764
1765 // Try to represent the value as a tagged small integer.
1766 int int_value = FastD2I(value);
1767 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1768 return Smi::FromInt(int_value);
1769 }
1770
1771 // Materialize the value in the heap.
1772 return AllocateHeapNumber(value, pretenure);
1773}
1774
1775
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001776Object* Heap::NumberToString(Object* number) {
1777 Object* cached = GetNumberStringCache(number);
1778 if (cached != undefined_value()) {
1779 return cached;
1780 }
1781
1782 char arr[100];
1783 Vector<char> buffer(arr, ARRAY_SIZE(arr));
1784 const char* str;
1785 if (number->IsSmi()) {
1786 int num = Smi::cast(number)->value();
1787 str = IntToCString(num, buffer);
1788 } else {
1789 double num = HeapNumber::cast(number)->value();
1790 str = DoubleToCString(num, buffer);
1791 }
1792 Object* result = AllocateStringFromAscii(CStrVector(str));
1793
1794 if (!result->IsFailure()) {
1795 SetNumberStringCache(number, String::cast(result));
1796 }
1797 return result;
1798}
1799
1800
ager@chromium.org3811b432009-10-28 14:53:37 +00001801Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
1802 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
1803}
1804
1805
1806Heap::RootListIndex Heap::RootIndexForExternalArrayType(
1807 ExternalArrayType array_type) {
1808 switch (array_type) {
1809 case kExternalByteArray:
1810 return kExternalByteArrayMapRootIndex;
1811 case kExternalUnsignedByteArray:
1812 return kExternalUnsignedByteArrayMapRootIndex;
1813 case kExternalShortArray:
1814 return kExternalShortArrayMapRootIndex;
1815 case kExternalUnsignedShortArray:
1816 return kExternalUnsignedShortArrayMapRootIndex;
1817 case kExternalIntArray:
1818 return kExternalIntArrayMapRootIndex;
1819 case kExternalUnsignedIntArray:
1820 return kExternalUnsignedIntArrayMapRootIndex;
1821 case kExternalFloatArray:
1822 return kExternalFloatArrayMapRootIndex;
1823 default:
1824 UNREACHABLE();
1825 return kUndefinedValueRootIndex;
1826 }
1827}
1828
1829
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001830Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1831 return SmiOrNumberFromDouble(value,
1832 true /* number object must be new */,
1833 pretenure);
1834}
1835
1836
1837Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1838 return SmiOrNumberFromDouble(value,
1839 false /* use preallocated NaN, -0.0 */,
1840 pretenure);
1841}
1842
1843
1844Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1845 // Statically ensure that it is safe to allocate proxies in paged spaces.
1846 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001847 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001848 Object* result = Allocate(proxy_map(), space);
1849 if (result->IsFailure()) return result;
1850
1851 Proxy::cast(result)->set_proxy(proxy);
1852 return result;
1853}
1854
1855
1856Object* Heap::AllocateSharedFunctionInfo(Object* name) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001857 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001858 if (result->IsFailure()) return result;
1859
1860 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1861 share->set_name(name);
1862 Code* illegal = Builtins::builtin(Builtins::Illegal);
1863 share->set_code(illegal);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001864 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1865 share->set_construct_stub(construct_stub);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001866 share->set_expected_nof_properties(0);
1867 share->set_length(0);
1868 share->set_formal_parameter_count(0);
1869 share->set_instance_class_name(Object_symbol());
1870 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001871 share->set_script(undefined_value());
1872 share->set_start_position_and_type(0);
1873 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001874 share->set_inferred_name(empty_string());
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001875 share->set_compiler_hints(0);
1876 share->set_this_property_assignments_count(0);
1877 share->set_this_property_assignments(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001878 return result;
1879}
1880
1881
ager@chromium.org6141cbe2009-11-20 12:14:52 +00001882// Returns true for a character in a range. Both limits are inclusive.
1883static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
1884 // This makes uses of the the unsigned wraparound.
1885 return character - from <= to - from;
1886}
1887
1888
1889static inline Object* MakeOrFindTwoCharacterString(uint32_t c1, uint32_t c2) {
1890 String* symbol;
1891 // Numeric strings have a different hash algorithm not known by
1892 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
1893 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
1894 Heap::symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
1895 return symbol;
1896 // Now we know the length is 2, we might as well make use of that fact
1897 // when building the new string.
1898 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
1899 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
1900 Object* result = Heap::AllocateRawAsciiString(2);
1901 if (result->IsFailure()) return result;
1902 char* dest = SeqAsciiString::cast(result)->GetChars();
1903 dest[0] = c1;
1904 dest[1] = c2;
1905 return result;
1906 } else {
1907 Object* result = Heap::AllocateRawTwoByteString(2);
1908 if (result->IsFailure()) return result;
1909 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1910 dest[0] = c1;
1911 dest[1] = c2;
1912 return result;
1913 }
1914}
1915
1916
ager@chromium.org3e875802009-06-29 08:26:34 +00001917Object* Heap::AllocateConsString(String* first, String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001918 int first_length = first->length();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001919 if (first_length == 0) {
1920 return second;
1921 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001922
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001923 int second_length = second->length();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001924 if (second_length == 0) {
1925 return first;
1926 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001927
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001928 int length = first_length + second_length;
ager@chromium.org6141cbe2009-11-20 12:14:52 +00001929
1930 // Optimization for 2-byte strings often used as keys in a decompression
1931 // dictionary. Check whether we already have the string in the symbol
1932 // table to prevent creation of many unneccesary strings.
1933 if (length == 2) {
1934 unsigned c1 = first->Get(0);
1935 unsigned c2 = second->Get(0);
1936 return MakeOrFindTwoCharacterString(c1, c2);
1937 }
1938
ager@chromium.org5ec48922009-05-05 07:25:34 +00001939 bool is_ascii = first->IsAsciiRepresentation()
1940 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001941
ager@chromium.org3e875802009-06-29 08:26:34 +00001942 // Make sure that an out of memory exception is thrown if the length
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001943 // of the new cons string is too large.
1944 if (length > String::kMaxLength || length < 0) {
ager@chromium.org3e875802009-06-29 08:26:34 +00001945 Top::context()->mark_out_of_memory();
1946 return Failure::OutOfMemoryException();
1947 }
1948
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001949 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001950 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001951 ASSERT(first->IsFlat());
1952 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001953 if (is_ascii) {
1954 Object* result = AllocateRawAsciiString(length);
1955 if (result->IsFailure()) return result;
1956 // Copy the characters into the new object.
1957 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org3e875802009-06-29 08:26:34 +00001958 // Copy first part.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001959 const char* src;
1960 if (first->IsExternalString()) {
1961 src = ExternalAsciiString::cast(first)->resource()->data();
1962 } else {
1963 src = SeqAsciiString::cast(first)->GetChars();
1964 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001965 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1966 // Copy second part.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001967 if (second->IsExternalString()) {
1968 src = ExternalAsciiString::cast(second)->resource()->data();
1969 } else {
1970 src = SeqAsciiString::cast(second)->GetChars();
1971 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001972 for (int i = 0; i < second_length; i++) *dest++ = src[i];
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001973 return result;
1974 } else {
1975 Object* result = AllocateRawTwoByteString(length);
1976 if (result->IsFailure()) return result;
1977 // Copy the characters into the new object.
1978 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001979 String::WriteToFlat(first, dest, 0, first_length);
1980 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001981 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001982 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001983 }
1984
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001985 Map* map = is_ascii ? cons_ascii_string_map() : cons_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001986
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001987 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001988 if (result->IsFailure()) return result;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001989
1990 AssertNoAllocation no_gc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001991 ConsString* cons_string = ConsString::cast(result);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001992 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001993 cons_string->set_length(length);
1994 cons_string->set_hash_field(String::kEmptyHashField);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001995 cons_string->set_first(first, mode);
1996 cons_string->set_second(second, mode);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001997 return result;
1998}
1999
2000
ager@chromium.org870a0b62008-11-04 11:43:05 +00002001Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00002002 int start,
2003 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002004 int length = end - start;
2005
ager@chromium.org7c537e22008-10-16 08:43:32 +00002006 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002007 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002008 buffer->Get(start));
ager@chromium.org6141cbe2009-11-20 12:14:52 +00002009 } else if (length == 2) {
2010 // Optimization for 2-byte strings often used as keys in a decompression
2011 // dictionary. Check whether we already have the string in the symbol
2012 // table to prevent creation of many unneccesary strings.
2013 unsigned c1 = buffer->Get(start);
2014 unsigned c2 = buffer->Get(start + 1);
2015 return MakeOrFindTwoCharacterString(c1, c2);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002016 }
2017
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002018 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002019 if (!buffer->IsFlat()) {
2020 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00002021 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002022
ager@chromium.org5ec48922009-05-05 07:25:34 +00002023 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002024 ? AllocateRawAsciiString(length)
2025 : AllocateRawTwoByteString(length);
2026 if (result->IsFailure()) return result;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002027 String* string_result = String::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002028
2029 // Copy the characters into the new object.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002030 if (buffer->IsAsciiRepresentation()) {
2031 ASSERT(string_result->IsAsciiRepresentation());
2032 char* dest = SeqAsciiString::cast(string_result)->GetChars();
2033 String::WriteToFlat(buffer, dest, start, end);
2034 } else {
2035 ASSERT(string_result->IsTwoByteRepresentation());
2036 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
2037 String::WriteToFlat(buffer, dest, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002038 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002039
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002040 return result;
2041}
2042
2043
2044Object* Heap::AllocateExternalStringFromAscii(
2045 ExternalAsciiString::Resource* resource) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002046 size_t length = resource->length();
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002047 if (length > static_cast<size_t>(String::kMaxLength)) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002048 Top::context()->mark_out_of_memory();
2049 return Failure::OutOfMemoryException();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002050 }
2051
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002052 Map* map = external_ascii_string_map();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002053 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002054 if (result->IsFailure()) return result;
2055
2056 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002057 external_string->set_length(static_cast<int>(length));
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002058 external_string->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002059 external_string->set_resource(resource);
2060
2061 return result;
2062}
2063
2064
2065Object* Heap::AllocateExternalStringFromTwoByte(
2066 ExternalTwoByteString::Resource* resource) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002067 size_t length = resource->length();
2068 if (length > static_cast<size_t>(String::kMaxLength)) {
2069 Top::context()->mark_out_of_memory();
2070 return Failure::OutOfMemoryException();
2071 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002072
2073 Map* map = Heap::external_string_map();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002074 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002075 if (result->IsFailure()) return result;
2076
2077 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002078 external_string->set_length(static_cast<int>(length));
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002079 external_string->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080 external_string->set_resource(resource);
2081
2082 return result;
2083}
2084
2085
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002086Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002087 if (code <= String::kMaxAsciiCharCode) {
2088 Object* value = Heap::single_character_string_cache()->get(code);
2089 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002090
2091 char buffer[1];
2092 buffer[0] = static_cast<char>(code);
2093 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
2094
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002095 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002096 Heap::single_character_string_cache()->set(code, result);
2097 return result;
2098 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002099
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002100 Object* result = Heap::AllocateRawTwoByteString(1);
2101 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00002102 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002103 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002104 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002105}
2106
2107
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002108Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002109 if (length < 0 || length > ByteArray::kMaxLength) {
2110 return Failure::OutOfMemoryException();
2111 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002112 if (pretenure == NOT_TENURED) {
2113 return AllocateByteArray(length);
2114 }
2115 int size = ByteArray::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002116 Object* result = (size <= MaxObjectSizeInPagedSpace())
2117 ? old_data_space_->AllocateRaw(size)
2118 : lo_space_->AllocateRaw(size);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002119 if (result->IsFailure()) return result;
2120
2121 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2122 reinterpret_cast<Array*>(result)->set_length(length);
2123 return result;
2124}
2125
2126
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002127Object* Heap::AllocateByteArray(int length) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002128 if (length < 0 || length > ByteArray::kMaxLength) {
2129 return Failure::OutOfMemoryException();
2130 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002131 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002132 AllocationSpace space =
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002133 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002134 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002135 if (result->IsFailure()) return result;
2136
2137 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2138 reinterpret_cast<Array*>(result)->set_length(length);
2139 return result;
2140}
2141
2142
ager@chromium.org6f10e412009-02-13 10:11:16 +00002143void Heap::CreateFillerObjectAt(Address addr, int size) {
2144 if (size == 0) return;
2145 HeapObject* filler = HeapObject::FromAddress(addr);
2146 if (size == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002147 filler->set_map(Heap::one_pointer_filler_map());
ager@chromium.org6f10e412009-02-13 10:11:16 +00002148 } else {
2149 filler->set_map(Heap::byte_array_map());
2150 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2151 }
2152}
2153
2154
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002155Object* Heap::AllocatePixelArray(int length,
2156 uint8_t* external_pointer,
2157 PretenureFlag pretenure) {
2158 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002159 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002160 if (result->IsFailure()) return result;
2161
2162 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
2163 reinterpret_cast<PixelArray*>(result)->set_length(length);
2164 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
2165
2166 return result;
2167}
2168
2169
ager@chromium.org3811b432009-10-28 14:53:37 +00002170Object* Heap::AllocateExternalArray(int length,
2171 ExternalArrayType array_type,
2172 void* external_pointer,
2173 PretenureFlag pretenure) {
2174 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org3811b432009-10-28 14:53:37 +00002175 Object* result = AllocateRaw(ExternalArray::kAlignedSize,
2176 space,
2177 OLD_DATA_SPACE);
ager@chromium.org3811b432009-10-28 14:53:37 +00002178 if (result->IsFailure()) return result;
2179
2180 reinterpret_cast<ExternalArray*>(result)->set_map(
2181 MapForExternalArrayType(array_type));
2182 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2183 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2184 external_pointer);
2185
2186 return result;
2187}
2188
2189
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002190Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002191 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002192 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002193 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002194 // Compute size
2195 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
2196 int sinfo_size = 0;
2197 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
2198 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002199 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002200 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002201 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002202 result = lo_space_->AllocateRawCode(obj_size);
2203 } else {
2204 result = code_space_->AllocateRaw(obj_size);
2205 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002206
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002207 if (result->IsFailure()) return result;
2208
2209 // Initialize the object
2210 HeapObject::cast(result)->set_map(code_map());
2211 Code* code = Code::cast(result);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002212 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002213 code->set_instruction_size(desc.instr_size);
2214 code->set_relocation_size(desc.reloc_size);
2215 code->set_sinfo_size(sinfo_size);
2216 code->set_flags(flags);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002217 // Allow self references to created code object by patching the handle to
2218 // point to the newly allocated Code object.
2219 if (!self_reference.is_null()) {
2220 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002221 }
2222 // Migrate generated code.
2223 // The generated code can contain Object** values (typically from handles)
2224 // that are dereferenced during the copy to point directly to the actual heap
2225 // objects. These pointers can include references to the code object itself,
2226 // through the self_reference parameter.
2227 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002228 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
2229
2230#ifdef DEBUG
2231 code->Verify();
2232#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002233 return code;
2234}
2235
2236
2237Object* Heap::CopyCode(Code* code) {
2238 // Allocate an object the same size as the code object.
2239 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002240 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002241 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002242 result = lo_space_->AllocateRawCode(obj_size);
2243 } else {
2244 result = code_space_->AllocateRaw(obj_size);
2245 }
2246
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002247 if (result->IsFailure()) return result;
2248
2249 // Copy code object.
2250 Address old_addr = code->address();
2251 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002252 CopyBlock(reinterpret_cast<Object**>(new_addr),
2253 reinterpret_cast<Object**>(old_addr),
2254 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002255 // Relocate the copy.
2256 Code* new_code = Code::cast(result);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002257 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002258 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002259 return new_code;
2260}
2261
2262
2263Object* Heap::Allocate(Map* map, AllocationSpace space) {
2264 ASSERT(gc_state_ == NOT_IN_GC);
2265 ASSERT(map->instance_type() != MAP_TYPE);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002266 // If allocation failures are disallowed, we may allocate in a different
2267 // space when new space is full and the object is not a large object.
2268 AllocationSpace retry_space =
2269 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
2270 Object* result =
2271 AllocateRaw(map->instance_size(), space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002272 if (result->IsFailure()) return result;
2273 HeapObject::cast(result)->set_map(map);
ager@chromium.org3811b432009-10-28 14:53:37 +00002274#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002275 ProducerHeapProfile::RecordJSObjectAllocation(result);
ager@chromium.org3811b432009-10-28 14:53:37 +00002276#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002277 return result;
2278}
2279
2280
2281Object* Heap::InitializeFunction(JSFunction* function,
2282 SharedFunctionInfo* shared,
2283 Object* prototype) {
2284 ASSERT(!prototype->IsMap());
2285 function->initialize_properties();
2286 function->initialize_elements();
2287 function->set_shared(shared);
2288 function->set_prototype_or_initial_map(prototype);
2289 function->set_context(undefined_value());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002290 function->set_literals(empty_fixed_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002291 return function;
2292}
2293
2294
2295Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002296 // Allocate the prototype. Make sure to use the object function
2297 // from the function's context, since the function can be from a
2298 // different context.
2299 JSFunction* object_function =
2300 function->context()->global_context()->object_function();
2301 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002302 if (prototype->IsFailure()) return prototype;
2303 // When creating the prototype for the function we must set its
2304 // constructor to the function.
2305 Object* result =
2306 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2307 function,
2308 DONT_ENUM);
2309 if (result->IsFailure()) return result;
2310 return prototype;
2311}
2312
2313
2314Object* Heap::AllocateFunction(Map* function_map,
2315 SharedFunctionInfo* shared,
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002316 Object* prototype,
2317 PretenureFlag pretenure) {
2318 AllocationSpace space =
2319 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2320 Object* result = Allocate(function_map, space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002321 if (result->IsFailure()) return result;
2322 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2323}
2324
2325
2326Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002327 // To get fast allocation and map sharing for arguments objects we
2328 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002329
2330 // This calls Copy directly rather than using Heap::AllocateRaw so we
2331 // duplicate the check here.
2332 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2333
2334 JSObject* boilerplate =
2335 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002336
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002337 // Check that the size of the boilerplate matches our
2338 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
2339 // on the size being a known constant.
2340 ASSERT(kArgumentsObjectSize == boilerplate->map()->instance_size());
2341
2342 // Do the allocation.
2343 Object* result =
2344 AllocateRaw(kArgumentsObjectSize, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002345 if (result->IsFailure()) return result;
2346
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002347 // Copy the content. The arguments boilerplate doesn't have any
2348 // fields that point to new space so it's safe to skip the write
2349 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002350 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2351 reinterpret_cast<Object**>(boilerplate->address()),
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002352 kArgumentsObjectSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002353
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002354 // Set the two properties.
2355 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002356 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002357 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2358 Smi::FromInt(length),
2359 SKIP_WRITE_BARRIER);
2360
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002361 // Check the state of the object
2362 ASSERT(JSObject::cast(result)->HasFastProperties());
2363 ASSERT(JSObject::cast(result)->HasFastElements());
2364
2365 return result;
2366}
2367
2368
2369Object* Heap::AllocateInitialMap(JSFunction* fun) {
2370 ASSERT(!fun->has_initial_map());
2371
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002372 // First create a new map with the size and number of in-object properties
2373 // suggested by the function.
2374 int instance_size = fun->shared()->CalculateInstanceSize();
2375 int in_object_properties = fun->shared()->CalculateInObjectProperties();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002376 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002377 if (map_obj->IsFailure()) return map_obj;
2378
2379 // Fetch or allocate prototype.
2380 Object* prototype;
2381 if (fun->has_instance_prototype()) {
2382 prototype = fun->instance_prototype();
2383 } else {
2384 prototype = AllocateFunctionPrototype(fun);
2385 if (prototype->IsFailure()) return prototype;
2386 }
2387 Map* map = Map::cast(map_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002388 map->set_inobject_properties(in_object_properties);
2389 map->set_unused_property_fields(in_object_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002390 map->set_prototype(prototype);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002391
2392 // If the function has only simple this property assignments add field
2393 // descriptors for these to the initial map as the object cannot be
2394 // constructed without having these properties.
2395 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
ager@chromium.org3811b432009-10-28 14:53:37 +00002396 if (fun->shared()->has_only_simple_this_property_assignments() &&
2397 fun->shared()->this_property_assignments_count() > 0) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002398 int count = fun->shared()->this_property_assignments_count();
2399 if (count > in_object_properties) {
2400 count = in_object_properties;
2401 }
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00002402 Object* descriptors_obj = DescriptorArray::Allocate(count);
2403 if (descriptors_obj->IsFailure()) return descriptors_obj;
2404 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002405 for (int i = 0; i < count; i++) {
2406 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2407 ASSERT(name->IsSymbol());
2408 FieldDescriptor field(name, i, NONE);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002409 field.SetEnumerationIndex(i);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002410 descriptors->Set(i, &field);
2411 }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002412 descriptors->SetNextEnumerationIndex(count);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002413 descriptors->Sort();
2414 map->set_instance_descriptors(descriptors);
2415 map->set_pre_allocated_property_fields(count);
2416 map->set_unused_property_fields(in_object_properties - count);
2417 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002418 return map;
2419}
2420
2421
2422void Heap::InitializeJSObjectFromMap(JSObject* obj,
2423 FixedArray* properties,
2424 Map* map) {
2425 obj->set_properties(properties);
2426 obj->initialize_elements();
2427 // TODO(1240798): Initialize the object's body using valid initial values
2428 // according to the object's initial map. For example, if the map's
2429 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2430 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2431 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2432 // verification code has to cope with (temporarily) invalid objects. See
2433 // for example, JSArray::JSArrayVerify).
2434 obj->InitializeBody(map->instance_size());
2435}
2436
2437
2438Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2439 // JSFunctions should be allocated using AllocateFunction to be
2440 // properly initialized.
2441 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2442
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002443 // Both types of globla objects should be allocated using
2444 // AllocateGloblaObject to be properly initialized.
2445 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2446 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2447
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002448 // Allocate the backing storage for the properties.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002449 int prop_size =
2450 map->pre_allocated_property_fields() +
2451 map->unused_property_fields() -
2452 map->inobject_properties();
2453 ASSERT(prop_size >= 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002454 Object* properties = AllocateFixedArray(prop_size, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002455 if (properties->IsFailure()) return properties;
2456
2457 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002458 AllocationSpace space =
2459 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002460 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002461 Object* obj = Allocate(map, space);
2462 if (obj->IsFailure()) return obj;
2463
2464 // Initialize the JSObject.
2465 InitializeJSObjectFromMap(JSObject::cast(obj),
2466 FixedArray::cast(properties),
2467 map);
2468 return obj;
2469}
2470
2471
2472Object* Heap::AllocateJSObject(JSFunction* constructor,
2473 PretenureFlag pretenure) {
2474 // Allocate the initial map if absent.
2475 if (!constructor->has_initial_map()) {
2476 Object* initial_map = AllocateInitialMap(constructor);
2477 if (initial_map->IsFailure()) return initial_map;
2478 constructor->set_initial_map(Map::cast(initial_map));
2479 Map::cast(initial_map)->set_constructor(constructor);
2480 }
2481 // Allocate the object based on the constructors initial map.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002482 Object* result =
2483 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2484 // Make sure result is NOT a global object if valid.
2485 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2486 return result;
2487}
2488
2489
2490Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2491 ASSERT(constructor->has_initial_map());
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002492 Map* map = constructor->initial_map();
2493
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002494 // Make sure no field properties are described in the initial map.
2495 // This guarantees us that normalizing the properties does not
2496 // require us to change property values to JSGlobalPropertyCells.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002497 ASSERT(map->NextFreePropertyIndex() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002498
2499 // Make sure we don't have a ton of pre-allocated slots in the
2500 // global objects. They will be unused once we normalize the object.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002501 ASSERT(map->unused_property_fields() == 0);
2502 ASSERT(map->inobject_properties() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002503
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002504 // Initial size of the backing store to avoid resize of the storage during
2505 // bootstrapping. The size differs between the JS global object ad the
2506 // builtins object.
2507 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002508
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002509 // Allocate a dictionary object for backing storage.
2510 Object* obj =
2511 StringDictionary::Allocate(
2512 map->NumberOfDescribedProperties() * 2 + initial_size);
2513 if (obj->IsFailure()) return obj;
2514 StringDictionary* dictionary = StringDictionary::cast(obj);
2515
2516 // The global object might be created from an object template with accessors.
2517 // Fill these accessors into the dictionary.
2518 DescriptorArray* descs = map->instance_descriptors();
2519 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2520 PropertyDetails details = descs->GetDetails(i);
2521 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2522 PropertyDetails d =
2523 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2524 Object* value = descs->GetCallbacksObject(i);
2525 value = Heap::AllocateJSGlobalPropertyCell(value);
2526 if (value->IsFailure()) return value;
2527
2528 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2529 if (result->IsFailure()) return result;
2530 dictionary = StringDictionary::cast(result);
2531 }
2532
2533 // Allocate the global object and initialize it with the backing store.
2534 obj = Allocate(map, OLD_POINTER_SPACE);
2535 if (obj->IsFailure()) return obj;
2536 JSObject* global = JSObject::cast(obj);
2537 InitializeJSObjectFromMap(global, dictionary, map);
2538
2539 // Create a new map for the global object.
2540 obj = map->CopyDropDescriptors();
2541 if (obj->IsFailure()) return obj;
2542 Map* new_map = Map::cast(obj);
2543
2544 // Setup the global object as a normalized object.
2545 global->set_map(new_map);
2546 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2547 global->set_properties(dictionary);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002548
2549 // Make sure result is a global object with properties in dictionary.
2550 ASSERT(global->IsGlobalObject());
2551 ASSERT(!global->HasFastProperties());
2552 return global;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002553}
2554
2555
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002556Object* Heap::CopyJSObject(JSObject* source) {
2557 // Never used to copy functions. If functions need to be copied we
2558 // have to be careful to clear the literals array.
2559 ASSERT(!source->IsJSFunction());
2560
2561 // Make the clone.
2562 Map* map = source->map();
2563 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002564 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002565
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002566 // If we're forced to always allocate, we use the general allocation
2567 // functions which may leave us with an object in old space.
2568 if (always_allocate()) {
2569 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2570 if (clone->IsFailure()) return clone;
2571 Address clone_address = HeapObject::cast(clone)->address();
2572 CopyBlock(reinterpret_cast<Object**>(clone_address),
2573 reinterpret_cast<Object**>(source->address()),
2574 object_size);
2575 // Update write barrier for all fields that lie beyond the header.
2576 for (int offset = JSObject::kHeaderSize;
2577 offset < object_size;
2578 offset += kPointerSize) {
2579 RecordWrite(clone_address, offset);
2580 }
2581 } else {
2582 clone = new_space_.AllocateRaw(object_size);
2583 if (clone->IsFailure()) return clone;
2584 ASSERT(Heap::InNewSpace(clone));
2585 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002586 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002587 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2588 reinterpret_cast<Object**>(source->address()),
2589 object_size);
2590 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002591
2592 FixedArray* elements = FixedArray::cast(source->elements());
2593 FixedArray* properties = FixedArray::cast(source->properties());
2594 // Update elements if necessary.
2595 if (elements->length()> 0) {
2596 Object* elem = CopyFixedArray(elements);
2597 if (elem->IsFailure()) return elem;
2598 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2599 }
2600 // Update properties if necessary.
2601 if (properties->length() > 0) {
2602 Object* prop = CopyFixedArray(properties);
2603 if (prop->IsFailure()) return prop;
2604 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2605 }
2606 // Return the new clone.
ager@chromium.org3811b432009-10-28 14:53:37 +00002607#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002608 ProducerHeapProfile::RecordJSObjectAllocation(clone);
ager@chromium.org3811b432009-10-28 14:53:37 +00002609#endif
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002610 return clone;
2611}
2612
2613
2614Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2615 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002616 // Allocate initial map if absent.
2617 if (!constructor->has_initial_map()) {
2618 Object* initial_map = AllocateInitialMap(constructor);
2619 if (initial_map->IsFailure()) return initial_map;
2620 constructor->set_initial_map(Map::cast(initial_map));
2621 Map::cast(initial_map)->set_constructor(constructor);
2622 }
2623
2624 Map* map = constructor->initial_map();
2625
2626 // Check that the already allocated object has the same size as
2627 // objects allocated using the constructor.
2628 ASSERT(map->instance_size() == object->map()->instance_size());
2629
2630 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002631 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002632 Object* properties = AllocateFixedArray(prop_size, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002633 if (properties->IsFailure()) return properties;
2634
2635 // Reset the map for the object.
2636 object->set_map(constructor->initial_map());
2637
2638 // Reinitialize the object from the constructor map.
2639 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2640 return object;
2641}
2642
2643
2644Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2645 PretenureFlag pretenure) {
2646 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2647 if (result->IsFailure()) return result;
2648
2649 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002650 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002651 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002652 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002653 }
2654 return result;
2655}
2656
2657
2658Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2659 PretenureFlag pretenure) {
2660 // Count the number of characters in the UTF-8 string and check if
2661 // it is an ASCII string.
2662 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2663 decoder->Reset(string.start(), string.length());
2664 int chars = 0;
2665 bool is_ascii = true;
2666 while (decoder->has_more()) {
2667 uc32 r = decoder->GetNext();
2668 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2669 chars++;
2670 }
2671
2672 // If the string is ascii, we do not need to convert the characters
2673 // since UTF8 is backwards compatible with ascii.
2674 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2675
2676 Object* result = AllocateRawTwoByteString(chars, pretenure);
2677 if (result->IsFailure()) return result;
2678
2679 // Convert and copy the characters into the new object.
2680 String* string_result = String::cast(result);
2681 decoder->Reset(string.start(), string.length());
2682 for (int i = 0; i < chars; i++) {
2683 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002684 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002685 }
2686 return result;
2687}
2688
2689
2690Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2691 PretenureFlag pretenure) {
2692 // Check if the string is an ASCII string.
2693 int i = 0;
2694 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2695
2696 Object* result;
2697 if (i == string.length()) { // It's an ASCII string.
2698 result = AllocateRawAsciiString(string.length(), pretenure);
2699 } else { // It's not an ASCII string.
2700 result = AllocateRawTwoByteString(string.length(), pretenure);
2701 }
2702 if (result->IsFailure()) return result;
2703
2704 // Copy the characters into the new object, which may be either ASCII or
2705 // UTF-16.
2706 String* string_result = String::cast(result);
2707 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002708 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002709 }
2710 return result;
2711}
2712
2713
2714Map* Heap::SymbolMapForString(String* string) {
2715 // If the string is in new space it cannot be used as a symbol.
2716 if (InNewSpace(string)) return NULL;
2717
2718 // Find the corresponding symbol map for strings.
2719 Map* map = string->map();
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002720 if (map == ascii_string_map()) return ascii_symbol_map();
2721 if (map == string_map()) return symbol_map();
2722 if (map == cons_string_map()) return cons_symbol_map();
2723 if (map == cons_ascii_string_map()) return cons_ascii_symbol_map();
2724 if (map == external_string_map()) return external_symbol_map();
2725 if (map == external_ascii_string_map()) return external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002726
2727 // No match found.
2728 return NULL;
2729}
2730
2731
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002732Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2733 int chars,
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002734 uint32_t hash_field) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002735 ASSERT(chars >= 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002736 // Ensure the chars matches the number of characters in the buffer.
2737 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2738 // Determine whether the string is ascii.
2739 bool is_ascii = true;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002740 while (buffer->has_more()) {
2741 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
2742 is_ascii = false;
2743 break;
2744 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002745 }
2746 buffer->Rewind();
2747
2748 // Compute map and object size.
2749 int size;
2750 Map* map;
2751
2752 if (is_ascii) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002753 if (chars > SeqAsciiString::kMaxLength) {
2754 return Failure::OutOfMemoryException();
2755 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002756 map = ascii_symbol_map();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002757 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002758 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002759 if (chars > SeqTwoByteString::kMaxLength) {
2760 return Failure::OutOfMemoryException();
2761 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002762 map = symbol_map();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002763 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002764 }
2765
2766 // Allocate string.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002767 Object* result = (size > MaxObjectSizeInPagedSpace())
2768 ? lo_space_->AllocateRaw(size)
2769 : old_data_space_->AllocateRaw(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002770 if (result->IsFailure()) return result;
2771
2772 reinterpret_cast<HeapObject*>(result)->set_map(map);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002773 // Set length and hash fields of the allocated string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002774 String* answer = String::cast(result);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002775 answer->set_length(chars);
2776 answer->set_hash_field(hash_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002777
ager@chromium.org870a0b62008-11-04 11:43:05 +00002778 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002779
2780 // Fill in the characters.
2781 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002782 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002783 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002784 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002785}
2786
2787
2788Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002789 if (length < 0 || length > SeqAsciiString::kMaxLength) {
2790 return Failure::OutOfMemoryException();
2791 }
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002792
ager@chromium.org7c537e22008-10-16 08:43:32 +00002793 int size = SeqAsciiString::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002794 ASSERT(size <= SeqAsciiString::kMaxSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002795
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002796 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2797 AllocationSpace retry_space = OLD_DATA_SPACE;
2798
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002799 if (space == NEW_SPACE) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002800 if (size > kMaxObjectSizeInNewSpace) {
2801 // Allocate in large object space, retry space will be ignored.
2802 space = LO_SPACE;
2803 } else if (size > MaxObjectSizeInPagedSpace()) {
2804 // Allocate in new space, retry in large object space.
2805 retry_space = LO_SPACE;
2806 }
2807 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2808 space = LO_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002809 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002810 Object* result = AllocateRaw(size, space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002811 if (result->IsFailure()) return result;
2812
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002813 // Partially initialize the object.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002814 HeapObject::cast(result)->set_map(ascii_string_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002815 String::cast(result)->set_length(length);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002816 String::cast(result)->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002817 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2818 return result;
2819}
2820
2821
2822Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002823 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
2824 return Failure::OutOfMemoryException();
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002825 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002826 int size = SeqTwoByteString::SizeFor(length);
2827 ASSERT(size <= SeqTwoByteString::kMaxSize);
2828 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2829 AllocationSpace retry_space = OLD_DATA_SPACE;
2830
2831 if (space == NEW_SPACE) {
2832 if (size > kMaxObjectSizeInNewSpace) {
2833 // Allocate in large object space, retry space will be ignored.
2834 space = LO_SPACE;
2835 } else if (size > MaxObjectSizeInPagedSpace()) {
2836 // Allocate in new space, retry in large object space.
2837 retry_space = LO_SPACE;
2838 }
2839 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2840 space = LO_SPACE;
2841 }
2842 Object* result = AllocateRaw(size, space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002843 if (result->IsFailure()) return result;
2844
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002845 // Partially initialize the object.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002846 HeapObject::cast(result)->set_map(string_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002847 String::cast(result)->set_length(length);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002848 String::cast(result)->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002849 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2850 return result;
2851}
2852
2853
2854Object* Heap::AllocateEmptyFixedArray() {
2855 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002856 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002857 if (result->IsFailure()) return result;
2858 // Initialize the object.
2859 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2860 reinterpret_cast<Array*>(result)->set_length(0);
2861 return result;
2862}
2863
2864
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002865Object* Heap::AllocateRawFixedArray(int length) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002866 if (length < 0 || length > FixedArray::kMaxLength) {
2867 return Failure::OutOfMemoryException();
2868 }
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002869 // Use the general function if we're forced to always allocate.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002870 if (always_allocate()) return AllocateFixedArray(length, TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002871 // Allocate the raw data for a fixed array.
2872 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002873 return size <= kMaxObjectSizeInNewSpace
2874 ? new_space_.AllocateRaw(size)
2875 : lo_space_->AllocateRawFixedArray(size);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002876}
2877
2878
2879Object* Heap::CopyFixedArray(FixedArray* src) {
2880 int len = src->length();
2881 Object* obj = AllocateRawFixedArray(len);
2882 if (obj->IsFailure()) return obj;
2883 if (Heap::InNewSpace(obj)) {
2884 HeapObject* dst = HeapObject::cast(obj);
2885 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2886 reinterpret_cast<Object**>(src->address()),
2887 FixedArray::SizeFor(len));
2888 return obj;
2889 }
2890 HeapObject::cast(obj)->set_map(src->map());
2891 FixedArray* result = FixedArray::cast(obj);
2892 result->set_length(len);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002893
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002894 // Copy the content
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002895 AssertNoAllocation no_gc;
2896 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002897 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2898 return result;
2899}
2900
2901
2902Object* Heap::AllocateFixedArray(int length) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002903 ASSERT(length >= 0);
ager@chromium.org32912102009-01-16 10:38:43 +00002904 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002905 Object* result = AllocateRawFixedArray(length);
2906 if (!result->IsFailure()) {
2907 // Initialize header.
2908 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2909 FixedArray* array = FixedArray::cast(result);
2910 array->set_length(length);
2911 Object* value = undefined_value();
2912 // Initialize body.
2913 for (int index = 0; index < length; index++) {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002914 ASSERT(!Heap::InNewSpace(value)); // value = undefined
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002915 array->set(index, value, SKIP_WRITE_BARRIER);
2916 }
2917 }
2918 return result;
2919}
2920
2921
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002922Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002923 ASSERT(length >= 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002924 ASSERT(empty_fixed_array()->IsFixedArray());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002925 if (length < 0 || length > FixedArray::kMaxLength) {
2926 return Failure::OutOfMemoryException();
2927 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002928 if (length == 0) return empty_fixed_array();
2929
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002930 AllocationSpace space =
2931 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002932 int size = FixedArray::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002933 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
2934 // Too big for new space.
2935 space = LO_SPACE;
2936 } else if (space == OLD_POINTER_SPACE &&
2937 size > MaxObjectSizeInPagedSpace()) {
2938 // Too big for old pointer space.
2939 space = LO_SPACE;
2940 }
2941
2942 // Specialize allocation for the space.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002943 Object* result = Failure::OutOfMemoryException();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002944 if (space == NEW_SPACE) {
2945 // We cannot use Heap::AllocateRaw() because it will not properly
2946 // allocate extra remembered set bits if always_allocate() is true and
2947 // new space allocation fails.
2948 result = new_space_.AllocateRaw(size);
2949 if (result->IsFailure() && always_allocate()) {
2950 if (size <= MaxObjectSizeInPagedSpace()) {
2951 result = old_pointer_space_->AllocateRaw(size);
2952 } else {
2953 result = lo_space_->AllocateRawFixedArray(size);
2954 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002955 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002956 } else if (space == OLD_POINTER_SPACE) {
2957 result = old_pointer_space_->AllocateRaw(size);
2958 } else {
2959 ASSERT(space == LO_SPACE);
2960 result = lo_space_->AllocateRawFixedArray(size);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002961 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002962 if (result->IsFailure()) return result;
2963
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002964 // Initialize the object.
2965 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2966 FixedArray* array = FixedArray::cast(result);
2967 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002968 Object* value = undefined_value();
2969 for (int index = 0; index < length; index++) {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002970 ASSERT(!Heap::InNewSpace(value)); // value = undefined
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002971 array->set(index, value, SKIP_WRITE_BARRIER);
2972 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002973 return array;
2974}
2975
2976
2977Object* Heap::AllocateFixedArrayWithHoles(int length) {
2978 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002979 Object* result = AllocateRawFixedArray(length);
2980 if (!result->IsFailure()) {
2981 // Initialize header.
2982 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2983 FixedArray* array = FixedArray::cast(result);
2984 array->set_length(length);
2985 // Initialize body.
2986 Object* value = the_hole_value();
2987 for (int index = 0; index < length; index++) {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002988 ASSERT(!Heap::InNewSpace(value)); // value = the hole
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002989 array->set(index, value, SKIP_WRITE_BARRIER);
2990 }
2991 }
2992 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002993}
2994
2995
2996Object* Heap::AllocateHashTable(int length) {
2997 Object* result = Heap::AllocateFixedArray(length);
2998 if (result->IsFailure()) return result;
2999 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00003000 ASSERT(result->IsHashTable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003001 return result;
3002}
3003
3004
3005Object* Heap::AllocateGlobalContext() {
3006 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
3007 if (result->IsFailure()) return result;
3008 Context* context = reinterpret_cast<Context*>(result);
3009 context->set_map(global_context_map());
3010 ASSERT(context->IsGlobalContext());
3011 ASSERT(result->IsContext());
3012 return result;
3013}
3014
3015
3016Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
3017 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
3018 Object* result = Heap::AllocateFixedArray(length);
3019 if (result->IsFailure()) return result;
3020 Context* context = reinterpret_cast<Context*>(result);
3021 context->set_map(context_map());
3022 context->set_closure(function);
3023 context->set_fcontext(context);
3024 context->set_previous(NULL);
3025 context->set_extension(NULL);
3026 context->set_global(function->context()->global());
3027 ASSERT(!context->IsGlobalContext());
3028 ASSERT(context->is_function_context());
3029 ASSERT(result->IsContext());
3030 return result;
3031}
3032
3033
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003034Object* Heap::AllocateWithContext(Context* previous,
3035 JSObject* extension,
3036 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003037 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
3038 if (result->IsFailure()) return result;
3039 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003040 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003041 context->set_closure(previous->closure());
3042 context->set_fcontext(previous->fcontext());
3043 context->set_previous(previous);
3044 context->set_extension(extension);
3045 context->set_global(previous->global());
3046 ASSERT(!context->IsGlobalContext());
3047 ASSERT(!context->is_function_context());
3048 ASSERT(result->IsContext());
3049 return result;
3050}
3051
3052
3053Object* Heap::AllocateStruct(InstanceType type) {
3054 Map* map;
3055 switch (type) {
3056#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
3057STRUCT_LIST(MAKE_CASE)
3058#undef MAKE_CASE
3059 default:
3060 UNREACHABLE();
3061 return Failure::InternalError();
3062 }
3063 int size = map->instance_size();
3064 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003065 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003066 Object* result = Heap::Allocate(map, space);
3067 if (result->IsFailure()) return result;
3068 Struct::cast(result)->InitializeBody(size);
3069 return result;
3070}
3071
3072
ager@chromium.org96c75b52009-08-26 09:13:16 +00003073bool Heap::IdleNotification() {
ager@chromium.orga1645e22009-09-09 19:27:10 +00003074 static const int kIdlesBeforeScavenge = 4;
3075 static const int kIdlesBeforeMarkSweep = 7;
3076 static const int kIdlesBeforeMarkCompact = 8;
ager@chromium.org96c75b52009-08-26 09:13:16 +00003077 static int number_idle_notifications = 0;
3078 static int last_gc_count = gc_count_;
3079
3080 bool finished = false;
3081
3082 if (last_gc_count == gc_count_) {
3083 number_idle_notifications++;
3084 } else {
3085 number_idle_notifications = 0;
3086 last_gc_count = gc_count_;
3087 }
3088
ager@chromium.orga1645e22009-09-09 19:27:10 +00003089 if (number_idle_notifications == kIdlesBeforeScavenge) {
3090 CollectGarbage(0, NEW_SPACE);
3091 new_space_.Shrink();
ager@chromium.org96c75b52009-08-26 09:13:16 +00003092 last_gc_count = gc_count_;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003093
3094 } else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00003095 // Before doing the mark-sweep collections we clear the
3096 // compilation cache to avoid hanging on to source code and
3097 // generated code for cached functions.
3098 CompilationCache::Clear();
3099
ager@chromium.orga1645e22009-09-09 19:27:10 +00003100 CollectAllGarbage(false);
3101 new_space_.Shrink();
3102 last_gc_count = gc_count_;
3103
3104 } else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
3105 CollectAllGarbage(true);
3106 new_space_.Shrink();
3107 last_gc_count = gc_count_;
3108 number_idle_notifications = 0;
3109 finished = true;
ager@chromium.org96c75b52009-08-26 09:13:16 +00003110 }
3111
3112 // Uncommit unused memory in new space.
3113 Heap::UncommitFromSpace();
3114 return finished;
3115}
3116
3117
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003118#ifdef DEBUG
3119
3120void Heap::Print() {
3121 if (!HasBeenSetup()) return;
3122 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003123 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003124 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3125 space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003126}
3127
3128
3129void Heap::ReportCodeStatistics(const char* title) {
3130 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
3131 PagedSpace::ResetCodeStatistics();
3132 // We do not look for code in new space, map space, or old space. If code
3133 // somehow ends up in those spaces, we would miss it here.
3134 code_space_->CollectCodeStatistics();
3135 lo_space_->CollectCodeStatistics();
3136 PagedSpace::ReportCodeStatistics();
3137}
3138
3139
3140// This function expects that NewSpace's allocated objects histogram is
3141// populated (via a call to CollectStatistics or else as a side effect of a
3142// just-completed scavenge collection).
3143void Heap::ReportHeapStatistics(const char* title) {
3144 USE(title);
3145 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
3146 title, gc_count_);
3147 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00003148 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
3149 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003150
3151 PrintF("\n");
3152 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
3153 GlobalHandles::PrintStats();
3154 PrintF("\n");
3155
3156 PrintF("Heap statistics : ");
3157 MemoryAllocator::ReportStatistics();
3158 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003159 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003160 PrintF("Old pointer space : ");
3161 old_pointer_space_->ReportStatistics();
3162 PrintF("Old data space : ");
3163 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003164 PrintF("Code space : ");
3165 code_space_->ReportStatistics();
3166 PrintF("Map space : ");
3167 map_space_->ReportStatistics();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003168 PrintF("Cell space : ");
3169 cell_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003170 PrintF("Large object space : ");
3171 lo_space_->ReportStatistics();
3172 PrintF(">>>>>> ========================================= >>>>>>\n");
3173}
3174
3175#endif // DEBUG
3176
3177bool Heap::Contains(HeapObject* value) {
3178 return Contains(value->address());
3179}
3180
3181
3182bool Heap::Contains(Address addr) {
3183 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3184 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003185 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003186 old_pointer_space_->Contains(addr) ||
3187 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003188 code_space_->Contains(addr) ||
3189 map_space_->Contains(addr) ||
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003190 cell_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003191 lo_space_->SlowContains(addr));
3192}
3193
3194
3195bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
3196 return InSpace(value->address(), space);
3197}
3198
3199
3200bool Heap::InSpace(Address addr, AllocationSpace space) {
3201 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3202 if (!HasBeenSetup()) return false;
3203
3204 switch (space) {
3205 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003206 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003207 case OLD_POINTER_SPACE:
3208 return old_pointer_space_->Contains(addr);
3209 case OLD_DATA_SPACE:
3210 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003211 case CODE_SPACE:
3212 return code_space_->Contains(addr);
3213 case MAP_SPACE:
3214 return map_space_->Contains(addr);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003215 case CELL_SPACE:
3216 return cell_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003217 case LO_SPACE:
3218 return lo_space_->SlowContains(addr);
3219 }
3220
3221 return false;
3222}
3223
3224
3225#ifdef DEBUG
3226void Heap::Verify() {
3227 ASSERT(HasBeenSetup());
3228
3229 VerifyPointersVisitor visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003230 IterateRoots(&visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003231
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003232 new_space_.Verify();
3233
3234 VerifyPointersAndRSetVisitor rset_visitor;
3235 old_pointer_space_->Verify(&rset_visitor);
3236 map_space_->Verify(&rset_visitor);
3237
3238 VerifyPointersVisitor no_rset_visitor;
3239 old_data_space_->Verify(&no_rset_visitor);
3240 code_space_->Verify(&no_rset_visitor);
3241 cell_space_->Verify(&no_rset_visitor);
3242
3243 lo_space_->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003244}
3245#endif // DEBUG
3246
3247
3248Object* Heap::LookupSymbol(Vector<const char> string) {
3249 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003250 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003251 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003252 // Can't use set_symbol_table because SymbolTable::cast knows that
3253 // SymbolTable is a singleton and checks for identity.
3254 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003255 ASSERT(symbol != NULL);
3256 return symbol;
3257}
3258
3259
3260Object* Heap::LookupSymbol(String* string) {
3261 if (string->IsSymbol()) return string;
3262 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003263 Object* new_table = symbol_table()->LookupString(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003264 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003265 // Can't use set_symbol_table because SymbolTable::cast knows that
3266 // SymbolTable is a singleton and checks for identity.
3267 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003268 ASSERT(symbol != NULL);
3269 return symbol;
3270}
3271
3272
ager@chromium.org7c537e22008-10-16 08:43:32 +00003273bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
3274 if (string->IsSymbol()) {
3275 *symbol = string;
3276 return true;
3277 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003278 return symbol_table()->LookupSymbolIfExists(string, symbol);
ager@chromium.org7c537e22008-10-16 08:43:32 +00003279}
3280
3281
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003282#ifdef DEBUG
3283void Heap::ZapFromSpace() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003284 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003285 for (Address a = new_space_.FromSpaceLow();
3286 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003287 a += kPointerSize) {
3288 Memory::Address_at(a) = kFromSpaceZapValue;
3289 }
3290}
3291#endif // DEBUG
3292
3293
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003294int Heap::IterateRSetRange(Address object_start,
3295 Address object_end,
3296 Address rset_start,
3297 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003298 Address object_address = object_start;
3299 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003300 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003301
3302 // Loop over all the pointers in [object_start, object_end).
3303 while (object_address < object_end) {
3304 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003305 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003306 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003307 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003308 // Do not dereference pointers at or past object_end.
3309 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3310 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003311 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003312 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3313 }
3314 // If this pointer does not need to be remembered anymore, clear
3315 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003316 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003317 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003318 }
3319 object_address += kPointerSize;
3320 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003321 // Update the remembered set if it has changed.
3322 if (result_rset != rset_word) {
3323 Memory::uint32_at(rset_address) = result_rset;
3324 }
3325 } else {
3326 // No bits in the word were set. This is the common case.
3327 object_address += kPointerSize * kBitsPerInt;
3328 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003329 rset_address += kIntSize;
3330 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003331 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003332}
3333
3334
3335void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3336 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003337 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003338
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003339 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3340 "V8.RSetPaged",
3341 0,
3342 Page::kObjectAreaSize / kPointerSize,
3343 30);
3344
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003345 PageIterator it(space, PageIterator::PAGES_IN_USE);
3346 while (it.has_next()) {
3347 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003348 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3349 page->RSetStart(), copy_object_func);
3350 if (paged_rset_histogram != NULL) {
3351 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3352 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003353 }
3354}
3355
3356
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003357void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
3358 IterateStrongRoots(v, mode);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003359 IterateWeakRoots(v, mode);
3360}
3361
3362
3363void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003364 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
ager@chromium.org3811b432009-10-28 14:53:37 +00003365 v->Synchronize("symbol_table");
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003366 if (mode != VISIT_ALL_IN_SCAVENGE) {
3367 // Scavenge collections have special processing for this.
3368 ExternalStringTable::Iterate(v);
3369 }
3370 v->Synchronize("external_string_table");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003371}
3372
3373
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003374void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003375 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
ager@chromium.org3811b432009-10-28 14:53:37 +00003376 v->Synchronize("strong_root_list");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003377
ager@chromium.org3b45ab52009-03-19 22:21:34 +00003378 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
ager@chromium.org3811b432009-10-28 14:53:37 +00003379 v->Synchronize("symbol");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003380
3381 Bootstrapper::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003382 v->Synchronize("bootstrapper");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003383 Top::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003384 v->Synchronize("top");
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00003385 Relocatable::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003386 v->Synchronize("relocatable");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003387
3388#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003389 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003390#endif
ager@chromium.org3811b432009-10-28 14:53:37 +00003391 v->Synchronize("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003392 CompilationCache::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003393 v->Synchronize("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003394
3395 // Iterate over local handles in handle scopes.
3396 HandleScopeImplementer::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003397 v->Synchronize("handlescope");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003398
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003399 // Iterate over the builtin code objects and code stubs in the
3400 // heap. Note that it is not necessary to iterate over code objects
3401 // on scavenge collections.
3402 if (mode != VISIT_ALL_IN_SCAVENGE) {
3403 Builtins::IterateBuiltins(v);
3404 }
ager@chromium.org3811b432009-10-28 14:53:37 +00003405 v->Synchronize("builtins");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003406
3407 // Iterate over global handles.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003408 if (mode == VISIT_ONLY_STRONG) {
3409 GlobalHandles::IterateStrongRoots(v);
3410 } else {
3411 GlobalHandles::IterateAllRoots(v);
3412 }
ager@chromium.org3811b432009-10-28 14:53:37 +00003413 v->Synchronize("globalhandles");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003414
3415 // Iterate over pointers being held by inactive threads.
3416 ThreadManager::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003417 v->Synchronize("threadmanager");
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003418
3419 // Iterate over the pointers the Serialization/Deserialization code is
3420 // holding.
3421 // During garbage collection this keeps the partial snapshot cache alive.
3422 // During deserialization of the startup snapshot this creates the partial
3423 // snapshot cache and deserializes the objects it refers to. During
3424 // serialization this does nothing, since the partial snapshot cache is
3425 // empty. However the next thing we do is create the partial snapshot,
3426 // filling up the partial snapshot cache with objects it needs as we go.
3427 SerializerDeserializer::Iterate(v);
3428 // We don't do a v->Synchronize call here, because in debug mode that will
3429 // output a flag to the snapshot. However at this point the serializer and
3430 // deserializer are deliberately a little unsynchronized (see above) so the
3431 // checking of the sync flag in the snapshot would fail.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003432}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003433
3434
3435// Flag is set when the heap has been configured. The heap can be repeatedly
3436// configured through the API until it is setup.
3437static bool heap_configured = false;
3438
3439// TODO(1236194): Since the heap size is configurable on the command line
3440// and through the API, we should gracefully handle the case that the heap
3441// size is not big enough to fit all the initial objects.
ager@chromium.org3811b432009-10-28 14:53:37 +00003442bool Heap::ConfigureHeap(int max_semispace_size, int max_old_gen_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003443 if (HasBeenSetup()) return false;
3444
ager@chromium.org3811b432009-10-28 14:53:37 +00003445 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
3446
3447 if (Snapshot::IsEnabled()) {
3448 // If we are using a snapshot we always reserve the default amount
3449 // of memory for each semispace because code in the snapshot has
3450 // write-barrier code that relies on the size and alignment of new
3451 // space. We therefore cannot use a larger max semispace size
3452 // than the default reserved semispace size.
3453 if (max_semispace_size_ > reserved_semispace_size_) {
3454 max_semispace_size_ = reserved_semispace_size_;
3455 }
3456 } else {
3457 // If we are not using snapshots we reserve space for the actual
3458 // max semispace size.
3459 reserved_semispace_size_ = max_semispace_size_;
3460 }
3461
3462 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003463
3464 // The new space size must be a power of two to support single-bit testing
3465 // for containment.
ager@chromium.org3811b432009-10-28 14:53:37 +00003466 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
3467 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
3468 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
3469 external_allocation_limit_ = 10 * max_semispace_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003470
3471 // The old generation is paged.
ager@chromium.org3811b432009-10-28 14:53:37 +00003472 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003473
3474 heap_configured = true;
3475 return true;
3476}
3477
3478
kasper.lund7276f142008-07-30 08:49:36 +00003479bool Heap::ConfigureHeapDefault() {
ager@chromium.org3811b432009-10-28 14:53:37 +00003480 return ConfigureHeap(FLAG_max_new_space_size / 2, FLAG_max_old_space_size);
kasper.lund7276f142008-07-30 08:49:36 +00003481}
3482
3483
ager@chromium.org60121232009-12-03 11:25:37 +00003484void Heap::RecordStats(HeapStats* stats) {
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00003485 *stats->start_marker = 0xDECADE00;
3486 *stats->end_marker = 0xDECADE01;
3487 *stats->new_space_size = new_space_.Size();
3488 *stats->new_space_capacity = new_space_.Capacity();
3489 *stats->old_pointer_space_size = old_pointer_space_->Size();
3490 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
3491 *stats->old_data_space_size = old_data_space_->Size();
3492 *stats->old_data_space_capacity = old_data_space_->Capacity();
3493 *stats->code_space_size = code_space_->Size();
3494 *stats->code_space_capacity = code_space_->Capacity();
3495 *stats->map_space_size = map_space_->Size();
3496 *stats->map_space_capacity = map_space_->Capacity();
3497 *stats->cell_space_size = cell_space_->Size();
3498 *stats->cell_space_capacity = cell_space_->Capacity();
3499 *stats->lo_space_size = lo_space_->Size();
ager@chromium.org60121232009-12-03 11:25:37 +00003500 GlobalHandles::RecordStats(stats);
3501}
3502
3503
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003504int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003505 return old_pointer_space_->Size()
3506 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003507 + code_space_->Size()
3508 + map_space_->Size()
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003509 + cell_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003510 + lo_space_->Size();
3511}
3512
3513
kasper.lund7276f142008-07-30 08:49:36 +00003514int Heap::PromotedExternalMemorySize() {
3515 if (amount_of_external_allocated_memory_
3516 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3517 return amount_of_external_allocated_memory_
3518 - amount_of_external_allocated_memory_at_last_global_gc_;
3519}
3520
3521
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003522bool Heap::Setup(bool create_heap_objects) {
3523 // Initialize heap spaces and initial maps and objects. Whenever something
3524 // goes wrong, just return false. The caller should check the results and
3525 // call Heap::TearDown() to release allocated memory.
3526 //
3527 // If the heap is not yet configured (eg, through the API), configure it.
3528 // Configuration is based on the flags new-space-size (really the semispace
3529 // size) and old-space-size if set or the initial values of semispace_size_
3530 // and old_generation_size_ otherwise.
3531 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00003532 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003533 }
3534
ager@chromium.orga1645e22009-09-09 19:27:10 +00003535 // Setup memory allocator and reserve a chunk of memory for new
ager@chromium.org3811b432009-10-28 14:53:37 +00003536 // space. The chunk is double the size of the requested reserved
3537 // new space size to ensure that we can find a pair of semispaces that
3538 // are contiguous and aligned to their size.
3539 if (!MemoryAllocator::Setup(MaxReserved())) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003540 void* chunk =
ager@chromium.org3811b432009-10-28 14:53:37 +00003541 MemoryAllocator::ReserveInitialChunk(4 * reserved_semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003542 if (chunk == NULL) return false;
3543
ager@chromium.orga1645e22009-09-09 19:27:10 +00003544 // Align the pair of semispaces to their size, which must be a power
3545 // of 2.
ager@chromium.orga1645e22009-09-09 19:27:10 +00003546 Address new_space_start =
ager@chromium.org3811b432009-10-28 14:53:37 +00003547 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
3548 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
3549 return false;
3550 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003551
ager@chromium.orga1645e22009-09-09 19:27:10 +00003552 // Initialize old pointer space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003553 old_pointer_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003554 new OldSpace(max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003555 if (old_pointer_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003556 if (!old_pointer_space_->Setup(NULL, 0)) return false;
3557
3558 // Initialize old data space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003559 old_data_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003560 new OldSpace(max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003561 if (old_data_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003562 if (!old_data_space_->Setup(NULL, 0)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003563
3564 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00003565 // generation size. It needs executable memory.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00003566 // On 64-bit platform(s), we put all code objects in a 2 GB range of
3567 // virtual address space, so that they can call each other with near calls.
3568 if (code_range_size_ > 0) {
3569 if (!CodeRange::Setup(code_range_size_)) {
3570 return false;
3571 }
3572 }
3573
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003574 code_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003575 new OldSpace(max_old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003576 if (code_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003577 if (!code_space_->Setup(NULL, 0)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003578
3579 // Initialize map space.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003580 map_space_ = new MapSpace(FLAG_use_big_map_space
3581 ? max_old_generation_size_
kasperl@chromium.orgeac059f2010-01-25 11:02:06 +00003582 : MapSpace::kMaxMapPageIndex * Page::kPageSize,
3583 FLAG_max_map_space_pages,
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003584 MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003585 if (map_space_ == NULL) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003586 if (!map_space_->Setup(NULL, 0)) return false;
3587
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003588 // Initialize global property cell space.
ager@chromium.org3811b432009-10-28 14:53:37 +00003589 cell_space_ = new CellSpace(max_old_generation_size_, CELL_SPACE);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003590 if (cell_space_ == NULL) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003591 if (!cell_space_->Setup(NULL, 0)) return false;
3592
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003593 // The large object code space may contain code or data. We set the memory
3594 // to be non-executable here for safety, but this means we need to enable it
3595 // explicitly when allocating large code objects.
3596 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003597 if (lo_space_ == NULL) return false;
3598 if (!lo_space_->Setup()) return false;
3599
3600 if (create_heap_objects) {
3601 // Create initial maps.
3602 if (!CreateInitialMaps()) return false;
3603 if (!CreateApiObjects()) return false;
3604
3605 // Create initial objects
3606 if (!CreateInitialObjects()) return false;
3607 }
3608
3609 LOG(IntEvent("heap-capacity", Capacity()));
3610 LOG(IntEvent("heap-available", Available()));
3611
ager@chromium.org3811b432009-10-28 14:53:37 +00003612#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00003613 // This should be called only after initial objects have been created.
3614 ProducerHeapProfile::Setup();
ager@chromium.org3811b432009-10-28 14:53:37 +00003615#endif
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00003616
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003617 return true;
3618}
3619
3620
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003621void Heap::SetStackLimits() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003622 // On 64 bit machines, pointers are generally out of range of Smis. We write
3623 // something that looks like an out of range Smi to the GC.
3624
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003625 // Set up the special root array entries containing the stack limits.
3626 // These are actually addresses, but the tag makes the GC ignore it.
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003627 roots_[kStackLimitRootIndex] =
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003628 reinterpret_cast<Object*>(
3629 (StackGuard::jslimit() & ~kSmiTagMask) | kSmiTag);
3630 roots_[kRealStackLimitRootIndex] =
3631 reinterpret_cast<Object*>(
3632 (StackGuard::real_jslimit() & ~kSmiTagMask) | kSmiTag);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003633}
3634
3635
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003636void Heap::TearDown() {
3637 GlobalHandles::TearDown();
3638
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003639 ExternalStringTable::TearDown();
3640
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003641 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003642
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003643 if (old_pointer_space_ != NULL) {
3644 old_pointer_space_->TearDown();
3645 delete old_pointer_space_;
3646 old_pointer_space_ = NULL;
3647 }
3648
3649 if (old_data_space_ != NULL) {
3650 old_data_space_->TearDown();
3651 delete old_data_space_;
3652 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003653 }
3654
3655 if (code_space_ != NULL) {
3656 code_space_->TearDown();
3657 delete code_space_;
3658 code_space_ = NULL;
3659 }
3660
3661 if (map_space_ != NULL) {
3662 map_space_->TearDown();
3663 delete map_space_;
3664 map_space_ = NULL;
3665 }
3666
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003667 if (cell_space_ != NULL) {
3668 cell_space_->TearDown();
3669 delete cell_space_;
3670 cell_space_ = NULL;
3671 }
3672
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003673 if (lo_space_ != NULL) {
3674 lo_space_->TearDown();
3675 delete lo_space_;
3676 lo_space_ = NULL;
3677 }
3678
3679 MemoryAllocator::TearDown();
3680}
3681
3682
3683void Heap::Shrink() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003684 // Try to shrink all paged spaces.
3685 PagedSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003686 for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next())
3687 space->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003688}
3689
3690
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003691#ifdef ENABLE_HEAP_PROTECTION
3692
3693void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003694 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003695 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003696 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3697 space->Protect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003698 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003699}
3700
3701
3702void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003703 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003704 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003705 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3706 space->Unprotect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003707 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003708}
3709
3710#endif
3711
3712
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003713#ifdef DEBUG
3714
3715class PrintHandleVisitor: public ObjectVisitor {
3716 public:
3717 void VisitPointers(Object** start, Object** end) {
3718 for (Object** p = start; p < end; p++)
3719 PrintF(" handle %p to %p\n", p, *p);
3720 }
3721};
3722
3723void Heap::PrintHandles() {
3724 PrintF("Handles:\n");
3725 PrintHandleVisitor v;
3726 HandleScopeImplementer::Iterate(&v);
3727}
3728
3729#endif
3730
3731
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003732Space* AllSpaces::next() {
3733 switch (counter_++) {
3734 case NEW_SPACE:
3735 return Heap::new_space();
3736 case OLD_POINTER_SPACE:
3737 return Heap::old_pointer_space();
3738 case OLD_DATA_SPACE:
3739 return Heap::old_data_space();
3740 case CODE_SPACE:
3741 return Heap::code_space();
3742 case MAP_SPACE:
3743 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003744 case CELL_SPACE:
3745 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003746 case LO_SPACE:
3747 return Heap::lo_space();
3748 default:
3749 return NULL;
3750 }
3751}
3752
3753
3754PagedSpace* PagedSpaces::next() {
3755 switch (counter_++) {
3756 case OLD_POINTER_SPACE:
3757 return Heap::old_pointer_space();
3758 case OLD_DATA_SPACE:
3759 return Heap::old_data_space();
3760 case CODE_SPACE:
3761 return Heap::code_space();
3762 case MAP_SPACE:
3763 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003764 case CELL_SPACE:
3765 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003766 default:
3767 return NULL;
3768 }
3769}
3770
3771
3772
3773OldSpace* OldSpaces::next() {
3774 switch (counter_++) {
3775 case OLD_POINTER_SPACE:
3776 return Heap::old_pointer_space();
3777 case OLD_DATA_SPACE:
3778 return Heap::old_data_space();
3779 case CODE_SPACE:
3780 return Heap::code_space();
3781 default:
3782 return NULL;
3783 }
3784}
3785
3786
kasper.lund7276f142008-07-30 08:49:36 +00003787SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3788}
3789
3790
3791SpaceIterator::~SpaceIterator() {
3792 // Delete active iterator if any.
3793 delete iterator_;
3794}
3795
3796
3797bool SpaceIterator::has_next() {
3798 // Iterate until no more spaces.
3799 return current_space_ != LAST_SPACE;
3800}
3801
3802
3803ObjectIterator* SpaceIterator::next() {
3804 if (iterator_ != NULL) {
3805 delete iterator_;
3806 iterator_ = NULL;
3807 // Move to the next space
3808 current_space_++;
3809 if (current_space_ > LAST_SPACE) {
3810 return NULL;
3811 }
3812 }
3813
3814 // Return iterator for the new current space.
3815 return CreateIterator();
3816}
3817
3818
3819// Create an iterator for the space to iterate.
3820ObjectIterator* SpaceIterator::CreateIterator() {
3821 ASSERT(iterator_ == NULL);
3822
3823 switch (current_space_) {
3824 case NEW_SPACE:
3825 iterator_ = new SemiSpaceIterator(Heap::new_space());
3826 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003827 case OLD_POINTER_SPACE:
3828 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3829 break;
3830 case OLD_DATA_SPACE:
3831 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003832 break;
3833 case CODE_SPACE:
3834 iterator_ = new HeapObjectIterator(Heap::code_space());
3835 break;
3836 case MAP_SPACE:
3837 iterator_ = new HeapObjectIterator(Heap::map_space());
3838 break;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003839 case CELL_SPACE:
3840 iterator_ = new HeapObjectIterator(Heap::cell_space());
3841 break;
kasper.lund7276f142008-07-30 08:49:36 +00003842 case LO_SPACE:
3843 iterator_ = new LargeObjectIterator(Heap::lo_space());
3844 break;
3845 }
3846
3847 // Return the newly allocated iterator;
3848 ASSERT(iterator_ != NULL);
3849 return iterator_;
3850}
3851
3852
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003853HeapIterator::HeapIterator() {
3854 Init();
3855}
3856
3857
3858HeapIterator::~HeapIterator() {
3859 Shutdown();
3860}
3861
3862
3863void HeapIterator::Init() {
3864 // Start the iteration.
3865 space_iterator_ = new SpaceIterator();
3866 object_iterator_ = space_iterator_->next();
3867}
3868
3869
3870void HeapIterator::Shutdown() {
3871 // Make sure the last iterator is deallocated.
3872 delete space_iterator_;
3873 space_iterator_ = NULL;
3874 object_iterator_ = NULL;
3875}
3876
3877
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003878HeapObject* HeapIterator::next() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003879 // No iterator means we are done.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003880 if (object_iterator_ == NULL) return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003881
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003882 if (HeapObject* obj = object_iterator_->next_object()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003883 // If the current iterator has more objects we are fine.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003884 return obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003885 } else {
3886 // Go though the spaces looking for one that has objects.
3887 while (space_iterator_->has_next()) {
3888 object_iterator_ = space_iterator_->next();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003889 if (HeapObject* obj = object_iterator_->next_object()) {
3890 return obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003891 }
3892 }
3893 }
3894 // Done with the last space.
3895 object_iterator_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003896 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003897}
3898
3899
3900void HeapIterator::reset() {
3901 // Restart the iterator.
3902 Shutdown();
3903 Init();
3904}
3905
3906
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003907#ifdef DEBUG
3908
3909static bool search_for_any_global;
3910static Object* search_target;
3911static bool found_target;
3912static List<Object*> object_stack(20);
3913
3914
3915// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3916static const int kMarkTag = 2;
3917
3918static void MarkObjectRecursively(Object** p);
3919class MarkObjectVisitor : public ObjectVisitor {
3920 public:
3921 void VisitPointers(Object** start, Object** end) {
3922 // Copy all HeapObject pointers in [start, end)
3923 for (Object** p = start; p < end; p++) {
3924 if ((*p)->IsHeapObject())
3925 MarkObjectRecursively(p);
3926 }
3927 }
3928};
3929
3930static MarkObjectVisitor mark_visitor;
3931
3932static void MarkObjectRecursively(Object** p) {
3933 if (!(*p)->IsHeapObject()) return;
3934
3935 HeapObject* obj = HeapObject::cast(*p);
3936
3937 Object* map = obj->map();
3938
3939 if (!map->IsHeapObject()) return; // visited before
3940
3941 if (found_target) return; // stop if target found
3942 object_stack.Add(obj);
3943 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3944 (!search_for_any_global && (obj == search_target))) {
3945 found_target = true;
3946 return;
3947 }
3948
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003949 // not visited yet
3950 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3951
3952 Address map_addr = map_p->address();
3953
3954 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3955
3956 MarkObjectRecursively(&map);
3957
3958 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3959 &mark_visitor);
3960
3961 if (!found_target) // don't pop if found the target
3962 object_stack.RemoveLast();
3963}
3964
3965
3966static void UnmarkObjectRecursively(Object** p);
3967class UnmarkObjectVisitor : public ObjectVisitor {
3968 public:
3969 void VisitPointers(Object** start, Object** end) {
3970 // Copy all HeapObject pointers in [start, end)
3971 for (Object** p = start; p < end; p++) {
3972 if ((*p)->IsHeapObject())
3973 UnmarkObjectRecursively(p);
3974 }
3975 }
3976};
3977
3978static UnmarkObjectVisitor unmark_visitor;
3979
3980static void UnmarkObjectRecursively(Object** p) {
3981 if (!(*p)->IsHeapObject()) return;
3982
3983 HeapObject* obj = HeapObject::cast(*p);
3984
3985 Object* map = obj->map();
3986
3987 if (map->IsHeapObject()) return; // unmarked already
3988
3989 Address map_addr = reinterpret_cast<Address>(map);
3990
3991 map_addr -= kMarkTag;
3992
3993 ASSERT_TAG_ALIGNED(map_addr);
3994
3995 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3996
3997 obj->set_map(reinterpret_cast<Map*>(map_p));
3998
3999 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
4000
4001 obj->IterateBody(Map::cast(map_p)->instance_type(),
4002 obj->SizeFromMap(Map::cast(map_p)),
4003 &unmark_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004004}
4005
4006
4007static void MarkRootObjectRecursively(Object** root) {
4008 if (search_for_any_global) {
4009 ASSERT(search_target == NULL);
4010 } else {
4011 ASSERT(search_target->IsHeapObject());
4012 }
4013 found_target = false;
4014 object_stack.Clear();
4015
4016 MarkObjectRecursively(root);
4017 UnmarkObjectRecursively(root);
4018
4019 if (found_target) {
4020 PrintF("=====================================\n");
4021 PrintF("==== Path to object ====\n");
4022 PrintF("=====================================\n\n");
4023
4024 ASSERT(!object_stack.is_empty());
4025 for (int i = 0; i < object_stack.length(); i++) {
4026 if (i > 0) PrintF("\n |\n |\n V\n\n");
4027 Object* obj = object_stack[i];
4028 obj->Print();
4029 }
4030 PrintF("=====================================\n");
4031 }
4032}
4033
4034
4035// Helper class for visiting HeapObjects recursively.
4036class MarkRootVisitor: public ObjectVisitor {
4037 public:
4038 void VisitPointers(Object** start, Object** end) {
4039 // Visit all HeapObject pointers in [start, end)
4040 for (Object** p = start; p < end; p++) {
4041 if ((*p)->IsHeapObject())
4042 MarkRootObjectRecursively(p);
4043 }
4044 }
4045};
4046
4047
4048// Triggers a depth-first traversal of reachable objects from roots
4049// and finds a path to a specific heap object and prints it.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004050void Heap::TracePathToObject(Object* target) {
4051 search_target = target;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004052 search_for_any_global = false;
4053
4054 MarkRootVisitor root_visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00004055 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004056}
4057
4058
4059// Triggers a depth-first traversal of reachable objects from roots
4060// and finds a path to any global object and prints it. Useful for
4061// determining the source for leaks of global objects.
4062void Heap::TracePathToGlobal() {
4063 search_target = NULL;
4064 search_for_any_global = true;
4065
4066 MarkRootVisitor root_visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00004067 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004068}
4069#endif
4070
4071
kasper.lund7276f142008-07-30 08:49:36 +00004072GCTracer::GCTracer()
4073 : start_time_(0.0),
4074 start_size_(0.0),
4075 gc_count_(0),
4076 full_gc_count_(0),
4077 is_compacting_(false),
4078 marked_count_(0) {
4079 // These two fields reflect the state of the previous full collection.
4080 // Set them before they are changed by the collector.
4081 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
4082 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
4083 if (!FLAG_trace_gc) return;
4084 start_time_ = OS::TimeCurrentMillis();
4085 start_size_ = SizeOfHeapObjects();
4086}
4087
4088
4089GCTracer::~GCTracer() {
4090 if (!FLAG_trace_gc) return;
4091 // Printf ONE line iff flag is set.
4092 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
4093 CollectorString(),
4094 start_size_, SizeOfHeapObjects(),
4095 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
kasperl@chromium.orge959c182009-07-27 08:59:04 +00004096
4097#if defined(ENABLE_LOGGING_AND_PROFILING)
4098 Heap::PrintShortHeapStatistics();
4099#endif
kasper.lund7276f142008-07-30 08:49:36 +00004100}
4101
4102
4103const char* GCTracer::CollectorString() {
4104 switch (collector_) {
4105 case SCAVENGER:
4106 return "Scavenge";
4107 case MARK_COMPACTOR:
4108 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
4109 : "Mark-sweep";
4110 }
4111 return "Unknown GC";
4112}
4113
4114
ager@chromium.org5aa501c2009-06-23 07:57:28 +00004115int KeyedLookupCache::Hash(Map* map, String* name) {
4116 // Uses only lower 32 bits if pointers are larger.
4117 uintptr_t addr_hash =
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004118 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
4119 return (addr_hash ^ name->Hash()) & kCapacityMask;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00004120}
4121
4122
4123int KeyedLookupCache::Lookup(Map* map, String* name) {
4124 int index = Hash(map, name);
4125 Key& key = keys_[index];
4126 if ((key.map == map) && key.name->Equals(name)) {
4127 return field_offsets_[index];
4128 }
4129 return -1;
4130}
4131
4132
4133void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
4134 String* symbol;
4135 if (Heap::LookupSymbolIfExists(name, &symbol)) {
4136 int index = Hash(map, symbol);
4137 Key& key = keys_[index];
4138 key.map = map;
4139 key.name = symbol;
4140 field_offsets_[index] = field_offset;
4141 }
4142}
4143
4144
4145void KeyedLookupCache::Clear() {
4146 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
4147}
4148
4149
4150KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
4151
4152
4153int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
4154
4155
4156void DescriptorLookupCache::Clear() {
4157 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
4158}
4159
4160
4161DescriptorLookupCache::Key
4162DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
4163
4164int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
4165
4166
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00004167#ifdef DEBUG
4168bool Heap::GarbageCollectionGreedyCheck() {
4169 ASSERT(FLAG_gc_greedy);
4170 if (Bootstrapper::IsActive()) return true;
4171 if (disallow_allocation_failure()) return true;
4172 return CollectGarbage(0, NEW_SPACE);
4173}
4174#endif
4175
ager@chromium.org18ad94b2009-09-02 08:22:29 +00004176
4177TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
4178 : type_(t) {
4179 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
4180 uint32_t in1 = 0xffffffffu; // generated by the FPU.
4181 for (int i = 0; i < kCacheSize; i++) {
4182 elements_[i].in[0] = in0;
4183 elements_[i].in[1] = in1;
4184 elements_[i].output = NULL;
4185 }
4186}
4187
4188
4189TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
4190
4191
4192void TranscendentalCache::Clear() {
4193 for (int i = 0; i < kNumberOfCaches; i++) {
4194 if (caches_[i] != NULL) {
4195 delete caches_[i];
4196 caches_[i] = NULL;
4197 }
4198 }
4199}
4200
4201
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004202void ExternalStringTable::CleanUp() {
4203 int last = 0;
4204 for (int i = 0; i < new_space_strings_.length(); ++i) {
4205 if (new_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4206 if (Heap::InNewSpace(new_space_strings_[i])) {
4207 new_space_strings_[last++] = new_space_strings_[i];
4208 } else {
4209 old_space_strings_.Add(new_space_strings_[i]);
4210 }
4211 }
4212 new_space_strings_.Rewind(last);
4213 last = 0;
4214 for (int i = 0; i < old_space_strings_.length(); ++i) {
4215 if (old_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4216 ASSERT(!Heap::InNewSpace(old_space_strings_[i]));
4217 old_space_strings_[last++] = old_space_strings_[i];
4218 }
4219 old_space_strings_.Rewind(last);
4220 Verify();
4221}
4222
4223
4224void ExternalStringTable::TearDown() {
4225 new_space_strings_.Free();
4226 old_space_strings_.Free();
4227}
4228
4229
4230List<Object*> ExternalStringTable::new_space_strings_;
4231List<Object*> ExternalStringTable::old_space_strings_;
4232
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004233} } // namespace v8::internal