blob: c29815e5509f3ff85ac73d7ec7a222ce6a534a11 [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"
36#include "global-handles.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "mark-compact.h"
38#include "natives.h"
39#include "scanner.h"
40#include "scopeinfo.h"
41#include "v8threads.h"
ager@chromium.org18ad94b2009-09-02 08:22:29 +000042#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
43#include "regexp-macro-assembler.h"
44#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
kasperl@chromium.org71affb52009-05-26 05:44:31 +000046namespace v8 {
47namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000048
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049
ager@chromium.org3b45ab52009-03-19 22:21:34 +000050String* Heap::hidden_symbol_;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000051Object* Heap::roots_[Heap::kRootListLength];
52
ager@chromium.org3b45ab52009-03-19 22:21:34 +000053
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000054NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000055OldSpace* Heap::old_pointer_space_ = NULL;
56OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057OldSpace* Heap::code_space_ = NULL;
58MapSpace* Heap::map_space_ = NULL;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +000059CellSpace* Heap::cell_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060LargeObjectSpace* Heap::lo_space_ = NULL;
61
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000062static const int kMinimumPromotionLimit = 2*MB;
63static const int kMinimumAllocationLimit = 8*MB;
64
65int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
66int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
67
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000068int Heap::old_gen_exhausted_ = false;
69
kasper.lund7276f142008-07-30 08:49:36 +000070int Heap::amount_of_external_allocated_memory_ = 0;
71int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
72
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073// semispace_size_ should be a power of 2 and old_generation_size_ should be
74// a multiple of Page::kPageSize.
kasperl@chromium.orge959c182009-07-27 08:59:04 +000075#if defined(ANDROID)
ager@chromium.orgeadaf222009-06-16 09:43:10 +000076int Heap::semispace_size_ = 512*KB;
77int Heap::old_generation_size_ = 128*MB;
78int Heap::initial_semispace_size_ = 128*KB;
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +000079#elif defined(V8_TARGET_ARCH_X64)
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000080int Heap::semispace_size_ = 8*MB;
81int Heap::old_generation_size_ = 1*GB;
82int Heap::initial_semispace_size_ = 1*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000083#else
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +000084int Heap::semispace_size_ = 4*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000085int Heap::old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000086int Heap::initial_semispace_size_ = 512*KB;
87#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000088
89GCCallback Heap::global_gc_prologue_callback_ = NULL;
90GCCallback Heap::global_gc_epilogue_callback_ = NULL;
91
92// Variables set based on semispace_size_ and old_generation_size_ in
93// ConfigureHeap.
94int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
ager@chromium.orgeadaf222009-06-16 09:43:10 +000095int Heap::survived_since_last_expansion_ = 0;
kasperl@chromium.orge959c182009-07-27 08:59:04 +000096int Heap::external_allocation_limit_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000097
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000098Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
99
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000100int Heap::mc_count_ = 0;
101int Heap::gc_count_ = 0;
102
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000103int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000104bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000105
kasper.lund7276f142008-07-30 08:49:36 +0000106#ifdef DEBUG
107bool Heap::allocation_allowed_ = true;
108
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000109int Heap::allocation_timeout_ = 0;
110bool Heap::disallow_allocation_failure_ = false;
111#endif // DEBUG
112
113
114int Heap::Capacity() {
115 if (!HasBeenSetup()) return 0;
116
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000117 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000118 old_pointer_space_->Capacity() +
119 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000120 code_space_->Capacity() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000121 map_space_->Capacity() +
122 cell_space_->Capacity();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123}
124
125
126int Heap::Available() {
127 if (!HasBeenSetup()) return 0;
128
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000129 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000130 old_pointer_space_->Available() +
131 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000132 code_space_->Available() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000133 map_space_->Available() +
134 cell_space_->Available();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000135}
136
137
138bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000139 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000140 old_data_space_ != NULL &&
141 code_space_ != NULL &&
142 map_space_ != NULL &&
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000143 cell_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000144 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000145}
146
147
148GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
149 // Is global GC requested?
150 if (space != NEW_SPACE || FLAG_gc_global) {
151 Counters::gc_compactor_caused_by_request.Increment();
152 return MARK_COMPACTOR;
153 }
154
155 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000156 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000157 Counters::gc_compactor_caused_by_promoted_data.Increment();
158 return MARK_COMPACTOR;
159 }
160
161 // Have allocation in OLD and LO failed?
162 if (old_gen_exhausted_) {
163 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
164 return MARK_COMPACTOR;
165 }
166
167 // Is there enough space left in OLD to guarantee that a scavenge can
168 // succeed?
169 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000170 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 // for object promotion. It counts only the bytes that the memory
172 // allocator has not yet allocated from the OS and assigned to any space,
173 // and does not count available bytes already in the old space or code
174 // space. Undercounting is safe---we may get an unrequested full GC when
175 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000176 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000177 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
178 return MARK_COMPACTOR;
179 }
180
181 // Default
182 return SCAVENGER;
183}
184
185
186// TODO(1238405): Combine the infrastructure for --heap-stats and
187// --log-gc to avoid the complicated preprocessor and flag testing.
188#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
189void Heap::ReportStatisticsBeforeGC() {
190 // Heap::ReportHeapStatistics will also log NewSpace statistics when
191 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
192 // following logic is used to avoid double logging.
193#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000194 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195 if (FLAG_heap_stats) {
196 ReportHeapStatistics("Before GC");
197 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000198 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000200 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000201#elif defined(DEBUG)
202 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000205 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 }
207#elif defined(ENABLE_LOGGING_AND_PROFILING)
208 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000209 new_space_.CollectStatistics();
210 new_space_.ReportStatistics();
211 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000212 }
213#endif
214}
215
216
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000217#if defined(ENABLE_LOGGING_AND_PROFILING)
218void Heap::PrintShortHeapStatistics() {
219 if (!FLAG_trace_gc_verbose) return;
220 PrintF("Memory allocator, used: %8d, available: %8d\n",
221 MemoryAllocator::Size(), MemoryAllocator::Available());
222 PrintF("New space, used: %8d, available: %8d\n",
223 Heap::new_space_.Size(), new_space_.Available());
224 PrintF("Old pointers, used: %8d, available: %8d\n",
225 old_pointer_space_->Size(), old_pointer_space_->Available());
226 PrintF("Old data space, used: %8d, available: %8d\n",
227 old_data_space_->Size(), old_data_space_->Available());
228 PrintF("Code space, used: %8d, available: %8d\n",
229 code_space_->Size(), code_space_->Available());
230 PrintF("Map space, used: %8d, available: %8d\n",
231 map_space_->Size(), map_space_->Available());
232 PrintF("Large object space, used: %8d, avaialble: %8d\n",
233 lo_space_->Size(), lo_space_->Available());
234}
235#endif
236
237
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000238// TODO(1238405): Combine the infrastructure for --heap-stats and
239// --log-gc to avoid the complicated preprocessor and flag testing.
240void Heap::ReportStatisticsAfterGC() {
241 // Similar to the before GC, we use some complicated logic to ensure that
242 // NewSpace statistics are logged exactly once when --log-gc is turned on.
243#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
244 if (FLAG_heap_stats) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000245 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 ReportHeapStatistics("After GC");
247 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000248 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249 }
250#elif defined(DEBUG)
251 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
252#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000253 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254#endif
255}
256#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
257
258
259void Heap::GarbageCollectionPrologue() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000260 TranscendentalCache::Clear();
kasper.lund7276f142008-07-30 08:49:36 +0000261 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262#ifdef DEBUG
263 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
264 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000265
266 if (FLAG_verify_heap) {
267 Verify();
268 }
269
270 if (FLAG_gc_verbose) Print();
271
272 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000273 // Not all spaces have remembered set bits that we care about.
274 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000275 map_space_->PrintRSet();
276 lo_space_->PrintRSet();
277 }
278#endif
279
280#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
281 ReportStatisticsBeforeGC();
282#endif
283}
284
285int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000286 int total = 0;
287 AllSpaces spaces;
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000288 while (Space* space = spaces.next()) {
289 total += space->Size();
290 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000291 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000292}
293
294void Heap::GarbageCollectionEpilogue() {
295#ifdef DEBUG
296 allow_allocation(true);
297 ZapFromSpace();
298
299 if (FLAG_verify_heap) {
300 Verify();
301 }
302
303 if (FLAG_print_global_handles) GlobalHandles::Print();
304 if (FLAG_print_handles) PrintHandles();
305 if (FLAG_gc_verbose) Print();
306 if (FLAG_code_stats) ReportCodeStatistics("After GC");
307#endif
308
309 Counters::alive_after_last_gc.Set(SizeOfObjects());
310
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000311 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
312 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
314 ReportStatisticsAfterGC();
315#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000316#ifdef ENABLE_DEBUGGER_SUPPORT
317 Debug::AfterGarbageCollection();
318#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319}
320
321
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000322void Heap::CollectAllGarbage(bool force_compaction) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000323 // Since we are ignoring the return value, the exact choice of space does
324 // not matter, so long as we do not specify NEW_SPACE, which would not
325 // cause a full GC.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000326 MarkCompactCollector::SetForceCompaction(force_compaction);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000327 CollectGarbage(0, OLD_POINTER_SPACE);
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000328 MarkCompactCollector::SetForceCompaction(false);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000329}
330
331
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000332void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000333 // If the garbage collector interface is exposed through the global
334 // gc() function, we avoid being clever about forcing GCs when
335 // contexts are disposed and leave it to the embedder to make
336 // informed decisions about when to force a collection.
337 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000338 HistogramTimerScope scope(&Counters::gc_context);
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000339 CollectAllGarbage(false);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000340 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000341 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000342}
343
344
345void Heap::NotifyContextDisposed() {
346 context_disposed_pending_ = true;
347}
348
349
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
351 // The VM is in the GC state until exiting this function.
352 VMState state(GC);
353
354#ifdef DEBUG
355 // Reset the allocation timeout to the GC interval, but make sure to
356 // allow at least a few allocations after a collection. The reason
357 // for this is that we have a lot of allocation sequences and we
358 // assume that a garbage collection will allow the subsequent
359 // allocation attempts to go through.
360 allocation_timeout_ = Max(6, FLAG_gc_interval);
361#endif
362
363 { GCTracer tracer;
364 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000365 // The GC count was incremented in the prologue. Tell the tracer about
366 // it.
367 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368
369 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000370 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000371 tracer.set_collector(collector);
372
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000373 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374 ? &Counters::gc_scavenger
375 : &Counters::gc_compactor;
376 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000377 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000378 rate->Stop();
379
380 GarbageCollectionEpilogue();
381 }
382
383
384#ifdef ENABLE_LOGGING_AND_PROFILING
385 if (FLAG_log_gc) HeapProfiler::WriteSample();
386#endif
387
388 switch (space) {
389 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000390 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000391 case OLD_POINTER_SPACE:
392 return old_pointer_space_->Available() >= requested_size;
393 case OLD_DATA_SPACE:
394 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000395 case CODE_SPACE:
396 return code_space_->Available() >= requested_size;
397 case MAP_SPACE:
398 return map_space_->Available() >= requested_size;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000399 case CELL_SPACE:
400 return cell_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000401 case LO_SPACE:
402 return lo_space_->Available() >= requested_size;
403 }
404 return false;
405}
406
407
kasper.lund7276f142008-07-30 08:49:36 +0000408void Heap::PerformScavenge() {
409 GCTracer tracer;
410 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
411}
412
413
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000414#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000415// Helper class for verifying the symbol table.
416class SymbolTableVerifier : public ObjectVisitor {
417 public:
418 SymbolTableVerifier() { }
419 void VisitPointers(Object** start, Object** end) {
420 // Visit all HeapObject pointers in [start, end).
421 for (Object** p = start; p < end; p++) {
422 if ((*p)->IsHeapObject()) {
423 // Check that the symbol is actually a symbol.
424 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000425 }
426 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000427 }
428};
429#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000430
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000431
432static void VerifySymbolTable() {
433#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000434 SymbolTableVerifier verifier;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000435 Heap::symbol_table()->IterateElements(&verifier);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000436#endif // DEBUG
437}
438
439
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000440void Heap::EnsureFromSpaceIsCommitted() {
441 if (new_space_.CommitFromSpaceIfNeeded()) return;
442
443 // Committing memory to from space failed.
444 // Try shrinking and try again.
445 Shrink();
446 if (new_space_.CommitFromSpaceIfNeeded()) return;
447
448 // Committing memory to from space failed again.
449 // Memory is exhausted and we will die.
450 V8::FatalProcessOutOfMemory("Committing semi space failed.");
451}
452
453
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000454void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000455 GarbageCollector collector,
456 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000457 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000458 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
459 ASSERT(!allocation_allowed_);
460 global_gc_prologue_callback_();
461 }
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000462 EnsureFromSpaceIsCommitted();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000464 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000466 int old_gen_size = PromotedSpaceSize();
467 old_gen_promotion_limit_ =
468 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
469 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000470 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471 old_gen_exhausted_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472 }
ager@chromium.org439e85a2009-08-26 13:15:29 +0000473 Scavenge();
474
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475 Counters::objs_since_last_young.Set(0);
476
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000477 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000478
kasper.lund7276f142008-07-30 08:49:36 +0000479 if (collector == MARK_COMPACTOR) {
480 // Register the amount of external allocated memory.
481 amount_of_external_allocated_memory_at_last_global_gc_ =
482 amount_of_external_allocated_memory_;
483 }
484
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000485 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
486 ASSERT(!allocation_allowed_);
487 global_gc_epilogue_callback_();
488 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000489 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000490}
491
492
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000493void Heap::PostGarbageCollectionProcessing() {
494 // Process weak handles post gc.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000495 {
496 DisableAssertNoAllocation allow_allocation;
497 GlobalHandles::PostGarbageCollectionProcessing();
498 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000499 // Update flat string readers.
500 FlatStringReader::PostGarbageCollectionProcessing();
501}
502
503
kasper.lund7276f142008-07-30 08:49:36 +0000504void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000507 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508 LOG(ResourceEvent("markcompact", "begin"));
509
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000510 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000511
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000512 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000514 MarkCompactPrologue(is_compacting);
515
516 MarkCompactCollector::CollectGarbage();
517
518 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000519
520 LOG(ResourceEvent("markcompact", "end"));
521
522 gc_state_ = NOT_IN_GC;
523
524 Shrink();
525
526 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000527 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528}
529
530
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000531void Heap::MarkCompactPrologue(bool is_compacting) {
532 // At any old GC clear the keyed lookup cache to enable collection of unused
533 // maps.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000534 KeyedLookupCache::Clear();
535 ContextSlotCache::Clear();
536 DescriptorLookupCache::Clear();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000537
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000538 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000539
540 Top::MarkCompactPrologue(is_compacting);
541 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000542}
543
544
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000545void Heap::MarkCompactEpilogue(bool is_compacting) {
546 Top::MarkCompactEpilogue(is_compacting);
547 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548}
549
550
551Object* Heap::FindCodeObject(Address a) {
552 Object* obj = code_space_->FindObject(a);
553 if (obj->IsFailure()) {
554 obj = lo_space_->FindObject(a);
555 }
kasper.lund7276f142008-07-30 08:49:36 +0000556 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557 return obj;
558}
559
560
561// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000562class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563 public:
564
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000565 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566
567 void VisitPointers(Object** start, Object** end) {
568 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000569 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570 }
571
572 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000573 void ScavengePointer(Object** p) {
574 Object* object = *p;
575 if (!Heap::InNewSpace(object)) return;
576 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
577 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578 }
579};
580
581
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000582// A queue of pointers and maps of to-be-promoted objects during a
583// scavenge collection.
584class PromotionQueue {
585 public:
586 void Initialize(Address start_address) {
587 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
588 }
589
590 bool is_empty() { return front_ <= rear_; }
591
592 void insert(HeapObject* object, Map* map) {
593 *(--rear_) = object;
594 *(--rear_) = map;
595 // Assert no overflow into live objects.
596 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
597 }
598
599 void remove(HeapObject** object, Map** map) {
600 *object = *(--front_);
601 *map = Map::cast(*(--front_));
602 // Assert no underflow.
603 ASSERT(front_ >= rear_);
604 }
605
606 private:
607 // The front of the queue is higher in memory than the rear.
608 HeapObject** front_;
609 HeapObject** rear_;
610};
611
612
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000613// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000614static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615
616
617#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000618// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000619// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000620class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000621 public:
622 void VisitPointers(Object** start, Object**end) {
623 for (Object** current = start; current < end; current++) {
624 if ((*current)->IsHeapObject()) {
625 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
626 }
627 }
628 }
629};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000630
631
632static void VerifyNonPointerSpacePointers() {
633 // Verify that there are no pointers to new space in spaces where we
634 // do not expect them.
635 VerifyNonPointerSpacePointersVisitor v;
636 HeapObjectIterator code_it(Heap::code_space());
637 while (code_it.has_next()) {
638 HeapObject* object = code_it.next();
639 if (object->IsCode()) {
640 Code::cast(object)->ConvertICTargetsFromAddressToObject();
641 object->Iterate(&v);
642 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
643 } else {
644 // If we find non-code objects in code space (e.g., free list
645 // nodes) we want to verify them as well.
646 object->Iterate(&v);
647 }
648 }
649
650 HeapObjectIterator data_it(Heap::old_data_space());
651 while (data_it.has_next()) data_it.next()->Iterate(&v);
652}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653#endif
654
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000655
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000656void Heap::Scavenge() {
657#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000658 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000659#endif
660
661 gc_state_ = SCAVENGE;
662
663 // Implements Cheney's copying algorithm
664 LOG(ResourceEvent("scavenge", "begin"));
665
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000666 // Clear descriptor cache.
667 DescriptorLookupCache::Clear();
668
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000669 // Used for updating survived_since_last_expansion_ at function end.
670 int survived_watermark = PromotedSpaceSize();
671
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000672 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000673 survived_since_last_expansion_ > new_space_.Capacity()) {
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000674 // Grow the size of new space if there is room to grow and enough
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000675 // data has survived scavenge since the last expansion.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000676 new_space_.Grow();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000677 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678 }
679
680 // Flip the semispaces. After flipping, to space is empty, from space has
681 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000682 new_space_.Flip();
683 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000685 // We need to sweep newly copied objects which can be either in the
686 // to space or promoted to the old generation. For to-space
687 // objects, we treat the bottom of the to space as a queue. Newly
688 // copied and unswept objects lie between a 'front' mark and the
689 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000690 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000691 // Promoted objects can go into various old-generation spaces, and
692 // can be allocated internally in the spaces (from the free list).
693 // We treat the top of the to space as a queue of addresses of
694 // promoted objects. The addresses of newly promoted and unswept
695 // objects lie between a 'front' mark and a 'rear' mark that is
696 // updated as a side effect of promoting an object.
697 //
698 // There is guaranteed to be enough room at the top of the to space
699 // for the addresses of promoted objects: every object promoted
700 // frees up its size in bytes from the top of the new space, and
701 // objects are at least one pointer in size.
702 Address new_space_front = new_space_.ToSpaceLow();
703 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000705 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000707 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000708
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000709 // Copy objects reachable from weak pointers.
710 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
711
712 // Copy objects reachable from the old generation. By definition,
713 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000714 IterateRSet(old_pointer_space_, &ScavengePointer);
715 IterateRSet(map_space_, &ScavengePointer);
716 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000717
718 // Copy objects reachable from cells by scavenging cell values directly.
719 HeapObjectIterator cell_iterator(cell_space_);
720 while (cell_iterator.has_next()) {
721 HeapObject* cell = cell_iterator.next();
722 if (cell->IsJSGlobalPropertyCell()) {
723 Address value_address =
724 reinterpret_cast<Address>(cell) +
725 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
726 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
727 }
728 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000730 do {
731 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000732
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000733 // The addresses new_space_front and new_space_.top() define a
734 // queue of unprocessed copied objects. Process them until the
735 // queue is empty.
736 while (new_space_front < new_space_.top()) {
737 HeapObject* object = HeapObject::FromAddress(new_space_front);
738 object->Iterate(&scavenge_visitor);
739 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000740 }
741
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000742 // Promote and process all the to-be-promoted objects.
743 while (!promotion_queue.is_empty()) {
744 HeapObject* source;
745 Map* map;
746 promotion_queue.remove(&source, &map);
747 // Copy the from-space object to its new location (given by the
748 // forwarding address) and fix its map.
749 HeapObject* target = source->map_word().ToForwardingAddress();
750 CopyBlock(reinterpret_cast<Object**>(target->address()),
751 reinterpret_cast<Object**>(source->address()),
752 source->SizeFromMap(map));
753 target->set_map(map);
754
755#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
756 // Update NewSpace stats if necessary.
757 RecordCopiedObject(target);
758#endif
759 // Visit the newly copied object for pointers to new space.
760 target->Iterate(&scavenge_visitor);
761 UpdateRSet(target);
762 }
763
764 // Take another spin if there are now unswept objects in new space
765 // (there are currently no more unswept promoted objects).
766 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000767
768 // Set age mark.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000769 new_space_.set_age_mark(new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000771 // Update how much has survived scavenge.
772 survived_since_last_expansion_ +=
773 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
774
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775 LOG(ResourceEvent("scavenge", "end"));
776
777 gc_state_ = NOT_IN_GC;
778}
779
780
781void Heap::ClearRSetRange(Address start, int size_in_bytes) {
782 uint32_t start_bit;
783 Address start_word_address =
784 Page::ComputeRSetBitPosition(start, 0, &start_bit);
785 uint32_t end_bit;
786 Address end_word_address =
787 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
788 0,
789 &end_bit);
790
791 // We want to clear the bits in the starting word starting with the
792 // first bit, and in the ending word up to and including the last
793 // bit. Build a pair of bitmasks to do that.
794 uint32_t start_bitmask = start_bit - 1;
795 uint32_t end_bitmask = ~((end_bit << 1) - 1);
796
797 // If the start address and end address are the same, we mask that
798 // word once, otherwise mask the starting and ending word
799 // separately and all the ones in between.
800 if (start_word_address == end_word_address) {
801 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
802 } else {
803 Memory::uint32_at(start_word_address) &= start_bitmask;
804 Memory::uint32_at(end_word_address) &= end_bitmask;
805 start_word_address += kIntSize;
806 memset(start_word_address, 0, end_word_address - start_word_address);
807 }
808}
809
810
811class UpdateRSetVisitor: public ObjectVisitor {
812 public:
813
814 void VisitPointer(Object** p) {
815 UpdateRSet(p);
816 }
817
818 void VisitPointers(Object** start, Object** end) {
819 // Update a store into slots [start, end), used (a) to update remembered
820 // set when promoting a young object to old space or (b) to rebuild
821 // remembered sets after a mark-compact collection.
822 for (Object** p = start; p < end; p++) UpdateRSet(p);
823 }
824 private:
825
826 void UpdateRSet(Object** p) {
827 // The remembered set should not be set. It should be clear for objects
828 // newly copied to old space, and it is cleared before rebuilding in the
829 // mark-compact collector.
830 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
831 if (Heap::InNewSpace(*p)) {
832 Page::SetRSet(reinterpret_cast<Address>(p), 0);
833 }
834 }
835};
836
837
838int Heap::UpdateRSet(HeapObject* obj) {
839 ASSERT(!InNewSpace(obj));
840 // Special handling of fixed arrays to iterate the body based on the start
841 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
842 // will not work because Page::SetRSet needs to have the start of the
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000843 // object for large object pages.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000844 if (obj->IsFixedArray()) {
845 FixedArray* array = FixedArray::cast(obj);
846 int length = array->length();
847 for (int i = 0; i < length; i++) {
848 int offset = FixedArray::kHeaderSize + i * kPointerSize;
849 ASSERT(!Page::IsRSetSet(obj->address(), offset));
850 if (Heap::InNewSpace(array->get(i))) {
851 Page::SetRSet(obj->address(), offset);
852 }
853 }
854 } else if (!obj->IsCode()) {
855 // Skip code object, we know it does not contain inter-generational
856 // pointers.
857 UpdateRSetVisitor v;
858 obj->Iterate(&v);
859 }
860 return obj->Size();
861}
862
863
864void Heap::RebuildRSets() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000865 // By definition, we do not care about remembered set bits in code,
866 // data, or cell spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000867 map_space_->ClearRSet();
868 RebuildRSets(map_space_);
869
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000870 old_pointer_space_->ClearRSet();
871 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000872
873 Heap::lo_space_->ClearRSet();
874 RebuildRSets(lo_space_);
875}
876
877
878void Heap::RebuildRSets(PagedSpace* space) {
879 HeapObjectIterator it(space);
880 while (it.has_next()) Heap::UpdateRSet(it.next());
881}
882
883
884void Heap::RebuildRSets(LargeObjectSpace* space) {
885 LargeObjectIterator it(space);
886 while (it.has_next()) Heap::UpdateRSet(it.next());
887}
888
889
890#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
891void Heap::RecordCopiedObject(HeapObject* obj) {
892 bool should_record = false;
893#ifdef DEBUG
894 should_record = FLAG_heap_stats;
895#endif
896#ifdef ENABLE_LOGGING_AND_PROFILING
897 should_record = should_record || FLAG_log_gc;
898#endif
899 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000900 if (new_space_.Contains(obj)) {
901 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000902 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000903 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000904 }
905 }
906}
907#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
908
909
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000910
911HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000912 HeapObject* target,
913 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000914 // Copy the content of source to target.
915 CopyBlock(reinterpret_cast<Object**>(target->address()),
916 reinterpret_cast<Object**>(source->address()),
917 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000918
kasper.lund7276f142008-07-30 08:49:36 +0000919 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000920 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000921
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000922#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000923 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000924 RecordCopiedObject(target);
925#endif
926
927 return target;
928}
929
930
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000931static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000932 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000933 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000934 InstanceType type = map->instance_type();
935 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
936 ASSERT(object->IsString() && !object->IsSymbol());
937 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000938}
939
940
941void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
942 ASSERT(InFromSpace(object));
943 MapWord first_word = object->map_word();
944 ASSERT(!first_word.IsForwardingAddress());
945
946 // Optimization: Bypass flattened ConsString objects.
947 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000948 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000949 *p = object;
950 // After patching *p we have to repeat the checks that object is in the
951 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000952 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000953 first_word = object->map_word();
954 if (first_word.IsForwardingAddress()) {
955 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000956 return;
957 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958 }
959
kasper.lund7276f142008-07-30 08:49:36 +0000960 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000961 // We rely on live objects in new space to be at least two pointers,
962 // so we can store the from-space address and map pointer of promoted
963 // objects in the to space.
964 ASSERT(object_size >= 2 * kPointerSize);
965
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000966 // If the object should be promoted, we try to copy it to old space.
967 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000968 Object* result;
969 if (object_size > MaxObjectSizeInPagedSpace()) {
970 result = lo_space_->AllocateRawFixedArray(object_size);
971 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000972 // Save the from-space object pointer and its map pointer at the
973 // top of the to space to be swept and copied later. Write the
974 // forwarding address over the map word of the from-space
975 // object.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000976 HeapObject* target = HeapObject::cast(result);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000977 promotion_queue.insert(object, first_word.ToMap());
978 object->set_map_word(MapWord::FromForwardingAddress(target));
979
980 // Give the space allocated for the result a proper map by
981 // treating it as a free list node (not linked into the free
982 // list).
983 FreeListNode* node = FreeListNode::FromAddress(target->address());
984 node->set_size(object_size);
985
986 *p = target;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000987 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000988 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000989 } else {
990 OldSpace* target_space = Heap::TargetSpace(object);
991 ASSERT(target_space == Heap::old_pointer_space_ ||
992 target_space == Heap::old_data_space_);
993 result = target_space->AllocateRaw(object_size);
994 if (!result->IsFailure()) {
995 HeapObject* target = HeapObject::cast(result);
996 if (target_space == Heap::old_pointer_space_) {
997 // Save the from-space object pointer and its map pointer at the
998 // top of the to space to be swept and copied later. Write the
999 // forwarding address over the map word of the from-space
1000 // object.
1001 promotion_queue.insert(object, first_word.ToMap());
1002 object->set_map_word(MapWord::FromForwardingAddress(target));
1003
1004 // Give the space allocated for the result a proper map by
1005 // treating it as a free list node (not linked into the free
1006 // list).
1007 FreeListNode* node = FreeListNode::FromAddress(target->address());
1008 node->set_size(object_size);
1009
1010 *p = target;
1011 } else {
1012 // Objects promoted to the data space can be copied immediately
1013 // and not revisited---we will never sweep that space for
1014 // pointers and the copied objects do not contain pointers to
1015 // new space objects.
1016 *p = MigrateObject(object, target, object_size);
1017#ifdef DEBUG
1018 VerifyNonPointerSpacePointersVisitor v;
1019 (*p)->Iterate(&v);
1020#endif
1021 }
1022 return;
1023 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 }
1025 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001026 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001027 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001028 // Failed allocation at this point is utterly unexpected.
1029 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001030 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1031}
1032
1033
1034void Heap::ScavengePointer(HeapObject** p) {
1035 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001036}
1037
1038
1039Object* Heap::AllocatePartialMap(InstanceType instance_type,
1040 int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001041 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001042 if (result->IsFailure()) return result;
1043
1044 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001045 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1047 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001048 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001049 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1050 return result;
1051}
1052
1053
1054Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001055 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001056 if (result->IsFailure()) return result;
1057
1058 Map* map = reinterpret_cast<Map*>(result);
1059 map->set_map(meta_map());
1060 map->set_instance_type(instance_type);
1061 map->set_prototype(null_value());
1062 map->set_constructor(null_value());
1063 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001064 map->set_inobject_properties(0);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001065 map->set_pre_allocated_property_fields(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001066 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067 map->set_code_cache(empty_fixed_array());
1068 map->set_unused_property_fields(0);
1069 map->set_bit_field(0);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001070 map->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001071 return map;
1072}
1073
1074
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001075const Heap::StringTypeTable Heap::string_type_table[] = {
1076#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1077 {type, size, k##camel_name##MapRootIndex},
1078 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1079#undef STRING_TYPE_ELEMENT
1080};
1081
1082
1083const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1084#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1085 {contents, k##name##RootIndex},
1086 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1087#undef CONSTANT_SYMBOL_ELEMENT
1088};
1089
1090
1091const Heap::StructTable Heap::struct_table[] = {
1092#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1093 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1094 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1095#undef STRUCT_TABLE_ELEMENT
1096};
1097
1098
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001099bool Heap::CreateInitialMaps() {
1100 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1101 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001102 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001103 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1104 set_meta_map(new_meta_map);
1105 new_meta_map->set_map(new_meta_map);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001106
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001107 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001108 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001109 set_fixed_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001110
1111 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1112 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001113 set_oddball_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001114
1115 // Allocate the empty array
1116 obj = AllocateEmptyFixedArray();
1117 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001118 set_empty_fixed_array(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001119
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001120 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001121 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001122 set_null_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001123
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001124 // Allocate the empty descriptor array.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001125 obj = AllocateEmptyFixedArray();
1126 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001127 set_empty_descriptor_array(DescriptorArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001128
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001129 // Fix the instance_descriptors for the existing maps.
1130 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001131 meta_map()->set_code_cache(empty_fixed_array());
1132
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001133 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001134 fixed_array_map()->set_code_cache(empty_fixed_array());
1135
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001136 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001137 oddball_map()->set_code_cache(empty_fixed_array());
1138
1139 // Fix prototype object for existing maps.
1140 meta_map()->set_prototype(null_value());
1141 meta_map()->set_constructor(null_value());
1142
1143 fixed_array_map()->set_prototype(null_value());
1144 fixed_array_map()->set_constructor(null_value());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001145
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001146 oddball_map()->set_prototype(null_value());
1147 oddball_map()->set_constructor(null_value());
1148
1149 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1150 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001151 set_heap_number_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152
1153 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1154 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001155 set_proxy_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001156
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001157 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1158 const StringTypeTable& entry = string_type_table[i];
1159 obj = AllocateMap(entry.type, entry.size);
1160 if (obj->IsFailure()) return false;
1161 roots_[entry.index] = Map::cast(obj);
1162 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001163
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001164 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001165 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001166 set_undetectable_short_string_map(Map::cast(obj));
1167 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001168
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001169 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001170 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001171 set_undetectable_medium_string_map(Map::cast(obj));
1172 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001173
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001174 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001175 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001176 set_undetectable_long_string_map(Map::cast(obj));
1177 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001178
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001179 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001180 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001181 set_undetectable_short_ascii_string_map(Map::cast(obj));
1182 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001183
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001184 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001185 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001186 set_undetectable_medium_ascii_string_map(Map::cast(obj));
1187 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001188
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001189 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001190 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001191 set_undetectable_long_ascii_string_map(Map::cast(obj));
1192 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001193
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001194 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001195 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001196 set_byte_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001197
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001198 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1199 if (obj->IsFailure()) return false;
1200 set_pixel_array_map(Map::cast(obj));
1201
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001202 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1203 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001204 set_code_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001205
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001206 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1207 JSGlobalPropertyCell::kSize);
1208 if (obj->IsFailure()) return false;
1209 set_global_property_cell_map(Map::cast(obj));
1210
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001211 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1212 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001213 set_one_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001214
1215 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1216 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001217 set_two_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001218
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001219 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1220 const StructTable& entry = struct_table[i];
1221 obj = AllocateMap(entry.type, entry.size);
1222 if (obj->IsFailure()) return false;
1223 roots_[entry.index] = Map::cast(obj);
1224 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001225
ager@chromium.org236ad962008-09-25 09:45:57 +00001226 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001227 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001228 set_hash_table_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229
ager@chromium.org236ad962008-09-25 09:45:57 +00001230 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001231 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001232 set_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001233
ager@chromium.org236ad962008-09-25 09:45:57 +00001234 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001235 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001236 set_catch_context_map(Map::cast(obj));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001237
1238 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1239 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001240 set_global_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001241
1242 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1243 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001244 set_boilerplate_function_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001245
1246 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1247 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001248 set_shared_function_info_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001249
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001250 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001251 return true;
1252}
1253
1254
1255Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1256 // Statically ensure that it is safe to allocate heap numbers in paged
1257 // spaces.
1258 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001259 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001260 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001261 if (result->IsFailure()) return result;
1262
1263 HeapObject::cast(result)->set_map(heap_number_map());
1264 HeapNumber::cast(result)->set_value(value);
1265 return result;
1266}
1267
1268
1269Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001270 // Use general version, if we're forced to always allocate.
1271 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001272 // This version of AllocateHeapNumber is optimized for
1273 // allocation in new space.
1274 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1275 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001276 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001277 if (result->IsFailure()) return result;
1278 HeapObject::cast(result)->set_map(heap_number_map());
1279 HeapNumber::cast(result)->set_value(value);
1280 return result;
1281}
1282
1283
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001284Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001285 Object* result = AllocateRawCell();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001286 if (result->IsFailure()) return result;
1287 HeapObject::cast(result)->set_map(global_property_cell_map());
1288 JSGlobalPropertyCell::cast(result)->set_value(value);
1289 return result;
1290}
1291
1292
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001293Object* Heap::CreateOddball(Map* map,
1294 const char* to_string,
1295 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001296 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001297 if (result->IsFailure()) return result;
1298 return Oddball::cast(result)->Initialize(to_string, to_number);
1299}
1300
1301
1302bool Heap::CreateApiObjects() {
1303 Object* obj;
1304
1305 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1306 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001307 set_neander_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001308
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001309 obj = Heap::AllocateJSObjectFromMap(neander_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001310 if (obj->IsFailure()) return false;
1311 Object* elements = AllocateFixedArray(2);
1312 if (elements->IsFailure()) return false;
1313 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1314 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001315 set_message_listeners(JSObject::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001316
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001317 return true;
1318}
1319
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001320
1321void Heap::CreateCEntryStub() {
1322 CEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001323 set_c_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001324}
1325
1326
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001327#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1328void Heap::CreateRegExpCEntryStub() {
1329 RegExpCEntryStub stub;
1330 set_re_c_entry_code(*stub.GetCode());
1331}
1332#endif
1333
1334
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001335void Heap::CreateCEntryDebugBreakStub() {
1336 CEntryDebugBreakStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001337 set_c_entry_debug_break_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001338}
1339
1340
1341void Heap::CreateJSEntryStub() {
1342 JSEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001343 set_js_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001344}
1345
1346
1347void Heap::CreateJSConstructEntryStub() {
1348 JSConstructEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001349 set_js_construct_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001350}
1351
1352
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001353void Heap::CreateFixedStubs() {
1354 // Here we create roots for fixed stubs. They are needed at GC
1355 // for cooking and uncooking (check out frames.cc).
1356 // The eliminates the need for doing dictionary lookup in the
1357 // stub cache for these stubs.
1358 HandleScope scope;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001359 // gcc-4.4 has problem generating correct code of following snippet:
1360 // { CEntryStub stub;
1361 // c_entry_code_ = *stub.GetCode();
1362 // }
1363 // { CEntryDebugBreakStub stub;
1364 // c_entry_debug_break_code_ = *stub.GetCode();
1365 // }
1366 // To workaround the problem, make separate functions without inlining.
1367 Heap::CreateCEntryStub();
1368 Heap::CreateCEntryDebugBreakStub();
1369 Heap::CreateJSEntryStub();
1370 Heap::CreateJSConstructEntryStub();
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001371#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1372 Heap::CreateRegExpCEntryStub();
1373#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374}
1375
1376
1377bool Heap::CreateInitialObjects() {
1378 Object* obj;
1379
1380 // The -0 value must be set before NumberFromDouble works.
1381 obj = AllocateHeapNumber(-0.0, TENURED);
1382 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001383 set_minus_zero_value(obj);
1384 ASSERT(signbit(minus_zero_value()->Number()) != 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001385
1386 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1387 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001388 set_nan_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001390 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001391 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001392 set_undefined_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001393 ASSERT(!InNewSpace(undefined_value()));
1394
1395 // Allocate initial symbol table.
1396 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1397 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001398 // Don't use set_symbol_table() due to asserts.
1399 roots_[kSymbolTableRootIndex] = obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001400
1401 // Assign the print strings for oddballs after creating symboltable.
1402 Object* symbol = LookupAsciiSymbol("undefined");
1403 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001404 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1405 Oddball::cast(undefined_value())->set_to_number(nan_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001406
1407 // Assign the print strings for oddballs after creating symboltable.
1408 symbol = LookupAsciiSymbol("null");
1409 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001410 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1411 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001412
1413 // Allocate the null_value
1414 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1415 if (obj->IsFailure()) return false;
1416
1417 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1418 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001419 set_true_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420
1421 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1422 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001423 set_false_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001424
1425 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1426 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001427 set_the_hole_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001428
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001429 obj = CreateOddball(
1430 oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
1431 if (obj->IsFailure()) return false;
1432 set_no_interceptor_result_sentinel(obj);
1433
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001434 obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
1435 if (obj->IsFailure()) return false;
1436 set_termination_exception(obj);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001437
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438 // Allocate the empty string.
1439 obj = AllocateRawAsciiString(0, TENURED);
1440 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001441 set_empty_string(String::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001442
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001443 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1444 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1445 if (obj->IsFailure()) return false;
1446 roots_[constant_symbol_table[i].index] = String::cast(obj);
1447 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001448
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001449 // Allocate the hidden symbol which is used to identify the hidden properties
1450 // in JSObjects. The hash code has a special value so that it will not match
1451 // the empty string when searching for the property. It cannot be part of the
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001452 // loop above because it needs to be allocated manually with the special
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001453 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1454 // that it will always be at the first entry in property descriptors.
1455 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1456 if (obj->IsFailure()) return false;
1457 hidden_symbol_ = String::cast(obj);
1458
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001459 // Allocate the proxy for __proto__.
1460 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1461 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001462 set_prototype_accessors(Proxy::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001464 // Allocate the code_stubs dictionary. The initial size is set to avoid
1465 // expanding the dictionary during bootstrapping.
1466 obj = NumberDictionary::Allocate(128);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001468 set_code_stubs(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001469
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001470 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1471 // is set to avoid expanding the dictionary during bootstrapping.
1472 obj = NumberDictionary::Allocate(64);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001473 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001474 set_non_monomorphic_cache(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475
1476 CreateFixedStubs();
1477
1478 // Allocate the number->string conversion cache
1479 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1480 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001481 set_number_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001482
1483 // Allocate cache for single character strings.
1484 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1485 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001486 set_single_character_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001487
1488 // Allocate cache for external strings pointing to native source code.
1489 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1490 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001491 set_natives_source_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001492
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001493 // Handling of script id generation is in Factory::NewScript.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001494 set_last_script_id(undefined_value());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001495
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001496 // Initialize keyed lookup cache.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001497 KeyedLookupCache::Clear();
1498
1499 // Initialize context slot cache.
1500 ContextSlotCache::Clear();
1501
1502 // Initialize descriptor cache.
1503 DescriptorLookupCache::Clear();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001504
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001505 // Initialize compilation cache.
1506 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001507
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001508 return true;
1509}
1510
1511
1512static inline int double_get_hash(double d) {
1513 DoubleRepresentation rep(d);
1514 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1515 (Heap::kNumberStringCacheSize - 1));
1516}
1517
1518
1519static inline int smi_get_hash(Smi* smi) {
1520 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1521}
1522
1523
1524
1525Object* Heap::GetNumberStringCache(Object* number) {
1526 int hash;
1527 if (number->IsSmi()) {
1528 hash = smi_get_hash(Smi::cast(number));
1529 } else {
1530 hash = double_get_hash(number->Number());
1531 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001532 Object* key = number_string_cache()->get(hash * 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001533 if (key == number) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001534 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001535 } else if (key->IsHeapNumber() &&
1536 number->IsHeapNumber() &&
1537 key->Number() == number->Number()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001538 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539 }
1540 return undefined_value();
1541}
1542
1543
1544void Heap::SetNumberStringCache(Object* number, String* string) {
1545 int hash;
1546 if (number->IsSmi()) {
1547 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001548 number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549 } else {
1550 hash = double_get_hash(number->Number());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001551 number_string_cache()->set(hash * 2, number);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001552 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001553 number_string_cache()->set(hash * 2 + 1, string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554}
1555
1556
1557Object* Heap::SmiOrNumberFromDouble(double value,
1558 bool new_object,
1559 PretenureFlag pretenure) {
1560 // We need to distinguish the minus zero value and this cannot be
1561 // done after conversion to int. Doing this by comparing bit
1562 // patterns is faster than using fpclassify() et al.
1563 static const DoubleRepresentation plus_zero(0.0);
1564 static const DoubleRepresentation minus_zero(-0.0);
1565 static const DoubleRepresentation nan(OS::nan_value());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001566 ASSERT(minus_zero_value() != NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001567 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1568
1569 DoubleRepresentation rep(value);
1570 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1571 if (rep.bits == minus_zero.bits) {
1572 return new_object ? AllocateHeapNumber(-0.0, pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001573 : minus_zero_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574 }
1575 if (rep.bits == nan.bits) {
1576 return new_object
1577 ? AllocateHeapNumber(OS::nan_value(), pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001578 : nan_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579 }
1580
1581 // Try to represent the value as a tagged small integer.
1582 int int_value = FastD2I(value);
1583 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1584 return Smi::FromInt(int_value);
1585 }
1586
1587 // Materialize the value in the heap.
1588 return AllocateHeapNumber(value, pretenure);
1589}
1590
1591
1592Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1593 return SmiOrNumberFromDouble(value,
1594 true /* number object must be new */,
1595 pretenure);
1596}
1597
1598
1599Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1600 return SmiOrNumberFromDouble(value,
1601 false /* use preallocated NaN, -0.0 */,
1602 pretenure);
1603}
1604
1605
1606Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1607 // Statically ensure that it is safe to allocate proxies in paged spaces.
1608 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001609 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001610 Object* result = Allocate(proxy_map(), space);
1611 if (result->IsFailure()) return result;
1612
1613 Proxy::cast(result)->set_proxy(proxy);
1614 return result;
1615}
1616
1617
1618Object* Heap::AllocateSharedFunctionInfo(Object* name) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001619 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001620 if (result->IsFailure()) return result;
1621
1622 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1623 share->set_name(name);
1624 Code* illegal = Builtins::builtin(Builtins::Illegal);
1625 share->set_code(illegal);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001626 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1627 share->set_construct_stub(construct_stub);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628 share->set_expected_nof_properties(0);
1629 share->set_length(0);
1630 share->set_formal_parameter_count(0);
1631 share->set_instance_class_name(Object_symbol());
1632 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 share->set_script(undefined_value());
1634 share->set_start_position_and_type(0);
1635 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001636 share->set_inferred_name(empty_string());
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001637 share->set_compiler_hints(0);
1638 share->set_this_property_assignments_count(0);
1639 share->set_this_property_assignments(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001640 return result;
1641}
1642
1643
ager@chromium.org3e875802009-06-29 08:26:34 +00001644Object* Heap::AllocateConsString(String* first, String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001645 int first_length = first->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001646 if (first_length == 0) return second;
1647
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001648 int second_length = second->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001649 if (second_length == 0) return first;
1650
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001651 int length = first_length + second_length;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001652 bool is_ascii = first->IsAsciiRepresentation()
1653 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654
ager@chromium.org3e875802009-06-29 08:26:34 +00001655 // Make sure that an out of memory exception is thrown if the length
1656 // of the new cons string is too large to fit in a Smi.
1657 if (length > Smi::kMaxValue || length < -0) {
1658 Top::context()->mark_out_of_memory();
1659 return Failure::OutOfMemoryException();
1660 }
1661
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001662 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001663 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001664 ASSERT(first->IsFlat());
1665 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001666 if (is_ascii) {
1667 Object* result = AllocateRawAsciiString(length);
1668 if (result->IsFailure()) return result;
1669 // Copy the characters into the new object.
1670 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org3e875802009-06-29 08:26:34 +00001671 // Copy first part.
1672 char* src = SeqAsciiString::cast(first)->GetChars();
1673 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1674 // Copy second part.
1675 src = SeqAsciiString::cast(second)->GetChars();
1676 for (int i = 0; i < second_length; i++) *dest++ = src[i];
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001677 return result;
1678 } else {
1679 Object* result = AllocateRawTwoByteString(length);
1680 if (result->IsFailure()) return result;
1681 // Copy the characters into the new object.
1682 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001683 String::WriteToFlat(first, dest, 0, first_length);
1684 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001685 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001686 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001687 }
1688
1689 Map* map;
1690 if (length <= String::kMaxShortStringSize) {
1691 map = is_ascii ? short_cons_ascii_string_map()
1692 : short_cons_string_map();
1693 } else if (length <= String::kMaxMediumStringSize) {
1694 map = is_ascii ? medium_cons_ascii_string_map()
1695 : medium_cons_string_map();
1696 } else {
1697 map = is_ascii ? long_cons_ascii_string_map()
1698 : long_cons_string_map();
1699 }
1700
1701 Object* result = Allocate(map, NEW_SPACE);
1702 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001703 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001704 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001705 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1706 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001707 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001708 return result;
1709}
1710
1711
ager@chromium.org870a0b62008-11-04 11:43:05 +00001712Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001713 int start,
1714 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001715 int length = end - start;
1716
1717 // If the resulting string is small make a sub string.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001718 if (length <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001719 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720 }
1721
1722 Map* map;
1723 if (length <= String::kMaxShortStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001724 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001725 short_sliced_ascii_string_map() :
1726 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001727 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001728 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001729 medium_sliced_ascii_string_map() :
1730 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001731 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001732 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001733 long_sliced_ascii_string_map() :
1734 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001735 }
1736
1737 Object* result = Allocate(map, NEW_SPACE);
1738 if (result->IsFailure()) return result;
1739
1740 SlicedString* sliced_string = SlicedString::cast(result);
1741 sliced_string->set_buffer(buffer);
1742 sliced_string->set_start(start);
1743 sliced_string->set_length(length);
1744
1745 return result;
1746}
1747
1748
ager@chromium.org870a0b62008-11-04 11:43:05 +00001749Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001750 int start,
1751 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001752 int length = end - start;
1753
ager@chromium.org7c537e22008-10-16 08:43:32 +00001754 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001755 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001756 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001757 }
1758
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001759 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001760 if (!buffer->IsFlat()) {
1761 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001762 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001763
ager@chromium.org5ec48922009-05-05 07:25:34 +00001764 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001765 ? AllocateRawAsciiString(length)
1766 : AllocateRawTwoByteString(length);
1767 if (result->IsFailure()) return result;
1768
1769 // Copy the characters into the new object.
1770 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001771 StringHasher hasher(length);
1772 int i = 0;
1773 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001774 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001775 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001776 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001778 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001779 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001780 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001781 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001782 }
1783 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001784 return result;
1785}
1786
1787
1788Object* Heap::AllocateExternalStringFromAscii(
1789 ExternalAsciiString::Resource* resource) {
1790 Map* map;
1791 int length = resource->length();
1792 if (length <= String::kMaxShortStringSize) {
1793 map = short_external_ascii_string_map();
1794 } else if (length <= String::kMaxMediumStringSize) {
1795 map = medium_external_ascii_string_map();
1796 } else {
1797 map = long_external_ascii_string_map();
1798 }
1799
1800 Object* result = Allocate(map, NEW_SPACE);
1801 if (result->IsFailure()) return result;
1802
1803 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1804 external_string->set_length(length);
1805 external_string->set_resource(resource);
1806
1807 return result;
1808}
1809
1810
1811Object* Heap::AllocateExternalStringFromTwoByte(
1812 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001813 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001814
ager@chromium.org6f10e412009-02-13 10:11:16 +00001815 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001816 Object* result = Allocate(map, NEW_SPACE);
1817 if (result->IsFailure()) return result;
1818
1819 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1820 external_string->set_length(length);
1821 external_string->set_resource(resource);
1822
1823 return result;
1824}
1825
1826
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001827Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001828 if (code <= String::kMaxAsciiCharCode) {
1829 Object* value = Heap::single_character_string_cache()->get(code);
1830 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001831
1832 char buffer[1];
1833 buffer[0] = static_cast<char>(code);
1834 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1835
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001836 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001837 Heap::single_character_string_cache()->set(code, result);
1838 return result;
1839 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001840
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001841 Object* result = Heap::AllocateRawTwoByteString(1);
1842 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001843 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001844 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001845 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001846}
1847
1848
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001849Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1850 if (pretenure == NOT_TENURED) {
1851 return AllocateByteArray(length);
1852 }
1853 int size = ByteArray::SizeFor(length);
1854 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001855 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001856
1857 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1858
1859 if (result->IsFailure()) return result;
1860
1861 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1862 reinterpret_cast<Array*>(result)->set_length(length);
1863 return result;
1864}
1865
1866
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001867Object* Heap::AllocateByteArray(int length) {
1868 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001869 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001870 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001871
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001872 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001873
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001874 if (result->IsFailure()) return result;
1875
1876 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1877 reinterpret_cast<Array*>(result)->set_length(length);
1878 return result;
1879}
1880
1881
ager@chromium.org6f10e412009-02-13 10:11:16 +00001882void Heap::CreateFillerObjectAt(Address addr, int size) {
1883 if (size == 0) return;
1884 HeapObject* filler = HeapObject::FromAddress(addr);
1885 if (size == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001886 filler->set_map(Heap::one_pointer_filler_map());
ager@chromium.org6f10e412009-02-13 10:11:16 +00001887 } else {
1888 filler->set_map(Heap::byte_array_map());
1889 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1890 }
1891}
1892
1893
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001894Object* Heap::AllocatePixelArray(int length,
1895 uint8_t* external_pointer,
1896 PretenureFlag pretenure) {
1897 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1898
1899 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
1900
1901 if (result->IsFailure()) return result;
1902
1903 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
1904 reinterpret_cast<PixelArray*>(result)->set_length(length);
1905 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
1906
1907 return result;
1908}
1909
1910
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001911Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001912 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001913 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001914 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001915 // Compute size
1916 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1917 int sinfo_size = 0;
1918 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1919 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001920 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001921 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001922 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001923 result = lo_space_->AllocateRawCode(obj_size);
1924 } else {
1925 result = code_space_->AllocateRaw(obj_size);
1926 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001927
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001928 if (result->IsFailure()) return result;
1929
1930 // Initialize the object
1931 HeapObject::cast(result)->set_map(code_map());
1932 Code* code = Code::cast(result);
1933 code->set_instruction_size(desc.instr_size);
1934 code->set_relocation_size(desc.reloc_size);
1935 code->set_sinfo_size(sinfo_size);
1936 code->set_flags(flags);
1937 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001938 // Allow self references to created code object by patching the handle to
1939 // point to the newly allocated Code object.
1940 if (!self_reference.is_null()) {
1941 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001942 }
1943 // Migrate generated code.
1944 // The generated code can contain Object** values (typically from handles)
1945 // that are dereferenced during the copy to point directly to the actual heap
1946 // objects. These pointers can include references to the code object itself,
1947 // through the self_reference parameter.
1948 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001949 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1950
1951#ifdef DEBUG
1952 code->Verify();
1953#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001954 return code;
1955}
1956
1957
1958Object* Heap::CopyCode(Code* code) {
1959 // Allocate an object the same size as the code object.
1960 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001961 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001962 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001963 result = lo_space_->AllocateRawCode(obj_size);
1964 } else {
1965 result = code_space_->AllocateRaw(obj_size);
1966 }
1967
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001968 if (result->IsFailure()) return result;
1969
1970 // Copy code object.
1971 Address old_addr = code->address();
1972 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001973 CopyBlock(reinterpret_cast<Object**>(new_addr),
1974 reinterpret_cast<Object**>(old_addr),
1975 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001976 // Relocate the copy.
1977 Code* new_code = Code::cast(result);
1978 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001979 return new_code;
1980}
1981
1982
1983Object* Heap::Allocate(Map* map, AllocationSpace space) {
1984 ASSERT(gc_state_ == NOT_IN_GC);
1985 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001986 Object* result = AllocateRaw(map->instance_size(),
1987 space,
1988 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001989 if (result->IsFailure()) return result;
1990 HeapObject::cast(result)->set_map(map);
1991 return result;
1992}
1993
1994
1995Object* Heap::InitializeFunction(JSFunction* function,
1996 SharedFunctionInfo* shared,
1997 Object* prototype) {
1998 ASSERT(!prototype->IsMap());
1999 function->initialize_properties();
2000 function->initialize_elements();
2001 function->set_shared(shared);
2002 function->set_prototype_or_initial_map(prototype);
2003 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002004 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002005 return function;
2006}
2007
2008
2009Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002010 // Allocate the prototype. Make sure to use the object function
2011 // from the function's context, since the function can be from a
2012 // different context.
2013 JSFunction* object_function =
2014 function->context()->global_context()->object_function();
2015 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002016 if (prototype->IsFailure()) return prototype;
2017 // When creating the prototype for the function we must set its
2018 // constructor to the function.
2019 Object* result =
2020 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2021 function,
2022 DONT_ENUM);
2023 if (result->IsFailure()) return result;
2024 return prototype;
2025}
2026
2027
2028Object* Heap::AllocateFunction(Map* function_map,
2029 SharedFunctionInfo* shared,
2030 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002031 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002032 if (result->IsFailure()) return result;
2033 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2034}
2035
2036
2037Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002038 // To get fast allocation and map sharing for arguments objects we
2039 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002040
2041 // This calls Copy directly rather than using Heap::AllocateRaw so we
2042 // duplicate the check here.
2043 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2044
2045 JSObject* boilerplate =
2046 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002047
2048 // Make the clone.
2049 Map* map = boilerplate->map();
2050 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002051 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002052 if (result->IsFailure()) return result;
2053
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002054 // Copy the content. The arguments boilerplate doesn't have any
2055 // fields that point to new space so it's safe to skip the write
2056 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002057 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2058 reinterpret_cast<Object**>(boilerplate->address()),
2059 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002060
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002061 // Set the two properties.
2062 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002063 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002064 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2065 Smi::FromInt(length),
2066 SKIP_WRITE_BARRIER);
2067
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002068 // Check the state of the object
2069 ASSERT(JSObject::cast(result)->HasFastProperties());
2070 ASSERT(JSObject::cast(result)->HasFastElements());
2071
2072 return result;
2073}
2074
2075
2076Object* Heap::AllocateInitialMap(JSFunction* fun) {
2077 ASSERT(!fun->has_initial_map());
2078
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002079 // First create a new map with the size and number of in-object properties
2080 // suggested by the function.
2081 int instance_size = fun->shared()->CalculateInstanceSize();
2082 int in_object_properties = fun->shared()->CalculateInObjectProperties();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002083 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002084 if (map_obj->IsFailure()) return map_obj;
2085
2086 // Fetch or allocate prototype.
2087 Object* prototype;
2088 if (fun->has_instance_prototype()) {
2089 prototype = fun->instance_prototype();
2090 } else {
2091 prototype = AllocateFunctionPrototype(fun);
2092 if (prototype->IsFailure()) return prototype;
2093 }
2094 Map* map = Map::cast(map_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002095 map->set_inobject_properties(in_object_properties);
2096 map->set_unused_property_fields(in_object_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002097 map->set_prototype(prototype);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002098
2099 // If the function has only simple this property assignments add field
2100 // descriptors for these to the initial map as the object cannot be
2101 // constructed without having these properties.
2102 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
2103 if (fun->shared()->has_only_this_property_assignments() &&
2104 fun->shared()->this_property_assignments_count() > 0) {
2105 int count = fun->shared()->this_property_assignments_count();
2106 if (count > in_object_properties) {
2107 count = in_object_properties;
2108 }
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00002109 Object* descriptors_obj = DescriptorArray::Allocate(count);
2110 if (descriptors_obj->IsFailure()) return descriptors_obj;
2111 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002112 for (int i = 0; i < count; i++) {
2113 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2114 ASSERT(name->IsSymbol());
2115 FieldDescriptor field(name, i, NONE);
2116 descriptors->Set(i, &field);
2117 }
2118 descriptors->Sort();
2119 map->set_instance_descriptors(descriptors);
2120 map->set_pre_allocated_property_fields(count);
2121 map->set_unused_property_fields(in_object_properties - count);
2122 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002123 return map;
2124}
2125
2126
2127void Heap::InitializeJSObjectFromMap(JSObject* obj,
2128 FixedArray* properties,
2129 Map* map) {
2130 obj->set_properties(properties);
2131 obj->initialize_elements();
2132 // TODO(1240798): Initialize the object's body using valid initial values
2133 // according to the object's initial map. For example, if the map's
2134 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2135 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2136 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2137 // verification code has to cope with (temporarily) invalid objects. See
2138 // for example, JSArray::JSArrayVerify).
2139 obj->InitializeBody(map->instance_size());
2140}
2141
2142
2143Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2144 // JSFunctions should be allocated using AllocateFunction to be
2145 // properly initialized.
2146 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2147
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002148 // Both types of globla objects should be allocated using
2149 // AllocateGloblaObject to be properly initialized.
2150 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2151 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2152
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002153 // Allocate the backing storage for the properties.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002154 int prop_size =
2155 map->pre_allocated_property_fields() +
2156 map->unused_property_fields() -
2157 map->inobject_properties();
2158 ASSERT(prop_size >= 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002159 Object* properties = AllocateFixedArray(prop_size, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002160 if (properties->IsFailure()) return properties;
2161
2162 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002163 AllocationSpace space =
2164 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002165 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002166 Object* obj = Allocate(map, space);
2167 if (obj->IsFailure()) return obj;
2168
2169 // Initialize the JSObject.
2170 InitializeJSObjectFromMap(JSObject::cast(obj),
2171 FixedArray::cast(properties),
2172 map);
2173 return obj;
2174}
2175
2176
2177Object* Heap::AllocateJSObject(JSFunction* constructor,
2178 PretenureFlag pretenure) {
2179 // Allocate the initial map if absent.
2180 if (!constructor->has_initial_map()) {
2181 Object* initial_map = AllocateInitialMap(constructor);
2182 if (initial_map->IsFailure()) return initial_map;
2183 constructor->set_initial_map(Map::cast(initial_map));
2184 Map::cast(initial_map)->set_constructor(constructor);
2185 }
2186 // Allocate the object based on the constructors initial map.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002187 Object* result =
2188 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2189 // Make sure result is NOT a global object if valid.
2190 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2191 return result;
2192}
2193
2194
2195Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2196 ASSERT(constructor->has_initial_map());
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002197 Map* map = constructor->initial_map();
2198
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002199 // Make sure no field properties are described in the initial map.
2200 // This guarantees us that normalizing the properties does not
2201 // require us to change property values to JSGlobalPropertyCells.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002202 ASSERT(map->NextFreePropertyIndex() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002203
2204 // Make sure we don't have a ton of pre-allocated slots in the
2205 // global objects. They will be unused once we normalize the object.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002206 ASSERT(map->unused_property_fields() == 0);
2207 ASSERT(map->inobject_properties() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002208
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002209 // Initial size of the backing store to avoid resize of the storage during
2210 // bootstrapping. The size differs between the JS global object ad the
2211 // builtins object.
2212 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002213
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002214 // Allocate a dictionary object for backing storage.
2215 Object* obj =
2216 StringDictionary::Allocate(
2217 map->NumberOfDescribedProperties() * 2 + initial_size);
2218 if (obj->IsFailure()) return obj;
2219 StringDictionary* dictionary = StringDictionary::cast(obj);
2220
2221 // The global object might be created from an object template with accessors.
2222 // Fill these accessors into the dictionary.
2223 DescriptorArray* descs = map->instance_descriptors();
2224 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2225 PropertyDetails details = descs->GetDetails(i);
2226 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2227 PropertyDetails d =
2228 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2229 Object* value = descs->GetCallbacksObject(i);
2230 value = Heap::AllocateJSGlobalPropertyCell(value);
2231 if (value->IsFailure()) return value;
2232
2233 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2234 if (result->IsFailure()) return result;
2235 dictionary = StringDictionary::cast(result);
2236 }
2237
2238 // Allocate the global object and initialize it with the backing store.
2239 obj = Allocate(map, OLD_POINTER_SPACE);
2240 if (obj->IsFailure()) return obj;
2241 JSObject* global = JSObject::cast(obj);
2242 InitializeJSObjectFromMap(global, dictionary, map);
2243
2244 // Create a new map for the global object.
2245 obj = map->CopyDropDescriptors();
2246 if (obj->IsFailure()) return obj;
2247 Map* new_map = Map::cast(obj);
2248
2249 // Setup the global object as a normalized object.
2250 global->set_map(new_map);
2251 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2252 global->set_properties(dictionary);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002253
2254 // Make sure result is a global object with properties in dictionary.
2255 ASSERT(global->IsGlobalObject());
2256 ASSERT(!global->HasFastProperties());
2257 return global;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002258}
2259
2260
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002261Object* Heap::CopyJSObject(JSObject* source) {
2262 // Never used to copy functions. If functions need to be copied we
2263 // have to be careful to clear the literals array.
2264 ASSERT(!source->IsJSFunction());
2265
2266 // Make the clone.
2267 Map* map = source->map();
2268 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002269 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002270
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002271 // If we're forced to always allocate, we use the general allocation
2272 // functions which may leave us with an object in old space.
2273 if (always_allocate()) {
2274 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2275 if (clone->IsFailure()) return clone;
2276 Address clone_address = HeapObject::cast(clone)->address();
2277 CopyBlock(reinterpret_cast<Object**>(clone_address),
2278 reinterpret_cast<Object**>(source->address()),
2279 object_size);
2280 // Update write barrier for all fields that lie beyond the header.
2281 for (int offset = JSObject::kHeaderSize;
2282 offset < object_size;
2283 offset += kPointerSize) {
2284 RecordWrite(clone_address, offset);
2285 }
2286 } else {
2287 clone = new_space_.AllocateRaw(object_size);
2288 if (clone->IsFailure()) return clone;
2289 ASSERT(Heap::InNewSpace(clone));
2290 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002291 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002292 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2293 reinterpret_cast<Object**>(source->address()),
2294 object_size);
2295 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002296
2297 FixedArray* elements = FixedArray::cast(source->elements());
2298 FixedArray* properties = FixedArray::cast(source->properties());
2299 // Update elements if necessary.
2300 if (elements->length()> 0) {
2301 Object* elem = CopyFixedArray(elements);
2302 if (elem->IsFailure()) return elem;
2303 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2304 }
2305 // Update properties if necessary.
2306 if (properties->length() > 0) {
2307 Object* prop = CopyFixedArray(properties);
2308 if (prop->IsFailure()) return prop;
2309 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2310 }
2311 // Return the new clone.
2312 return clone;
2313}
2314
2315
2316Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2317 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002318 // Allocate initial map if absent.
2319 if (!constructor->has_initial_map()) {
2320 Object* initial_map = AllocateInitialMap(constructor);
2321 if (initial_map->IsFailure()) return initial_map;
2322 constructor->set_initial_map(Map::cast(initial_map));
2323 Map::cast(initial_map)->set_constructor(constructor);
2324 }
2325
2326 Map* map = constructor->initial_map();
2327
2328 // Check that the already allocated object has the same size as
2329 // objects allocated using the constructor.
2330 ASSERT(map->instance_size() == object->map()->instance_size());
2331
2332 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002333 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002334 Object* properties = AllocateFixedArray(prop_size, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002335 if (properties->IsFailure()) return properties;
2336
2337 // Reset the map for the object.
2338 object->set_map(constructor->initial_map());
2339
2340 // Reinitialize the object from the constructor map.
2341 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2342 return object;
2343}
2344
2345
2346Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2347 PretenureFlag pretenure) {
2348 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2349 if (result->IsFailure()) return result;
2350
2351 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002352 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002353 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002354 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002355 }
2356 return result;
2357}
2358
2359
2360Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2361 PretenureFlag pretenure) {
2362 // Count the number of characters in the UTF-8 string and check if
2363 // it is an ASCII string.
2364 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2365 decoder->Reset(string.start(), string.length());
2366 int chars = 0;
2367 bool is_ascii = true;
2368 while (decoder->has_more()) {
2369 uc32 r = decoder->GetNext();
2370 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2371 chars++;
2372 }
2373
2374 // If the string is ascii, we do not need to convert the characters
2375 // since UTF8 is backwards compatible with ascii.
2376 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2377
2378 Object* result = AllocateRawTwoByteString(chars, pretenure);
2379 if (result->IsFailure()) return result;
2380
2381 // Convert and copy the characters into the new object.
2382 String* string_result = String::cast(result);
2383 decoder->Reset(string.start(), string.length());
2384 for (int i = 0; i < chars; i++) {
2385 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002386 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002387 }
2388 return result;
2389}
2390
2391
2392Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2393 PretenureFlag pretenure) {
2394 // Check if the string is an ASCII string.
2395 int i = 0;
2396 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2397
2398 Object* result;
2399 if (i == string.length()) { // It's an ASCII string.
2400 result = AllocateRawAsciiString(string.length(), pretenure);
2401 } else { // It's not an ASCII string.
2402 result = AllocateRawTwoByteString(string.length(), pretenure);
2403 }
2404 if (result->IsFailure()) return result;
2405
2406 // Copy the characters into the new object, which may be either ASCII or
2407 // UTF-16.
2408 String* string_result = String::cast(result);
2409 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002410 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002411 }
2412 return result;
2413}
2414
2415
2416Map* Heap::SymbolMapForString(String* string) {
2417 // If the string is in new space it cannot be used as a symbol.
2418 if (InNewSpace(string)) return NULL;
2419
2420 // Find the corresponding symbol map for strings.
2421 Map* map = string->map();
2422
2423 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2424 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2425 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2426
2427 if (map == short_string_map()) return short_symbol_map();
2428 if (map == medium_string_map()) return medium_symbol_map();
2429 if (map == long_string_map()) return long_symbol_map();
2430
2431 if (map == short_cons_string_map()) return short_cons_symbol_map();
2432 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2433 if (map == long_cons_string_map()) return long_cons_symbol_map();
2434
2435 if (map == short_cons_ascii_string_map()) {
2436 return short_cons_ascii_symbol_map();
2437 }
2438 if (map == medium_cons_ascii_string_map()) {
2439 return medium_cons_ascii_symbol_map();
2440 }
2441 if (map == long_cons_ascii_string_map()) {
2442 return long_cons_ascii_symbol_map();
2443 }
2444
2445 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002446 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2447 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002448
2449 if (map == short_sliced_ascii_string_map()) {
2450 return short_sliced_ascii_symbol_map();
2451 }
2452 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002453 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002454 }
2455 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002456 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002457 }
2458
ager@chromium.org6f10e412009-02-13 10:11:16 +00002459 if (map == short_external_string_map()) {
2460 return short_external_symbol_map();
2461 }
2462 if (map == medium_external_string_map()) {
2463 return medium_external_symbol_map();
2464 }
2465 if (map == long_external_string_map()) {
2466 return long_external_symbol_map();
2467 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002468
2469 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002470 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002471 }
2472 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002473 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002474 }
2475 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002476 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002477 }
2478
2479 // No match found.
2480 return NULL;
2481}
2482
2483
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002484Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2485 int chars,
2486 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002487 // Ensure the chars matches the number of characters in the buffer.
2488 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2489 // Determine whether the string is ascii.
2490 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002491 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002492 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2493 }
2494 buffer->Rewind();
2495
2496 // Compute map and object size.
2497 int size;
2498 Map* map;
2499
2500 if (is_ascii) {
2501 if (chars <= String::kMaxShortStringSize) {
2502 map = short_ascii_symbol_map();
2503 } else if (chars <= String::kMaxMediumStringSize) {
2504 map = medium_ascii_symbol_map();
2505 } else {
2506 map = long_ascii_symbol_map();
2507 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002508 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002509 } else {
2510 if (chars <= String::kMaxShortStringSize) {
2511 map = short_symbol_map();
2512 } else if (chars <= String::kMaxMediumStringSize) {
2513 map = medium_symbol_map();
2514 } else {
2515 map = long_symbol_map();
2516 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002517 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002518 }
2519
2520 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002521 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002522 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002523 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002524 if (result->IsFailure()) return result;
2525
2526 reinterpret_cast<HeapObject*>(result)->set_map(map);
2527 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002528 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002529 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002530
ager@chromium.org870a0b62008-11-04 11:43:05 +00002531 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002532
2533 // Fill in the characters.
2534 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002535 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002536 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002537 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002538}
2539
2540
2541Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002542 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002543 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002544
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002545 Object* result = Failure::OutOfMemoryException();
2546 if (space == NEW_SPACE) {
2547 result = size <= kMaxObjectSizeInNewSpace
2548 ? new_space_.AllocateRaw(size)
2549 : lo_space_->AllocateRawFixedArray(size);
2550 } else {
2551 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2552 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2553 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002554 if (result->IsFailure()) return result;
2555
2556 // Determine the map based on the string's length.
2557 Map* map;
2558 if (length <= String::kMaxShortStringSize) {
2559 map = short_ascii_string_map();
2560 } else if (length <= String::kMaxMediumStringSize) {
2561 map = medium_ascii_string_map();
2562 } else {
2563 map = long_ascii_string_map();
2564 }
2565
2566 // Partially initialize the object.
2567 HeapObject::cast(result)->set_map(map);
2568 String::cast(result)->set_length(length);
2569 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2570 return result;
2571}
2572
2573
2574Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002575 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002576 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002577
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002578 Object* result = Failure::OutOfMemoryException();
2579 if (space == NEW_SPACE) {
2580 result = size <= kMaxObjectSizeInNewSpace
2581 ? new_space_.AllocateRaw(size)
2582 : lo_space_->AllocateRawFixedArray(size);
2583 } else {
2584 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2585 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2586 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002587 if (result->IsFailure()) return result;
2588
2589 // Determine the map based on the string's length.
2590 Map* map;
2591 if (length <= String::kMaxShortStringSize) {
2592 map = short_string_map();
2593 } else if (length <= String::kMaxMediumStringSize) {
2594 map = medium_string_map();
2595 } else {
2596 map = long_string_map();
2597 }
2598
2599 // Partially initialize the object.
2600 HeapObject::cast(result)->set_map(map);
2601 String::cast(result)->set_length(length);
2602 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2603 return result;
2604}
2605
2606
2607Object* Heap::AllocateEmptyFixedArray() {
2608 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002609 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002610 if (result->IsFailure()) return result;
2611 // Initialize the object.
2612 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2613 reinterpret_cast<Array*>(result)->set_length(0);
2614 return result;
2615}
2616
2617
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002618Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002619 // Use the general function if we're forced to always allocate.
2620 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002621 // Allocate the raw data for a fixed array.
2622 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002623 return size <= kMaxObjectSizeInNewSpace
2624 ? new_space_.AllocateRaw(size)
2625 : lo_space_->AllocateRawFixedArray(size);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002626}
2627
2628
2629Object* Heap::CopyFixedArray(FixedArray* src) {
2630 int len = src->length();
2631 Object* obj = AllocateRawFixedArray(len);
2632 if (obj->IsFailure()) return obj;
2633 if (Heap::InNewSpace(obj)) {
2634 HeapObject* dst = HeapObject::cast(obj);
2635 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2636 reinterpret_cast<Object**>(src->address()),
2637 FixedArray::SizeFor(len));
2638 return obj;
2639 }
2640 HeapObject::cast(obj)->set_map(src->map());
2641 FixedArray* result = FixedArray::cast(obj);
2642 result->set_length(len);
2643 // Copy the content
2644 WriteBarrierMode mode = result->GetWriteBarrierMode();
2645 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2646 return result;
2647}
2648
2649
2650Object* Heap::AllocateFixedArray(int length) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002651 ASSERT(length >= 0);
ager@chromium.org32912102009-01-16 10:38:43 +00002652 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002653 Object* result = AllocateRawFixedArray(length);
2654 if (!result->IsFailure()) {
2655 // Initialize header.
2656 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2657 FixedArray* array = FixedArray::cast(result);
2658 array->set_length(length);
2659 Object* value = undefined_value();
2660 // Initialize body.
2661 for (int index = 0; index < length; index++) {
2662 array->set(index, value, SKIP_WRITE_BARRIER);
2663 }
2664 }
2665 return result;
2666}
2667
2668
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002669Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2670 ASSERT(empty_fixed_array()->IsFixedArray());
2671 if (length == 0) return empty_fixed_array();
2672
2673 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002674 Object* result = Failure::OutOfMemoryException();
2675 if (pretenure != TENURED) {
2676 result = size <= kMaxObjectSizeInNewSpace
2677 ? new_space_.AllocateRaw(size)
2678 : lo_space_->AllocateRawFixedArray(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002679 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002680 if (result->IsFailure()) {
2681 if (size > MaxObjectSizeInPagedSpace()) {
2682 result = lo_space_->AllocateRawFixedArray(size);
2683 } else {
2684 AllocationSpace space =
2685 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2686 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
2687 }
2688 if (result->IsFailure()) return result;
2689 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002690 // Initialize the object.
2691 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2692 FixedArray* array = FixedArray::cast(result);
2693 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002694 Object* value = undefined_value();
2695 for (int index = 0; index < length; index++) {
2696 array->set(index, value, SKIP_WRITE_BARRIER);
2697 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002698 return array;
2699}
2700
2701
2702Object* Heap::AllocateFixedArrayWithHoles(int length) {
2703 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002704 Object* result = AllocateRawFixedArray(length);
2705 if (!result->IsFailure()) {
2706 // Initialize header.
2707 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2708 FixedArray* array = FixedArray::cast(result);
2709 array->set_length(length);
2710 // Initialize body.
2711 Object* value = the_hole_value();
2712 for (int index = 0; index < length; index++) {
2713 array->set(index, value, SKIP_WRITE_BARRIER);
2714 }
2715 }
2716 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002717}
2718
2719
2720Object* Heap::AllocateHashTable(int length) {
2721 Object* result = Heap::AllocateFixedArray(length);
2722 if (result->IsFailure()) return result;
2723 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00002724 ASSERT(result->IsHashTable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002725 return result;
2726}
2727
2728
2729Object* Heap::AllocateGlobalContext() {
2730 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2731 if (result->IsFailure()) return result;
2732 Context* context = reinterpret_cast<Context*>(result);
2733 context->set_map(global_context_map());
2734 ASSERT(context->IsGlobalContext());
2735 ASSERT(result->IsContext());
2736 return result;
2737}
2738
2739
2740Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2741 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2742 Object* result = Heap::AllocateFixedArray(length);
2743 if (result->IsFailure()) return result;
2744 Context* context = reinterpret_cast<Context*>(result);
2745 context->set_map(context_map());
2746 context->set_closure(function);
2747 context->set_fcontext(context);
2748 context->set_previous(NULL);
2749 context->set_extension(NULL);
2750 context->set_global(function->context()->global());
2751 ASSERT(!context->IsGlobalContext());
2752 ASSERT(context->is_function_context());
2753 ASSERT(result->IsContext());
2754 return result;
2755}
2756
2757
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002758Object* Heap::AllocateWithContext(Context* previous,
2759 JSObject* extension,
2760 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002761 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2762 if (result->IsFailure()) return result;
2763 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002764 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002765 context->set_closure(previous->closure());
2766 context->set_fcontext(previous->fcontext());
2767 context->set_previous(previous);
2768 context->set_extension(extension);
2769 context->set_global(previous->global());
2770 ASSERT(!context->IsGlobalContext());
2771 ASSERT(!context->is_function_context());
2772 ASSERT(result->IsContext());
2773 return result;
2774}
2775
2776
2777Object* Heap::AllocateStruct(InstanceType type) {
2778 Map* map;
2779 switch (type) {
2780#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2781STRUCT_LIST(MAKE_CASE)
2782#undef MAKE_CASE
2783 default:
2784 UNREACHABLE();
2785 return Failure::InternalError();
2786 }
2787 int size = map->instance_size();
2788 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002789 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002790 Object* result = Heap::Allocate(map, space);
2791 if (result->IsFailure()) return result;
2792 Struct::cast(result)->InitializeBody(size);
2793 return result;
2794}
2795
2796
ager@chromium.org96c75b52009-08-26 09:13:16 +00002797bool Heap::IdleNotification() {
2798 static const int kIdlesBeforeCollection = 7;
2799 static int number_idle_notifications = 0;
2800 static int last_gc_count = gc_count_;
2801
2802 bool finished = false;
2803
2804 if (last_gc_count == gc_count_) {
2805 number_idle_notifications++;
2806 } else {
2807 number_idle_notifications = 0;
2808 last_gc_count = gc_count_;
2809 }
2810
2811 if (number_idle_notifications >= kIdlesBeforeCollection) {
2812 // The first time through we collect without forcing compaction.
2813 // The second time through we force compaction and quit.
2814 bool force_compaction =
2815 number_idle_notifications > kIdlesBeforeCollection;
2816 CollectAllGarbage(force_compaction);
2817 last_gc_count = gc_count_;
2818 if (force_compaction) {
ager@chromium.org439e85a2009-08-26 13:15:29 +00002819 // Shrink new space.
2820 new_space_.Shrink();
ager@chromium.org96c75b52009-08-26 09:13:16 +00002821 number_idle_notifications = 0;
2822 finished = true;
2823 }
2824 }
2825
2826 // Uncommit unused memory in new space.
2827 Heap::UncommitFromSpace();
2828 return finished;
2829}
2830
2831
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002832#ifdef DEBUG
2833
2834void Heap::Print() {
2835 if (!HasBeenSetup()) return;
2836 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002837 AllSpaces spaces;
2838 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002839}
2840
2841
2842void Heap::ReportCodeStatistics(const char* title) {
2843 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2844 PagedSpace::ResetCodeStatistics();
2845 // We do not look for code in new space, map space, or old space. If code
2846 // somehow ends up in those spaces, we would miss it here.
2847 code_space_->CollectCodeStatistics();
2848 lo_space_->CollectCodeStatistics();
2849 PagedSpace::ReportCodeStatistics();
2850}
2851
2852
2853// This function expects that NewSpace's allocated objects histogram is
2854// populated (via a call to CollectStatistics or else as a side effect of a
2855// just-completed scavenge collection).
2856void Heap::ReportHeapStatistics(const char* title) {
2857 USE(title);
2858 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2859 title, gc_count_);
2860 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002861 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2862 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002863
2864 PrintF("\n");
2865 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2866 GlobalHandles::PrintStats();
2867 PrintF("\n");
2868
2869 PrintF("Heap statistics : ");
2870 MemoryAllocator::ReportStatistics();
2871 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002872 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002873 PrintF("Old pointer space : ");
2874 old_pointer_space_->ReportStatistics();
2875 PrintF("Old data space : ");
2876 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002877 PrintF("Code space : ");
2878 code_space_->ReportStatistics();
2879 PrintF("Map space : ");
2880 map_space_->ReportStatistics();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002881 PrintF("Cell space : ");
2882 cell_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002883 PrintF("Large object space : ");
2884 lo_space_->ReportStatistics();
2885 PrintF(">>>>>> ========================================= >>>>>>\n");
2886}
2887
2888#endif // DEBUG
2889
2890bool Heap::Contains(HeapObject* value) {
2891 return Contains(value->address());
2892}
2893
2894
2895bool Heap::Contains(Address addr) {
2896 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2897 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002898 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002899 old_pointer_space_->Contains(addr) ||
2900 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002901 code_space_->Contains(addr) ||
2902 map_space_->Contains(addr) ||
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002903 cell_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002904 lo_space_->SlowContains(addr));
2905}
2906
2907
2908bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2909 return InSpace(value->address(), space);
2910}
2911
2912
2913bool Heap::InSpace(Address addr, AllocationSpace space) {
2914 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2915 if (!HasBeenSetup()) return false;
2916
2917 switch (space) {
2918 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002919 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002920 case OLD_POINTER_SPACE:
2921 return old_pointer_space_->Contains(addr);
2922 case OLD_DATA_SPACE:
2923 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002924 case CODE_SPACE:
2925 return code_space_->Contains(addr);
2926 case MAP_SPACE:
2927 return map_space_->Contains(addr);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002928 case CELL_SPACE:
2929 return cell_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002930 case LO_SPACE:
2931 return lo_space_->SlowContains(addr);
2932 }
2933
2934 return false;
2935}
2936
2937
2938#ifdef DEBUG
2939void Heap::Verify() {
2940 ASSERT(HasBeenSetup());
2941
2942 VerifyPointersVisitor visitor;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002943 IterateRoots(&visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002944
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002945 new_space_.Verify();
2946
2947 VerifyPointersAndRSetVisitor rset_visitor;
2948 old_pointer_space_->Verify(&rset_visitor);
2949 map_space_->Verify(&rset_visitor);
2950
2951 VerifyPointersVisitor no_rset_visitor;
2952 old_data_space_->Verify(&no_rset_visitor);
2953 code_space_->Verify(&no_rset_visitor);
2954 cell_space_->Verify(&no_rset_visitor);
2955
2956 lo_space_->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002957}
2958#endif // DEBUG
2959
2960
2961Object* Heap::LookupSymbol(Vector<const char> string) {
2962 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002963 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002964 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002965 // Can't use set_symbol_table because SymbolTable::cast knows that
2966 // SymbolTable is a singleton and checks for identity.
2967 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002968 ASSERT(symbol != NULL);
2969 return symbol;
2970}
2971
2972
2973Object* Heap::LookupSymbol(String* string) {
2974 if (string->IsSymbol()) return string;
2975 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002976 Object* new_table = symbol_table()->LookupString(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002977 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002978 // Can't use set_symbol_table because SymbolTable::cast knows that
2979 // SymbolTable is a singleton and checks for identity.
2980 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002981 ASSERT(symbol != NULL);
2982 return symbol;
2983}
2984
2985
ager@chromium.org7c537e22008-10-16 08:43:32 +00002986bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2987 if (string->IsSymbol()) {
2988 *symbol = string;
2989 return true;
2990 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002991 return symbol_table()->LookupSymbolIfExists(string, symbol);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002992}
2993
2994
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002995#ifdef DEBUG
2996void Heap::ZapFromSpace() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002997 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002998 for (Address a = new_space_.FromSpaceLow();
2999 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003000 a += kPointerSize) {
3001 Memory::Address_at(a) = kFromSpaceZapValue;
3002 }
3003}
3004#endif // DEBUG
3005
3006
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003007int Heap::IterateRSetRange(Address object_start,
3008 Address object_end,
3009 Address rset_start,
3010 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003011 Address object_address = object_start;
3012 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003013 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003014
3015 // Loop over all the pointers in [object_start, object_end).
3016 while (object_address < object_end) {
3017 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003018 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003019 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003020 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003021 // Do not dereference pointers at or past object_end.
3022 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3023 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003024 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003025 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3026 }
3027 // If this pointer does not need to be remembered anymore, clear
3028 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003029 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003030 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003031 }
3032 object_address += kPointerSize;
3033 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003034 // Update the remembered set if it has changed.
3035 if (result_rset != rset_word) {
3036 Memory::uint32_at(rset_address) = result_rset;
3037 }
3038 } else {
3039 // No bits in the word were set. This is the common case.
3040 object_address += kPointerSize * kBitsPerInt;
3041 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003042 rset_address += kIntSize;
3043 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003044 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003045}
3046
3047
3048void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3049 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003050 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003051
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003052 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3053 "V8.RSetPaged",
3054 0,
3055 Page::kObjectAreaSize / kPointerSize,
3056 30);
3057
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003058 PageIterator it(space, PageIterator::PAGES_IN_USE);
3059 while (it.has_next()) {
3060 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003061 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3062 page->RSetStart(), copy_object_func);
3063 if (paged_rset_histogram != NULL) {
3064 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3065 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003066 }
3067}
3068
3069
3070#ifdef DEBUG
3071#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
3072#else
3073#define SYNCHRONIZE_TAG(tag)
3074#endif
3075
3076void Heap::IterateRoots(ObjectVisitor* v) {
3077 IterateStrongRoots(v);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003078 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003079 SYNCHRONIZE_TAG("symbol_table");
3080}
3081
3082
3083void Heap::IterateStrongRoots(ObjectVisitor* v) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003084 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003085 SYNCHRONIZE_TAG("strong_root_list");
3086
ager@chromium.org3b45ab52009-03-19 22:21:34 +00003087 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003088 SYNCHRONIZE_TAG("symbol");
3089
3090 Bootstrapper::Iterate(v);
3091 SYNCHRONIZE_TAG("bootstrapper");
3092 Top::Iterate(v);
3093 SYNCHRONIZE_TAG("top");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003094
3095#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003096 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003097#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003098 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003099 CompilationCache::Iterate(v);
3100 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003101
3102 // Iterate over local handles in handle scopes.
3103 HandleScopeImplementer::Iterate(v);
3104 SYNCHRONIZE_TAG("handlescope");
3105
3106 // Iterate over the builtin code objects and code stubs in the heap. Note
3107 // that it is not strictly necessary to iterate over code objects on
3108 // scavenge collections. We still do it here because this same function
3109 // is used by the mark-sweep collector and the deserializer.
3110 Builtins::IterateBuiltins(v);
3111 SYNCHRONIZE_TAG("builtins");
3112
3113 // Iterate over global handles.
3114 GlobalHandles::IterateRoots(v);
3115 SYNCHRONIZE_TAG("globalhandles");
3116
3117 // Iterate over pointers being held by inactive threads.
3118 ThreadManager::Iterate(v);
3119 SYNCHRONIZE_TAG("threadmanager");
3120}
3121#undef SYNCHRONIZE_TAG
3122
3123
3124// Flag is set when the heap has been configured. The heap can be repeatedly
3125// configured through the API until it is setup.
3126static bool heap_configured = false;
3127
3128// TODO(1236194): Since the heap size is configurable on the command line
3129// and through the API, we should gracefully handle the case that the heap
3130// size is not big enough to fit all the initial objects.
3131bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
3132 if (HasBeenSetup()) return false;
3133
3134 if (semispace_size > 0) semispace_size_ = semispace_size;
3135 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
3136
3137 // The new space size must be a power of two to support single-bit testing
3138 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00003139 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003140 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
3141 young_generation_size_ = 2 * semispace_size_;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003142 external_allocation_limit_ = 10 * semispace_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003143
3144 // The old generation is paged.
3145 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
3146
3147 heap_configured = true;
3148 return true;
3149}
3150
3151
kasper.lund7276f142008-07-30 08:49:36 +00003152bool Heap::ConfigureHeapDefault() {
3153 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
3154}
3155
3156
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003157int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003158 return old_pointer_space_->Size()
3159 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003160 + code_space_->Size()
3161 + map_space_->Size()
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003162 + cell_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003163 + lo_space_->Size();
3164}
3165
3166
kasper.lund7276f142008-07-30 08:49:36 +00003167int Heap::PromotedExternalMemorySize() {
3168 if (amount_of_external_allocated_memory_
3169 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3170 return amount_of_external_allocated_memory_
3171 - amount_of_external_allocated_memory_at_last_global_gc_;
3172}
3173
3174
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003175bool Heap::Setup(bool create_heap_objects) {
3176 // Initialize heap spaces and initial maps and objects. Whenever something
3177 // goes wrong, just return false. The caller should check the results and
3178 // call Heap::TearDown() to release allocated memory.
3179 //
3180 // If the heap is not yet configured (eg, through the API), configure it.
3181 // Configuration is based on the flags new-space-size (really the semispace
3182 // size) and old-space-size if set or the initial values of semispace_size_
3183 // and old_generation_size_ otherwise.
3184 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00003185 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003186 }
3187
3188 // Setup memory allocator and allocate an initial chunk of memory. The
3189 // initial chunk is double the size of the new space to ensure that we can
3190 // find a pair of semispaces that are contiguous and aligned to their size.
3191 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
3192 void* chunk
3193 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
3194 if (chunk == NULL) return false;
3195
3196 // Put the initial chunk of the old space at the start of the initial
3197 // chunk, then the two new space semispaces, then the initial chunk of
3198 // code space. Align the pair of semispaces to their size, which must be
3199 // a power of 2.
3200 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003201 Address code_space_start = reinterpret_cast<Address>(chunk);
3202 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
3203 Address old_space_start = new_space_start + young_generation_size_;
3204 int code_space_size = new_space_start - code_space_start;
3205 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003206
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003207 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003208 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003209
3210 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00003211 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003212 old_pointer_space_ =
3213 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
3214 if (old_pointer_space_ == NULL) return false;
3215 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
3216 return false;
3217 }
3218 old_data_space_ =
3219 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
3220 if (old_data_space_ == NULL) return false;
3221 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
3222 old_space_size >> 1)) {
3223 return false;
3224 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003225
3226 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00003227 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003228 code_space_ =
3229 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003230 if (code_space_ == NULL) return false;
3231 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
3232
3233 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00003234 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003235 if (map_space_ == NULL) return false;
3236 // Setting up a paged space without giving it a virtual memory range big
3237 // enough to hold at least a page will cause it to allocate.
3238 if (!map_space_->Setup(NULL, 0)) return false;
3239
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003240 // Initialize global property cell space.
3241 cell_space_ = new CellSpace(old_generation_size_, CELL_SPACE);
3242 if (cell_space_ == NULL) return false;
3243 // Setting up a paged space without giving it a virtual memory range big
3244 // enough to hold at least a page will cause it to allocate.
3245 if (!cell_space_->Setup(NULL, 0)) return false;
3246
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003247 // The large object code space may contain code or data. We set the memory
3248 // to be non-executable here for safety, but this means we need to enable it
3249 // explicitly when allocating large code objects.
3250 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003251 if (lo_space_ == NULL) return false;
3252 if (!lo_space_->Setup()) return false;
3253
3254 if (create_heap_objects) {
3255 // Create initial maps.
3256 if (!CreateInitialMaps()) return false;
3257 if (!CreateApiObjects()) return false;
3258
3259 // Create initial objects
3260 if (!CreateInitialObjects()) return false;
3261 }
3262
3263 LOG(IntEvent("heap-capacity", Capacity()));
3264 LOG(IntEvent("heap-available", Available()));
3265
3266 return true;
3267}
3268
3269
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003270void Heap::SetStackLimit(intptr_t limit) {
3271 // On 64 bit machines, pointers are generally out of range of Smis. We write
3272 // something that looks like an out of range Smi to the GC.
3273
3274 // Set up the special root array entry containing the stack guard.
3275 // This is actually an address, but the tag makes the GC ignore it.
3276 roots_[kStackLimitRootIndex] =
3277 reinterpret_cast<Object*>((limit & ~kSmiTagMask) | kSmiTag);
3278}
3279
3280
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003281void Heap::TearDown() {
3282 GlobalHandles::TearDown();
3283
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003284 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003285
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003286 if (old_pointer_space_ != NULL) {
3287 old_pointer_space_->TearDown();
3288 delete old_pointer_space_;
3289 old_pointer_space_ = NULL;
3290 }
3291
3292 if (old_data_space_ != NULL) {
3293 old_data_space_->TearDown();
3294 delete old_data_space_;
3295 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003296 }
3297
3298 if (code_space_ != NULL) {
3299 code_space_->TearDown();
3300 delete code_space_;
3301 code_space_ = NULL;
3302 }
3303
3304 if (map_space_ != NULL) {
3305 map_space_->TearDown();
3306 delete map_space_;
3307 map_space_ = NULL;
3308 }
3309
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003310 if (cell_space_ != NULL) {
3311 cell_space_->TearDown();
3312 delete cell_space_;
3313 cell_space_ = NULL;
3314 }
3315
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003316 if (lo_space_ != NULL) {
3317 lo_space_->TearDown();
3318 delete lo_space_;
3319 lo_space_ = NULL;
3320 }
3321
3322 MemoryAllocator::TearDown();
3323}
3324
3325
3326void Heap::Shrink() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003327 // Try to shrink all paged spaces.
3328 PagedSpaces spaces;
3329 while (PagedSpace* space = spaces.next()) space->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003330}
3331
3332
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003333#ifdef ENABLE_HEAP_PROTECTION
3334
3335void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003336 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003337 AllSpaces spaces;
3338 while (Space* space = spaces.next()) space->Protect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003339 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003340}
3341
3342
3343void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003344 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003345 AllSpaces spaces;
3346 while (Space* space = spaces.next()) space->Unprotect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003347 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003348}
3349
3350#endif
3351
3352
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003353#ifdef DEBUG
3354
3355class PrintHandleVisitor: public ObjectVisitor {
3356 public:
3357 void VisitPointers(Object** start, Object** end) {
3358 for (Object** p = start; p < end; p++)
3359 PrintF(" handle %p to %p\n", p, *p);
3360 }
3361};
3362
3363void Heap::PrintHandles() {
3364 PrintF("Handles:\n");
3365 PrintHandleVisitor v;
3366 HandleScopeImplementer::Iterate(&v);
3367}
3368
3369#endif
3370
3371
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003372Space* AllSpaces::next() {
3373 switch (counter_++) {
3374 case NEW_SPACE:
3375 return Heap::new_space();
3376 case OLD_POINTER_SPACE:
3377 return Heap::old_pointer_space();
3378 case OLD_DATA_SPACE:
3379 return Heap::old_data_space();
3380 case CODE_SPACE:
3381 return Heap::code_space();
3382 case MAP_SPACE:
3383 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003384 case CELL_SPACE:
3385 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003386 case LO_SPACE:
3387 return Heap::lo_space();
3388 default:
3389 return NULL;
3390 }
3391}
3392
3393
3394PagedSpace* PagedSpaces::next() {
3395 switch (counter_++) {
3396 case OLD_POINTER_SPACE:
3397 return Heap::old_pointer_space();
3398 case OLD_DATA_SPACE:
3399 return Heap::old_data_space();
3400 case CODE_SPACE:
3401 return Heap::code_space();
3402 case MAP_SPACE:
3403 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003404 case CELL_SPACE:
3405 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003406 default:
3407 return NULL;
3408 }
3409}
3410
3411
3412
3413OldSpace* OldSpaces::next() {
3414 switch (counter_++) {
3415 case OLD_POINTER_SPACE:
3416 return Heap::old_pointer_space();
3417 case OLD_DATA_SPACE:
3418 return Heap::old_data_space();
3419 case CODE_SPACE:
3420 return Heap::code_space();
3421 default:
3422 return NULL;
3423 }
3424}
3425
3426
kasper.lund7276f142008-07-30 08:49:36 +00003427SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3428}
3429
3430
3431SpaceIterator::~SpaceIterator() {
3432 // Delete active iterator if any.
3433 delete iterator_;
3434}
3435
3436
3437bool SpaceIterator::has_next() {
3438 // Iterate until no more spaces.
3439 return current_space_ != LAST_SPACE;
3440}
3441
3442
3443ObjectIterator* SpaceIterator::next() {
3444 if (iterator_ != NULL) {
3445 delete iterator_;
3446 iterator_ = NULL;
3447 // Move to the next space
3448 current_space_++;
3449 if (current_space_ > LAST_SPACE) {
3450 return NULL;
3451 }
3452 }
3453
3454 // Return iterator for the new current space.
3455 return CreateIterator();
3456}
3457
3458
3459// Create an iterator for the space to iterate.
3460ObjectIterator* SpaceIterator::CreateIterator() {
3461 ASSERT(iterator_ == NULL);
3462
3463 switch (current_space_) {
3464 case NEW_SPACE:
3465 iterator_ = new SemiSpaceIterator(Heap::new_space());
3466 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003467 case OLD_POINTER_SPACE:
3468 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3469 break;
3470 case OLD_DATA_SPACE:
3471 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003472 break;
3473 case CODE_SPACE:
3474 iterator_ = new HeapObjectIterator(Heap::code_space());
3475 break;
3476 case MAP_SPACE:
3477 iterator_ = new HeapObjectIterator(Heap::map_space());
3478 break;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003479 case CELL_SPACE:
3480 iterator_ = new HeapObjectIterator(Heap::cell_space());
3481 break;
kasper.lund7276f142008-07-30 08:49:36 +00003482 case LO_SPACE:
3483 iterator_ = new LargeObjectIterator(Heap::lo_space());
3484 break;
3485 }
3486
3487 // Return the newly allocated iterator;
3488 ASSERT(iterator_ != NULL);
3489 return iterator_;
3490}
3491
3492
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003493HeapIterator::HeapIterator() {
3494 Init();
3495}
3496
3497
3498HeapIterator::~HeapIterator() {
3499 Shutdown();
3500}
3501
3502
3503void HeapIterator::Init() {
3504 // Start the iteration.
3505 space_iterator_ = new SpaceIterator();
3506 object_iterator_ = space_iterator_->next();
3507}
3508
3509
3510void HeapIterator::Shutdown() {
3511 // Make sure the last iterator is deallocated.
3512 delete space_iterator_;
3513 space_iterator_ = NULL;
3514 object_iterator_ = NULL;
3515}
3516
3517
3518bool HeapIterator::has_next() {
3519 // No iterator means we are done.
3520 if (object_iterator_ == NULL) return false;
3521
3522 if (object_iterator_->has_next_object()) {
3523 // If the current iterator has more objects we are fine.
3524 return true;
3525 } else {
3526 // Go though the spaces looking for one that has objects.
3527 while (space_iterator_->has_next()) {
3528 object_iterator_ = space_iterator_->next();
3529 if (object_iterator_->has_next_object()) {
3530 return true;
3531 }
3532 }
3533 }
3534 // Done with the last space.
3535 object_iterator_ = NULL;
3536 return false;
3537}
3538
3539
3540HeapObject* HeapIterator::next() {
3541 if (has_next()) {
3542 return object_iterator_->next_object();
3543 } else {
3544 return NULL;
3545 }
3546}
3547
3548
3549void HeapIterator::reset() {
3550 // Restart the iterator.
3551 Shutdown();
3552 Init();
3553}
3554
3555
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003556#ifdef ENABLE_LOGGING_AND_PROFILING
3557namespace {
3558
3559// JSConstructorProfile is responsible for gathering and logging
3560// "constructor profile" of JS object allocated on heap.
3561// It is run during garbage collection cycle, thus it doesn't need
3562// to use handles.
3563class JSConstructorProfile BASE_EMBEDDED {
3564 public:
3565 JSConstructorProfile() : zscope_(DELETE_ON_EXIT) {}
3566 void CollectStats(JSObject* obj);
3567 void PrintStats();
3568 // Used by ZoneSplayTree::ForEach.
3569 void Call(String* name, const NumberAndSizeInfo& number_and_size);
3570 private:
3571 struct TreeConfig {
3572 typedef String* Key;
3573 typedef NumberAndSizeInfo Value;
3574 static const Key kNoKey;
3575 static const Value kNoValue;
3576 // Strings are unique, so it is sufficient to compare their pointers.
3577 static int Compare(const Key& a, const Key& b) {
3578 return a == b ? 0 : (a < b ? -1 : 1);
3579 }
3580 };
3581
3582 typedef ZoneSplayTree<TreeConfig> JSObjectsInfoTree;
3583 static int CalculateJSObjectNetworkSize(JSObject* obj);
3584
3585 ZoneScope zscope_;
3586 JSObjectsInfoTree js_objects_info_tree_;
3587};
3588
3589const JSConstructorProfile::TreeConfig::Key
3590 JSConstructorProfile::TreeConfig::kNoKey = NULL;
3591const JSConstructorProfile::TreeConfig::Value
3592 JSConstructorProfile::TreeConfig::kNoValue;
3593
3594
3595int JSConstructorProfile::CalculateJSObjectNetworkSize(JSObject* obj) {
3596 int size = obj->Size();
3597 // If 'properties' and 'elements' are non-empty (thus, non-shared),
3598 // take their size into account.
3599 if (FixedArray::cast(obj->properties())->length() != 0) {
3600 size += obj->properties()->Size();
3601 }
3602 if (FixedArray::cast(obj->elements())->length() != 0) {
3603 size += obj->elements()->Size();
3604 }
3605 return size;
3606}
3607
3608
3609void JSConstructorProfile::Call(String* name,
3610 const NumberAndSizeInfo& number_and_size) {
3611 SmartPointer<char> s_name;
3612 if (name != NULL) {
3613 s_name = name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
3614 }
3615 LOG(HeapSampleJSConstructorEvent(*s_name,
3616 number_and_size.number(),
3617 number_and_size.bytes()));
3618}
3619
3620
3621void JSConstructorProfile::CollectStats(JSObject* obj) {
3622 String* constructor_func = NULL;
3623 if (obj->map()->constructor()->IsJSFunction()) {
3624 JSFunction* constructor = JSFunction::cast(obj->map()->constructor());
3625 SharedFunctionInfo* sfi = constructor->shared();
3626 String* name = String::cast(sfi->name());
3627 constructor_func = name->length() > 0 ? name : sfi->inferred_name();
3628 } else if (obj->IsJSFunction()) {
3629 constructor_func = Heap::function_class_symbol();
3630 }
3631 JSObjectsInfoTree::Locator loc;
3632 if (!js_objects_info_tree_.Find(constructor_func, &loc)) {
3633 js_objects_info_tree_.Insert(constructor_func, &loc);
3634 }
3635 NumberAndSizeInfo number_and_size = loc.value();
3636 number_and_size.increment_number(1);
3637 number_and_size.increment_bytes(CalculateJSObjectNetworkSize(obj));
3638 loc.set_value(number_and_size);
3639}
3640
3641
3642void JSConstructorProfile::PrintStats() {
3643 js_objects_info_tree_.ForEach(this);
3644}
3645
3646} // namespace
3647#endif
3648
3649
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003650//
3651// HeapProfiler class implementation.
3652//
3653#ifdef ENABLE_LOGGING_AND_PROFILING
3654void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3655 InstanceType type = obj->map()->instance_type();
3656 ASSERT(0 <= type && type <= LAST_TYPE);
3657 info[type].increment_number(1);
3658 info[type].increment_bytes(obj->Size());
3659}
3660#endif
3661
3662
3663#ifdef ENABLE_LOGGING_AND_PROFILING
3664void HeapProfiler::WriteSample() {
3665 LOG(HeapSampleBeginEvent("Heap", "allocated"));
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003666 LOG(HeapSampleStats(
3667 "Heap", "allocated", Heap::Capacity(), Heap::SizeOfObjects()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003668
3669 HistogramInfo info[LAST_TYPE+1];
3670#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3671 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3672#undef DEF_TYPE_NAME
3673
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003674 JSConstructorProfile js_cons_profile;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003675 HeapIterator iterator;
3676 while (iterator.has_next()) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003677 HeapObject* obj = iterator.next();
3678 CollectStats(obj, info);
3679 if (obj->IsJSObject()) {
3680 js_cons_profile.CollectStats(JSObject::cast(obj));
3681 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003682 }
3683
3684 // Lump all the string types together.
3685 int string_number = 0;
3686 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003687#define INCREMENT_SIZE(type, size, name, camel_name) \
3688 string_number += info[type].number(); \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003689 string_bytes += info[type].bytes();
3690 STRING_TYPE_LIST(INCREMENT_SIZE)
3691#undef INCREMENT_SIZE
3692 if (string_bytes > 0) {
3693 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3694 }
3695
3696 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3697 if (info[i].bytes() > 0) {
3698 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3699 info[i].bytes()));
3700 }
3701 }
3702
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003703 js_cons_profile.PrintStats();
3704
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003705 LOG(HeapSampleEndEvent("Heap", "allocated"));
3706}
3707
3708
3709#endif
3710
3711
3712
3713#ifdef DEBUG
3714
3715static bool search_for_any_global;
3716static Object* search_target;
3717static bool found_target;
3718static List<Object*> object_stack(20);
3719
3720
3721// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3722static const int kMarkTag = 2;
3723
3724static void MarkObjectRecursively(Object** p);
3725class MarkObjectVisitor : public ObjectVisitor {
3726 public:
3727 void VisitPointers(Object** start, Object** end) {
3728 // Copy all HeapObject pointers in [start, end)
3729 for (Object** p = start; p < end; p++) {
3730 if ((*p)->IsHeapObject())
3731 MarkObjectRecursively(p);
3732 }
3733 }
3734};
3735
3736static MarkObjectVisitor mark_visitor;
3737
3738static void MarkObjectRecursively(Object** p) {
3739 if (!(*p)->IsHeapObject()) return;
3740
3741 HeapObject* obj = HeapObject::cast(*p);
3742
3743 Object* map = obj->map();
3744
3745 if (!map->IsHeapObject()) return; // visited before
3746
3747 if (found_target) return; // stop if target found
3748 object_stack.Add(obj);
3749 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3750 (!search_for_any_global && (obj == search_target))) {
3751 found_target = true;
3752 return;
3753 }
3754
3755 if (obj->IsCode()) {
3756 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3757 }
3758
3759 // not visited yet
3760 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3761
3762 Address map_addr = map_p->address();
3763
3764 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3765
3766 MarkObjectRecursively(&map);
3767
3768 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3769 &mark_visitor);
3770
3771 if (!found_target) // don't pop if found the target
3772 object_stack.RemoveLast();
3773}
3774
3775
3776static void UnmarkObjectRecursively(Object** p);
3777class UnmarkObjectVisitor : public ObjectVisitor {
3778 public:
3779 void VisitPointers(Object** start, Object** end) {
3780 // Copy all HeapObject pointers in [start, end)
3781 for (Object** p = start; p < end; p++) {
3782 if ((*p)->IsHeapObject())
3783 UnmarkObjectRecursively(p);
3784 }
3785 }
3786};
3787
3788static UnmarkObjectVisitor unmark_visitor;
3789
3790static void UnmarkObjectRecursively(Object** p) {
3791 if (!(*p)->IsHeapObject()) return;
3792
3793 HeapObject* obj = HeapObject::cast(*p);
3794
3795 Object* map = obj->map();
3796
3797 if (map->IsHeapObject()) return; // unmarked already
3798
3799 Address map_addr = reinterpret_cast<Address>(map);
3800
3801 map_addr -= kMarkTag;
3802
3803 ASSERT_TAG_ALIGNED(map_addr);
3804
3805 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3806
3807 obj->set_map(reinterpret_cast<Map*>(map_p));
3808
3809 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3810
3811 obj->IterateBody(Map::cast(map_p)->instance_type(),
3812 obj->SizeFromMap(Map::cast(map_p)),
3813 &unmark_visitor);
3814
3815 if (obj->IsCode()) {
3816 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3817 }
3818}
3819
3820
3821static void MarkRootObjectRecursively(Object** root) {
3822 if (search_for_any_global) {
3823 ASSERT(search_target == NULL);
3824 } else {
3825 ASSERT(search_target->IsHeapObject());
3826 }
3827 found_target = false;
3828 object_stack.Clear();
3829
3830 MarkObjectRecursively(root);
3831 UnmarkObjectRecursively(root);
3832
3833 if (found_target) {
3834 PrintF("=====================================\n");
3835 PrintF("==== Path to object ====\n");
3836 PrintF("=====================================\n\n");
3837
3838 ASSERT(!object_stack.is_empty());
3839 for (int i = 0; i < object_stack.length(); i++) {
3840 if (i > 0) PrintF("\n |\n |\n V\n\n");
3841 Object* obj = object_stack[i];
3842 obj->Print();
3843 }
3844 PrintF("=====================================\n");
3845 }
3846}
3847
3848
3849// Helper class for visiting HeapObjects recursively.
3850class MarkRootVisitor: public ObjectVisitor {
3851 public:
3852 void VisitPointers(Object** start, Object** end) {
3853 // Visit all HeapObject pointers in [start, end)
3854 for (Object** p = start; p < end; p++) {
3855 if ((*p)->IsHeapObject())
3856 MarkRootObjectRecursively(p);
3857 }
3858 }
3859};
3860
3861
3862// Triggers a depth-first traversal of reachable objects from roots
3863// and finds a path to a specific heap object and prints it.
3864void Heap::TracePathToObject() {
3865 search_target = NULL;
3866 search_for_any_global = false;
3867
3868 MarkRootVisitor root_visitor;
3869 IterateRoots(&root_visitor);
3870}
3871
3872
3873// Triggers a depth-first traversal of reachable objects from roots
3874// and finds a path to any global object and prints it. Useful for
3875// determining the source for leaks of global objects.
3876void Heap::TracePathToGlobal() {
3877 search_target = NULL;
3878 search_for_any_global = true;
3879
3880 MarkRootVisitor root_visitor;
3881 IterateRoots(&root_visitor);
3882}
3883#endif
3884
3885
kasper.lund7276f142008-07-30 08:49:36 +00003886GCTracer::GCTracer()
3887 : start_time_(0.0),
3888 start_size_(0.0),
3889 gc_count_(0),
3890 full_gc_count_(0),
3891 is_compacting_(false),
3892 marked_count_(0) {
3893 // These two fields reflect the state of the previous full collection.
3894 // Set them before they are changed by the collector.
3895 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3896 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3897 if (!FLAG_trace_gc) return;
3898 start_time_ = OS::TimeCurrentMillis();
3899 start_size_ = SizeOfHeapObjects();
3900}
3901
3902
3903GCTracer::~GCTracer() {
3904 if (!FLAG_trace_gc) return;
3905 // Printf ONE line iff flag is set.
3906 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3907 CollectorString(),
3908 start_size_, SizeOfHeapObjects(),
3909 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003910
3911#if defined(ENABLE_LOGGING_AND_PROFILING)
3912 Heap::PrintShortHeapStatistics();
3913#endif
kasper.lund7276f142008-07-30 08:49:36 +00003914}
3915
3916
3917const char* GCTracer::CollectorString() {
3918 switch (collector_) {
3919 case SCAVENGER:
3920 return "Scavenge";
3921 case MARK_COMPACTOR:
3922 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3923 : "Mark-sweep";
3924 }
3925 return "Unknown GC";
3926}
3927
3928
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003929int KeyedLookupCache::Hash(Map* map, String* name) {
3930 // Uses only lower 32 bits if pointers are larger.
3931 uintptr_t addr_hash =
3932 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
3933 return (addr_hash ^ name->Hash()) % kLength;
3934}
3935
3936
3937int KeyedLookupCache::Lookup(Map* map, String* name) {
3938 int index = Hash(map, name);
3939 Key& key = keys_[index];
3940 if ((key.map == map) && key.name->Equals(name)) {
3941 return field_offsets_[index];
3942 }
3943 return -1;
3944}
3945
3946
3947void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
3948 String* symbol;
3949 if (Heap::LookupSymbolIfExists(name, &symbol)) {
3950 int index = Hash(map, symbol);
3951 Key& key = keys_[index];
3952 key.map = map;
3953 key.name = symbol;
3954 field_offsets_[index] = field_offset;
3955 }
3956}
3957
3958
3959void KeyedLookupCache::Clear() {
3960 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
3961}
3962
3963
3964KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
3965
3966
3967int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
3968
3969
3970void DescriptorLookupCache::Clear() {
3971 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
3972}
3973
3974
3975DescriptorLookupCache::Key
3976DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
3977
3978int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
3979
3980
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003981#ifdef DEBUG
3982bool Heap::GarbageCollectionGreedyCheck() {
3983 ASSERT(FLAG_gc_greedy);
3984 if (Bootstrapper::IsActive()) return true;
3985 if (disallow_allocation_failure()) return true;
3986 return CollectGarbage(0, NEW_SPACE);
3987}
3988#endif
3989
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003990
3991TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
3992 : type_(t) {
3993 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
3994 uint32_t in1 = 0xffffffffu; // generated by the FPU.
3995 for (int i = 0; i < kCacheSize; i++) {
3996 elements_[i].in[0] = in0;
3997 elements_[i].in[1] = in1;
3998 elements_[i].output = NULL;
3999 }
4000}
4001
4002
4003TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
4004
4005
4006void TranscendentalCache::Clear() {
4007 for (int i = 0; i < kNumberOfCaches; i++) {
4008 if (caches_[i] != NULL) {
4009 delete caches_[i];
4010 caches_[i] = NULL;
4011 }
4012 }
4013}
4014
4015
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004016} } // namespace v8::internal