blob: 8bab00e331d57fb6dfde483a962acd22815269bb [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 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"
42
43namespace v8 { namespace internal {
44
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
46 ROOT_LIST(ROOT_ALLOCATION)
47#undef ROOT_ALLOCATION
48
49
50#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
51 STRUCT_LIST(STRUCT_ALLOCATION)
52#undef STRUCT_ALLOCATION
53
54
55#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
56 SYMBOL_LIST(SYMBOL_ALLOCATION)
57#undef SYMBOL_ALLOCATION
58
ager@chromium.org3b45ab52009-03-19 22:21:34 +000059String* Heap::hidden_symbol_;
60
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000061NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000062OldSpace* Heap::old_pointer_space_ = NULL;
63OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000064OldSpace* Heap::code_space_ = NULL;
65MapSpace* Heap::map_space_ = NULL;
66LargeObjectSpace* Heap::lo_space_ = NULL;
67
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000068static const int kMinimumPromotionLimit = 2*MB;
69static const int kMinimumAllocationLimit = 8*MB;
70
71int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
72int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
73
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074int Heap::old_gen_exhausted_ = false;
75
kasper.lund7276f142008-07-30 08:49:36 +000076int Heap::amount_of_external_allocated_memory_ = 0;
77int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
78
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000079// semispace_size_ should be a power of 2 and old_generation_size_ should be
80// a multiple of Page::kPageSize.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000081int Heap::semispace_size_ = 2*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082int Heap::old_generation_size_ = 512*MB;
83int Heap::initial_semispace_size_ = 256*KB;
84
85GCCallback Heap::global_gc_prologue_callback_ = NULL;
86GCCallback Heap::global_gc_epilogue_callback_ = NULL;
87
88// Variables set based on semispace_size_ and old_generation_size_ in
89// ConfigureHeap.
90int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
91
92// Double the new space after this many scavenge collections.
93int Heap::new_space_growth_limit_ = 8;
94int Heap::scavenge_count_ = 0;
95Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097int Heap::mc_count_ = 0;
98int Heap::gc_count_ = 0;
99
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000100int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000101bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000102
kasper.lund7276f142008-07-30 08:49:36 +0000103#ifdef DEBUG
104bool Heap::allocation_allowed_ = true;
105
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000106int Heap::allocation_timeout_ = 0;
107bool Heap::disallow_allocation_failure_ = false;
108#endif // DEBUG
109
110
111int Heap::Capacity() {
112 if (!HasBeenSetup()) return 0;
113
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000114 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000115 old_pointer_space_->Capacity() +
116 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 code_space_->Capacity() +
118 map_space_->Capacity();
119}
120
121
122int Heap::Available() {
123 if (!HasBeenSetup()) return 0;
124
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000125 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000126 old_pointer_space_->Available() +
127 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 code_space_->Available() +
129 map_space_->Available();
130}
131
132
133bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000134 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000135 old_data_space_ != NULL &&
136 code_space_ != NULL &&
137 map_space_ != NULL &&
138 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139}
140
141
142GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
143 // Is global GC requested?
144 if (space != NEW_SPACE || FLAG_gc_global) {
145 Counters::gc_compactor_caused_by_request.Increment();
146 return MARK_COMPACTOR;
147 }
148
149 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000150 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000151 Counters::gc_compactor_caused_by_promoted_data.Increment();
152 return MARK_COMPACTOR;
153 }
154
155 // Have allocation in OLD and LO failed?
156 if (old_gen_exhausted_) {
157 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
158 return MARK_COMPACTOR;
159 }
160
161 // Is there enough space left in OLD to guarantee that a scavenge can
162 // succeed?
163 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000164 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 // for object promotion. It counts only the bytes that the memory
166 // allocator has not yet allocated from the OS and assigned to any space,
167 // and does not count available bytes already in the old space or code
168 // space. Undercounting is safe---we may get an unrequested full GC when
169 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000170 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
172 return MARK_COMPACTOR;
173 }
174
175 // Default
176 return SCAVENGER;
177}
178
179
180// TODO(1238405): Combine the infrastructure for --heap-stats and
181// --log-gc to avoid the complicated preprocessor and flag testing.
182#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
183void Heap::ReportStatisticsBeforeGC() {
184 // Heap::ReportHeapStatistics will also log NewSpace statistics when
185 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
186 // following logic is used to avoid double logging.
187#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000188 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000189 if (FLAG_heap_stats) {
190 ReportHeapStatistics("Before GC");
191 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000192 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000194 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195#elif defined(DEBUG)
196 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000199 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 }
201#elif defined(ENABLE_LOGGING_AND_PROFILING)
202 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 new_space_.CollectStatistics();
204 new_space_.ReportStatistics();
205 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 }
207#endif
208}
209
210
211// TODO(1238405): Combine the infrastructure for --heap-stats and
212// --log-gc to avoid the complicated preprocessor and flag testing.
213void Heap::ReportStatisticsAfterGC() {
214 // Similar to the before GC, we use some complicated logic to ensure that
215 // NewSpace statistics are logged exactly once when --log-gc is turned on.
216#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
217 if (FLAG_heap_stats) {
218 ReportHeapStatistics("After GC");
219 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000220 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000221 }
222#elif defined(DEBUG)
223 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
224#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000225 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226#endif
227}
228#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
229
230
231void Heap::GarbageCollectionPrologue() {
kasper.lund7276f142008-07-30 08:49:36 +0000232 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233#ifdef DEBUG
234 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
235 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237 if (FLAG_verify_heap) {
238 Verify();
239 }
240
241 if (FLAG_gc_verbose) Print();
242
243 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000244 // Not all spaces have remembered set bits that we care about.
245 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 map_space_->PrintRSet();
247 lo_space_->PrintRSet();
248 }
249#endif
250
251#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
252 ReportStatisticsBeforeGC();
253#endif
254}
255
256int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000257 int total = 0;
258 AllSpaces spaces;
259 while (Space* space = spaces.next()) total += space->Size();
260 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261}
262
263void Heap::GarbageCollectionEpilogue() {
264#ifdef DEBUG
265 allow_allocation(true);
266 ZapFromSpace();
267
268 if (FLAG_verify_heap) {
269 Verify();
270 }
271
272 if (FLAG_print_global_handles) GlobalHandles::Print();
273 if (FLAG_print_handles) PrintHandles();
274 if (FLAG_gc_verbose) Print();
275 if (FLAG_code_stats) ReportCodeStatistics("After GC");
276#endif
277
278 Counters::alive_after_last_gc.Set(SizeOfObjects());
279
280 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
281 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
282 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
283#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
284 ReportStatisticsAfterGC();
285#endif
286}
287
288
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000289void Heap::CollectAllGarbage() {
290 // Since we are ignoring the return value, the exact choice of space does
291 // not matter, so long as we do not specify NEW_SPACE, which would not
292 // cause a full GC.
293 CollectGarbage(0, OLD_POINTER_SPACE);
294}
295
296
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000297void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000298 // If the garbage collector interface is exposed through the global
299 // gc() function, we avoid being clever about forcing GCs when
300 // contexts are disposed and leave it to the embedder to make
301 // informed decisions about when to force a collection.
302 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000303 HistogramTimerScope scope(&Counters::gc_context);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000304 CollectAllGarbage();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000305 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000306 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000307}
308
309
310void Heap::NotifyContextDisposed() {
311 context_disposed_pending_ = true;
312}
313
314
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000315bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
316 // The VM is in the GC state until exiting this function.
317 VMState state(GC);
318
319#ifdef DEBUG
320 // Reset the allocation timeout to the GC interval, but make sure to
321 // allow at least a few allocations after a collection. The reason
322 // for this is that we have a lot of allocation sequences and we
323 // assume that a garbage collection will allow the subsequent
324 // allocation attempts to go through.
325 allocation_timeout_ = Max(6, FLAG_gc_interval);
326#endif
327
328 { GCTracer tracer;
329 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000330 // The GC count was incremented in the prologue. Tell the tracer about
331 // it.
332 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333
334 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000335 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 tracer.set_collector(collector);
337
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000338 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 ? &Counters::gc_scavenger
340 : &Counters::gc_compactor;
341 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000342 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 rate->Stop();
344
345 GarbageCollectionEpilogue();
346 }
347
348
349#ifdef ENABLE_LOGGING_AND_PROFILING
350 if (FLAG_log_gc) HeapProfiler::WriteSample();
351#endif
352
353 switch (space) {
354 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000355 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000356 case OLD_POINTER_SPACE:
357 return old_pointer_space_->Available() >= requested_size;
358 case OLD_DATA_SPACE:
359 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 case CODE_SPACE:
361 return code_space_->Available() >= requested_size;
362 case MAP_SPACE:
363 return map_space_->Available() >= requested_size;
364 case LO_SPACE:
365 return lo_space_->Available() >= requested_size;
366 }
367 return false;
368}
369
370
kasper.lund7276f142008-07-30 08:49:36 +0000371void Heap::PerformScavenge() {
372 GCTracer tracer;
373 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
374}
375
376
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000377void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000378 GarbageCollector collector,
379 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000380 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
381 ASSERT(!allocation_allowed_);
382 global_gc_prologue_callback_();
383 }
384
385 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000386 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000387
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000388 int old_gen_size = PromotedSpaceSize();
389 old_gen_promotion_limit_ =
390 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
391 old_gen_allocation_limit_ =
392 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393 old_gen_exhausted_ = false;
394
395 // If we have used the mark-compact collector to collect the new
396 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000397 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000398 // case where (1) a new space collection was requested, (2) the
399 // collector selection policy selected the mark-compact collector,
400 // and (3) the mark-compact collector policy selected not to
401 // compact the new space. In that case, there is no more (usable)
402 // free space in the new space after the collection compared to
403 // before.
404 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
405 Scavenge();
406 }
407 } else {
408 Scavenge();
409 }
410 Counters::objs_since_last_young.Set(0);
411
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000412 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413
kasper.lund7276f142008-07-30 08:49:36 +0000414 if (collector == MARK_COMPACTOR) {
415 // Register the amount of external allocated memory.
416 amount_of_external_allocated_memory_at_last_global_gc_ =
417 amount_of_external_allocated_memory_;
418 }
419
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
421 ASSERT(!allocation_allowed_);
422 global_gc_epilogue_callback_();
423 }
424}
425
426
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000427void Heap::PostGarbageCollectionProcessing() {
428 // Process weak handles post gc.
429 GlobalHandles::PostGarbageCollectionProcessing();
430 // Update flat string readers.
431 FlatStringReader::PostGarbageCollectionProcessing();
432}
433
434
kasper.lund7276f142008-07-30 08:49:36 +0000435void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000436 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000437 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000438 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000439 LOG(ResourceEvent("markcompact", "begin"));
440
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000441 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000442
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000443 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000445 MarkCompactPrologue(is_compacting);
446
447 MarkCompactCollector::CollectGarbage();
448
449 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450
451 LOG(ResourceEvent("markcompact", "end"));
452
453 gc_state_ = NOT_IN_GC;
454
455 Shrink();
456
457 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000458 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000459}
460
461
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000462void Heap::MarkCompactPrologue(bool is_compacting) {
463 // At any old GC clear the keyed lookup cache to enable collection of unused
464 // maps.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000465 ClearKeyedLookupCache();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000466
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000467 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000468
469 Top::MarkCompactPrologue(is_compacting);
470 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471}
472
473
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000474void Heap::MarkCompactEpilogue(bool is_compacting) {
475 Top::MarkCompactEpilogue(is_compacting);
476 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477}
478
479
480Object* Heap::FindCodeObject(Address a) {
481 Object* obj = code_space_->FindObject(a);
482 if (obj->IsFailure()) {
483 obj = lo_space_->FindObject(a);
484 }
kasper.lund7276f142008-07-30 08:49:36 +0000485 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000486 return obj;
487}
488
489
490// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000491class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492 public:
493
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000494 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000495
496 void VisitPointers(Object** start, Object** end) {
497 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000498 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000499 }
500
501 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000502 void ScavengePointer(Object** p) {
503 Object* object = *p;
504 if (!Heap::InNewSpace(object)) return;
505 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
506 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 }
508};
509
510
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000511// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512static Address promoted_top = NULL;
513
514
515#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000516// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000517// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000518class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000519 public:
520 void VisitPointers(Object** start, Object**end) {
521 for (Object** current = start; current < end; current++) {
522 if ((*current)->IsHeapObject()) {
523 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
524 }
525 }
526 }
527};
528#endif
529
530void Heap::Scavenge() {
531#ifdef DEBUG
532 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000533 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000534 HeapObjectIterator it(code_space_);
535 while (it.has_next()) {
536 HeapObject* object = it.next();
537 if (object->IsCode()) {
538 Code::cast(object)->ConvertICTargetsFromAddressToObject();
539 }
540 object->Iterate(&v);
541 if (object->IsCode()) {
542 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
543 }
544 }
545 }
546#endif
547
548 gc_state_ = SCAVENGE;
549
550 // Implements Cheney's copying algorithm
551 LOG(ResourceEvent("scavenge", "begin"));
552
553 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000554 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555 scavenge_count_ > new_space_growth_limit_) {
556 // Double the size of the new space, and double the limit. The next
557 // doubling attempt will occur after the current new_space_growth_limit_
558 // more collections.
559 // TODO(1240712): NewSpace::Double has a return value which is
560 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000561 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562 new_space_growth_limit_ *= 2;
563 }
564
565 // Flip the semispaces. After flipping, to space is empty, from space has
566 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000567 new_space_.Flip();
568 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000569
570 // We need to sweep newly copied objects which can be in either the to space
571 // or the old space. For to space objects, we use a mark. Newly copied
572 // objects lie between the mark and the allocation top. For objects
573 // promoted to old space, we write their addresses downward from the top of
574 // the new space. Sweeping newly promoted objects requires an allocation
575 // pointer and a mark. Note that the allocation pointer 'top' actually
576 // moves downward from the high address in the to space.
577 //
578 // There is guaranteed to be enough room at the top of the to space for the
579 // addresses of promoted objects: every object promoted frees up its size in
580 // bytes from the top of the new space, and objects are at least one pointer
581 // in size. Using the new space to record promoted addresses makes the
582 // scavenge collector agnostic to the allocation strategy (eg, linear or
583 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000584 Address new_mark = new_space_.ToSpaceLow();
585 Address promoted_mark = new_space_.ToSpaceHigh();
586 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000588 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000590 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000591
592 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000593 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000594 IterateRSet(old_pointer_space_, &ScavengePointer);
595 IterateRSet(map_space_, &ScavengePointer);
596 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597
598 bool has_processed_weak_pointers = false;
599
600 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000601 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602 ASSERT(promoted_mark >= promoted_top);
603
604 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000605 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 // Sweep newly copied objects in the to space. The allocation pointer
607 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000608 Address previous_top = new_space_.top();
609 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000610 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000611 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000612 }
613 new_mark = previous_top;
614
615 // Sweep newly copied objects in the old space. The promotion 'top'
616 // pointer could change during sweeping.
617 previous_top = promoted_top;
618 for (Address current = promoted_mark - kPointerSize;
619 current >= previous_top;
620 current -= kPointerSize) {
621 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000622 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000623 UpdateRSet(object);
624 }
625 promoted_mark = previous_top;
626 }
627
628 if (has_processed_weak_pointers) break; // We are done.
629 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000630 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631 has_processed_weak_pointers = true;
632 }
633
634 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000635 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000636
637 LOG(ResourceEvent("scavenge", "end"));
638
639 gc_state_ = NOT_IN_GC;
640}
641
642
643void Heap::ClearRSetRange(Address start, int size_in_bytes) {
644 uint32_t start_bit;
645 Address start_word_address =
646 Page::ComputeRSetBitPosition(start, 0, &start_bit);
647 uint32_t end_bit;
648 Address end_word_address =
649 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
650 0,
651 &end_bit);
652
653 // We want to clear the bits in the starting word starting with the
654 // first bit, and in the ending word up to and including the last
655 // bit. Build a pair of bitmasks to do that.
656 uint32_t start_bitmask = start_bit - 1;
657 uint32_t end_bitmask = ~((end_bit << 1) - 1);
658
659 // If the start address and end address are the same, we mask that
660 // word once, otherwise mask the starting and ending word
661 // separately and all the ones in between.
662 if (start_word_address == end_word_address) {
663 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
664 } else {
665 Memory::uint32_at(start_word_address) &= start_bitmask;
666 Memory::uint32_at(end_word_address) &= end_bitmask;
667 start_word_address += kIntSize;
668 memset(start_word_address, 0, end_word_address - start_word_address);
669 }
670}
671
672
673class UpdateRSetVisitor: public ObjectVisitor {
674 public:
675
676 void VisitPointer(Object** p) {
677 UpdateRSet(p);
678 }
679
680 void VisitPointers(Object** start, Object** end) {
681 // Update a store into slots [start, end), used (a) to update remembered
682 // set when promoting a young object to old space or (b) to rebuild
683 // remembered sets after a mark-compact collection.
684 for (Object** p = start; p < end; p++) UpdateRSet(p);
685 }
686 private:
687
688 void UpdateRSet(Object** p) {
689 // The remembered set should not be set. It should be clear for objects
690 // newly copied to old space, and it is cleared before rebuilding in the
691 // mark-compact collector.
692 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
693 if (Heap::InNewSpace(*p)) {
694 Page::SetRSet(reinterpret_cast<Address>(p), 0);
695 }
696 }
697};
698
699
700int Heap::UpdateRSet(HeapObject* obj) {
701 ASSERT(!InNewSpace(obj));
702 // Special handling of fixed arrays to iterate the body based on the start
703 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
704 // will not work because Page::SetRSet needs to have the start of the
705 // object.
706 if (obj->IsFixedArray()) {
707 FixedArray* array = FixedArray::cast(obj);
708 int length = array->length();
709 for (int i = 0; i < length; i++) {
710 int offset = FixedArray::kHeaderSize + i * kPointerSize;
711 ASSERT(!Page::IsRSetSet(obj->address(), offset));
712 if (Heap::InNewSpace(array->get(i))) {
713 Page::SetRSet(obj->address(), offset);
714 }
715 }
716 } else if (!obj->IsCode()) {
717 // Skip code object, we know it does not contain inter-generational
718 // pointers.
719 UpdateRSetVisitor v;
720 obj->Iterate(&v);
721 }
722 return obj->Size();
723}
724
725
726void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000727 // By definition, we do not care about remembered set bits in code or data
728 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729 map_space_->ClearRSet();
730 RebuildRSets(map_space_);
731
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000732 old_pointer_space_->ClearRSet();
733 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000734
735 Heap::lo_space_->ClearRSet();
736 RebuildRSets(lo_space_);
737}
738
739
740void Heap::RebuildRSets(PagedSpace* space) {
741 HeapObjectIterator it(space);
742 while (it.has_next()) Heap::UpdateRSet(it.next());
743}
744
745
746void Heap::RebuildRSets(LargeObjectSpace* space) {
747 LargeObjectIterator it(space);
748 while (it.has_next()) Heap::UpdateRSet(it.next());
749}
750
751
752#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
753void Heap::RecordCopiedObject(HeapObject* obj) {
754 bool should_record = false;
755#ifdef DEBUG
756 should_record = FLAG_heap_stats;
757#endif
758#ifdef ENABLE_LOGGING_AND_PROFILING
759 should_record = should_record || FLAG_log_gc;
760#endif
761 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000762 if (new_space_.Contains(obj)) {
763 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000764 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000765 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 }
767 }
768}
769#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
770
771
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000772
773HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000774 HeapObject* target,
775 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000776 // Copy the content of source to target.
777 CopyBlock(reinterpret_cast<Object**>(target->address()),
778 reinterpret_cast<Object**>(source->address()),
779 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000780
kasper.lund7276f142008-07-30 08:49:36 +0000781 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000782 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000783
784 // Update NewSpace stats if necessary.
785#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
786 RecordCopiedObject(target);
787#endif
788
789 return target;
790}
791
792
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000793// Inlined function.
794void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
795 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796
kasper.lund7276f142008-07-30 08:49:36 +0000797 // We use the first word (where the map pointer usually is) of a heap
798 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000799 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000800 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000801 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000802
kasper.lund7276f142008-07-30 08:49:36 +0000803 // If the first word is a forwarding address, the object has already been
804 // copied.
805 if (first_word.IsForwardingAddress()) {
806 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 return;
808 }
809
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000810 // Call the slow part of scavenge object.
811 return ScavengeObjectSlow(p, object);
812}
813
ager@chromium.org870a0b62008-11-04 11:43:05 +0000814
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000815static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000816 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000817 // is a candidate for being shortcut by the scavenger.
818 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000819 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
ager@chromium.orgc3e50d82008-11-05 11:53:10 +0000820 return (StringShape(map).representation_tag() == kConsStringTag) &&
ager@chromium.org870a0b62008-11-04 11:43:05 +0000821 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000822}
823
824
825void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
826 ASSERT(InFromSpace(object));
827 MapWord first_word = object->map_word();
828 ASSERT(!first_word.IsForwardingAddress());
829
830 // Optimization: Bypass flattened ConsString objects.
831 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000832 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833 *p = object;
834 // After patching *p we have to repeat the checks that object is in the
835 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000836 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000837 first_word = object->map_word();
838 if (first_word.IsForwardingAddress()) {
839 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000840 return;
841 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000842 }
843
kasper.lund7276f142008-07-30 08:49:36 +0000844 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845 // If the object should be promoted, we try to copy it to old space.
846 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000847 OldSpace* target_space = Heap::TargetSpace(object);
848 ASSERT(target_space == Heap::old_pointer_space_ ||
849 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000850 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000851 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000852 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000853 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000854 // Record the object's address at the top of the to space, to allow
855 // it to be swept by the scavenger.
856 promoted_top -= kPointerSize;
857 Memory::Object_at(promoted_top) = *p;
858 } else {
859#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000860 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000861 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000862 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 (*p)->Iterate(&v);
864#endif
865 }
866 return;
867 }
868 }
869
870 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000871 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000872 // Failed allocation at this point is utterly unexpected.
873 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000874 *p = MigrateObject(object, HeapObject::cast(result), object_size);
875}
876
877
878void Heap::ScavengePointer(HeapObject** p) {
879 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000880}
881
882
883Object* Heap::AllocatePartialMap(InstanceType instance_type,
884 int instance_size) {
885 Object* result = AllocateRawMap(Map::kSize);
886 if (result->IsFailure()) return result;
887
888 // Map::cast cannot be used due to uninitialized map field.
889 reinterpret_cast<Map*>(result)->set_map(meta_map());
890 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
891 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000892 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000893 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
894 return result;
895}
896
897
898Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
899 Object* result = AllocateRawMap(Map::kSize);
900 if (result->IsFailure()) return result;
901
902 Map* map = reinterpret_cast<Map*>(result);
903 map->set_map(meta_map());
904 map->set_instance_type(instance_type);
905 map->set_prototype(null_value());
906 map->set_constructor(null_value());
907 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000908 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000909 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910 map->set_code_cache(empty_fixed_array());
911 map->set_unused_property_fields(0);
912 map->set_bit_field(0);
913 return map;
914}
915
916
917bool Heap::CreateInitialMaps() {
918 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
919 if (obj->IsFailure()) return false;
920
921 // Map::cast cannot be used due to uninitialized map field.
922 meta_map_ = reinterpret_cast<Map*>(obj);
923 meta_map()->set_map(meta_map());
924
925 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
926 if (obj->IsFailure()) return false;
927 fixed_array_map_ = Map::cast(obj);
928
929 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
930 if (obj->IsFailure()) return false;
931 oddball_map_ = Map::cast(obj);
932
933 // Allocate the empty array
934 obj = AllocateEmptyFixedArray();
935 if (obj->IsFailure()) return false;
936 empty_fixed_array_ = FixedArray::cast(obj);
937
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000938 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939 if (obj->IsFailure()) return false;
940 null_value_ = obj;
941
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000942 // Allocate the empty descriptor array. AllocateMap can now be used.
943 obj = AllocateEmptyFixedArray();
944 if (obj->IsFailure()) return false;
945 // There is a check against empty_descriptor_array() in cast().
946 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000947
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000948 // Fix the instance_descriptors for the existing maps.
949 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 meta_map()->set_code_cache(empty_fixed_array());
951
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000952 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000953 fixed_array_map()->set_code_cache(empty_fixed_array());
954
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000955 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000956 oddball_map()->set_code_cache(empty_fixed_array());
957
958 // Fix prototype object for existing maps.
959 meta_map()->set_prototype(null_value());
960 meta_map()->set_constructor(null_value());
961
962 fixed_array_map()->set_prototype(null_value());
963 fixed_array_map()->set_constructor(null_value());
964 oddball_map()->set_prototype(null_value());
965 oddball_map()->set_constructor(null_value());
966
967 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
968 if (obj->IsFailure()) return false;
969 heap_number_map_ = Map::cast(obj);
970
971 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
972 if (obj->IsFailure()) return false;
973 proxy_map_ = Map::cast(obj);
974
975#define ALLOCATE_STRING_MAP(type, size, name) \
976 obj = AllocateMap(type, size); \
977 if (obj->IsFailure()) return false; \
978 name##_map_ = Map::cast(obj);
979 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
980#undef ALLOCATE_STRING_MAP
981
ager@chromium.org7c537e22008-10-16 08:43:32 +0000982 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983 if (obj->IsFailure()) return false;
984 undetectable_short_string_map_ = Map::cast(obj);
985 undetectable_short_string_map_->set_is_undetectable();
986
ager@chromium.org7c537e22008-10-16 08:43:32 +0000987 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000988 if (obj->IsFailure()) return false;
989 undetectable_medium_string_map_ = Map::cast(obj);
990 undetectable_medium_string_map_->set_is_undetectable();
991
ager@chromium.org7c537e22008-10-16 08:43:32 +0000992 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000993 if (obj->IsFailure()) return false;
994 undetectable_long_string_map_ = Map::cast(obj);
995 undetectable_long_string_map_->set_is_undetectable();
996
ager@chromium.org7c537e22008-10-16 08:43:32 +0000997 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000998 if (obj->IsFailure()) return false;
999 undetectable_short_ascii_string_map_ = Map::cast(obj);
1000 undetectable_short_ascii_string_map_->set_is_undetectable();
1001
ager@chromium.org7c537e22008-10-16 08:43:32 +00001002 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001003 if (obj->IsFailure()) return false;
1004 undetectable_medium_ascii_string_map_ = Map::cast(obj);
1005 undetectable_medium_ascii_string_map_->set_is_undetectable();
1006
ager@chromium.org7c537e22008-10-16 08:43:32 +00001007 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001008 if (obj->IsFailure()) return false;
1009 undetectable_long_ascii_string_map_ = Map::cast(obj);
1010 undetectable_long_ascii_string_map_->set_is_undetectable();
1011
1012 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
1013 if (obj->IsFailure()) return false;
1014 byte_array_map_ = Map::cast(obj);
1015
1016 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1017 if (obj->IsFailure()) return false;
1018 code_map_ = Map::cast(obj);
1019
1020 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1021 if (obj->IsFailure()) return false;
1022 one_word_filler_map_ = Map::cast(obj);
1023
1024 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1025 if (obj->IsFailure()) return false;
1026 two_word_filler_map_ = Map::cast(obj);
1027
1028#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1029 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1030 if (obj->IsFailure()) return false; \
1031 name##_map_ = Map::cast(obj);
1032 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1033#undef ALLOCATE_STRUCT_MAP
1034
ager@chromium.org236ad962008-09-25 09:45:57 +00001035 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001036 if (obj->IsFailure()) return false;
1037 hash_table_map_ = Map::cast(obj);
1038
ager@chromium.org236ad962008-09-25 09:45:57 +00001039 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001040 if (obj->IsFailure()) return false;
1041 context_map_ = Map::cast(obj);
1042
ager@chromium.org236ad962008-09-25 09:45:57 +00001043 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001044 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001045 catch_context_map_ = Map::cast(obj);
1046
1047 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1048 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001049 global_context_map_ = Map::cast(obj);
1050
1051 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1052 if (obj->IsFailure()) return false;
1053 boilerplate_function_map_ = Map::cast(obj);
1054
1055 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1056 if (obj->IsFailure()) return false;
1057 shared_function_info_map_ = Map::cast(obj);
1058
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001059 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060 return true;
1061}
1062
1063
1064Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1065 // Statically ensure that it is safe to allocate heap numbers in paged
1066 // spaces.
1067 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001068 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001069 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001070 if (result->IsFailure()) return result;
1071
1072 HeapObject::cast(result)->set_map(heap_number_map());
1073 HeapNumber::cast(result)->set_value(value);
1074 return result;
1075}
1076
1077
1078Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001079 // Use general version, if we're forced to always allocate.
1080 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001081 // This version of AllocateHeapNumber is optimized for
1082 // allocation in new space.
1083 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1084 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001085 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001086 if (result->IsFailure()) return result;
1087 HeapObject::cast(result)->set_map(heap_number_map());
1088 HeapNumber::cast(result)->set_value(value);
1089 return result;
1090}
1091
1092
1093Object* Heap::CreateOddball(Map* map,
1094 const char* to_string,
1095 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001096 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001097 if (result->IsFailure()) return result;
1098 return Oddball::cast(result)->Initialize(to_string, to_number);
1099}
1100
1101
1102bool Heap::CreateApiObjects() {
1103 Object* obj;
1104
1105 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1106 if (obj->IsFailure()) return false;
1107 neander_map_ = Map::cast(obj);
1108
1109 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1110 if (obj->IsFailure()) return false;
1111 Object* elements = AllocateFixedArray(2);
1112 if (elements->IsFailure()) return false;
1113 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1114 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1115 message_listeners_ = JSObject::cast(obj);
1116
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001117 return true;
1118}
1119
1120void Heap::CreateFixedStubs() {
1121 // Here we create roots for fixed stubs. They are needed at GC
1122 // for cooking and uncooking (check out frames.cc).
1123 // The eliminates the need for doing dictionary lookup in the
1124 // stub cache for these stubs.
1125 HandleScope scope;
1126 {
1127 CEntryStub stub;
1128 c_entry_code_ = *stub.GetCode();
1129 }
1130 {
1131 CEntryDebugBreakStub stub;
1132 c_entry_debug_break_code_ = *stub.GetCode();
1133 }
1134 {
1135 JSEntryStub stub;
1136 js_entry_code_ = *stub.GetCode();
1137 }
1138 {
1139 JSConstructEntryStub stub;
1140 js_construct_entry_code_ = *stub.GetCode();
1141 }
1142}
1143
1144
1145bool Heap::CreateInitialObjects() {
1146 Object* obj;
1147
1148 // The -0 value must be set before NumberFromDouble works.
1149 obj = AllocateHeapNumber(-0.0, TENURED);
1150 if (obj->IsFailure()) return false;
1151 minus_zero_value_ = obj;
1152 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1153
1154 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1155 if (obj->IsFailure()) return false;
1156 nan_value_ = obj;
1157
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001158 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001159 if (obj->IsFailure()) return false;
1160 undefined_value_ = obj;
1161 ASSERT(!InNewSpace(undefined_value()));
1162
1163 // Allocate initial symbol table.
1164 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1165 if (obj->IsFailure()) return false;
1166 symbol_table_ = obj;
1167
1168 // Assign the print strings for oddballs after creating symboltable.
1169 Object* symbol = LookupAsciiSymbol("undefined");
1170 if (symbol->IsFailure()) return false;
1171 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1172 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1173
1174 // Assign the print strings for oddballs after creating symboltable.
1175 symbol = LookupAsciiSymbol("null");
1176 if (symbol->IsFailure()) return false;
1177 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1178 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1179
1180 // Allocate the null_value
1181 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1182 if (obj->IsFailure()) return false;
1183
1184 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1185 if (obj->IsFailure()) return false;
1186 true_value_ = obj;
1187
1188 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1189 if (obj->IsFailure()) return false;
1190 false_value_ = obj;
1191
1192 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1193 if (obj->IsFailure()) return false;
1194 the_hole_value_ = obj;
1195
1196 // Allocate the empty string.
1197 obj = AllocateRawAsciiString(0, TENURED);
1198 if (obj->IsFailure()) return false;
1199 empty_string_ = String::cast(obj);
1200
1201#define SYMBOL_INITIALIZE(name, string) \
1202 obj = LookupAsciiSymbol(string); \
1203 if (obj->IsFailure()) return false; \
1204 (name##_) = String::cast(obj);
1205 SYMBOL_LIST(SYMBOL_INITIALIZE)
1206#undef SYMBOL_INITIALIZE
1207
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001208 // Allocate the hidden symbol which is used to identify the hidden properties
1209 // in JSObjects. The hash code has a special value so that it will not match
1210 // the empty string when searching for the property. It cannot be part of the
1211 // SYMBOL_LIST because it needs to be allocated manually with the special
1212 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1213 // that it will always be at the first entry in property descriptors.
1214 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1215 if (obj->IsFailure()) return false;
1216 hidden_symbol_ = String::cast(obj);
1217
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001218 // Allocate the proxy for __proto__.
1219 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1220 if (obj->IsFailure()) return false;
1221 prototype_accessors_ = Proxy::cast(obj);
1222
1223 // Allocate the code_stubs dictionary.
1224 obj = Dictionary::Allocate(4);
1225 if (obj->IsFailure()) return false;
1226 code_stubs_ = Dictionary::cast(obj);
1227
1228 // Allocate the non_monomorphic_cache used in stub-cache.cc
1229 obj = Dictionary::Allocate(4);
1230 if (obj->IsFailure()) return false;
1231 non_monomorphic_cache_ = Dictionary::cast(obj);
1232
1233 CreateFixedStubs();
1234
1235 // Allocate the number->string conversion cache
1236 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1237 if (obj->IsFailure()) return false;
1238 number_string_cache_ = FixedArray::cast(obj);
1239
1240 // Allocate cache for single character strings.
1241 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1242 if (obj->IsFailure()) return false;
1243 single_character_string_cache_ = FixedArray::cast(obj);
1244
1245 // Allocate cache for external strings pointing to native source code.
1246 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1247 if (obj->IsFailure()) return false;
1248 natives_source_cache_ = FixedArray::cast(obj);
1249
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001250 // Handling of script id generation is in Factory::NewScript.
1251 last_script_id_ = undefined_value();
1252
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001253 // Initialize keyed lookup cache.
1254 ClearKeyedLookupCache();
1255
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001256 // Initialize compilation cache.
1257 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001258
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001259 return true;
1260}
1261
1262
1263static inline int double_get_hash(double d) {
1264 DoubleRepresentation rep(d);
1265 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1266 (Heap::kNumberStringCacheSize - 1));
1267}
1268
1269
1270static inline int smi_get_hash(Smi* smi) {
1271 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1272}
1273
1274
1275
1276Object* Heap::GetNumberStringCache(Object* number) {
1277 int hash;
1278 if (number->IsSmi()) {
1279 hash = smi_get_hash(Smi::cast(number));
1280 } else {
1281 hash = double_get_hash(number->Number());
1282 }
1283 Object* key = number_string_cache_->get(hash * 2);
1284 if (key == number) {
1285 return String::cast(number_string_cache_->get(hash * 2 + 1));
1286 } else if (key->IsHeapNumber() &&
1287 number->IsHeapNumber() &&
1288 key->Number() == number->Number()) {
1289 return String::cast(number_string_cache_->get(hash * 2 + 1));
1290 }
1291 return undefined_value();
1292}
1293
1294
1295void Heap::SetNumberStringCache(Object* number, String* string) {
1296 int hash;
1297 if (number->IsSmi()) {
1298 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001299 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001300 } else {
1301 hash = double_get_hash(number->Number());
1302 number_string_cache_->set(hash * 2, number);
1303 }
1304 number_string_cache_->set(hash * 2 + 1, string);
1305}
1306
1307
1308Object* Heap::SmiOrNumberFromDouble(double value,
1309 bool new_object,
1310 PretenureFlag pretenure) {
1311 // We need to distinguish the minus zero value and this cannot be
1312 // done after conversion to int. Doing this by comparing bit
1313 // patterns is faster than using fpclassify() et al.
1314 static const DoubleRepresentation plus_zero(0.0);
1315 static const DoubleRepresentation minus_zero(-0.0);
1316 static const DoubleRepresentation nan(OS::nan_value());
1317 ASSERT(minus_zero_value_ != NULL);
1318 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1319
1320 DoubleRepresentation rep(value);
1321 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1322 if (rep.bits == minus_zero.bits) {
1323 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1324 : minus_zero_value_;
1325 }
1326 if (rep.bits == nan.bits) {
1327 return new_object
1328 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1329 : nan_value_;
1330 }
1331
1332 // Try to represent the value as a tagged small integer.
1333 int int_value = FastD2I(value);
1334 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1335 return Smi::FromInt(int_value);
1336 }
1337
1338 // Materialize the value in the heap.
1339 return AllocateHeapNumber(value, pretenure);
1340}
1341
1342
1343Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1344 return SmiOrNumberFromDouble(value,
1345 true /* number object must be new */,
1346 pretenure);
1347}
1348
1349
1350Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1351 return SmiOrNumberFromDouble(value,
1352 false /* use preallocated NaN, -0.0 */,
1353 pretenure);
1354}
1355
1356
1357Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1358 // Statically ensure that it is safe to allocate proxies in paged spaces.
1359 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001360 AllocationSpace space =
1361 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001362 Object* result = Allocate(proxy_map(), space);
1363 if (result->IsFailure()) return result;
1364
1365 Proxy::cast(result)->set_proxy(proxy);
1366 return result;
1367}
1368
1369
1370Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1371 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1372 if (result->IsFailure()) return result;
1373
1374 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1375 share->set_name(name);
1376 Code* illegal = Builtins::builtin(Builtins::Illegal);
1377 share->set_code(illegal);
1378 share->set_expected_nof_properties(0);
1379 share->set_length(0);
1380 share->set_formal_parameter_count(0);
1381 share->set_instance_class_name(Object_symbol());
1382 share->set_function_data(undefined_value());
1383 share->set_lazy_load_data(undefined_value());
1384 share->set_script(undefined_value());
1385 share->set_start_position_and_type(0);
1386 share->set_debug_info(undefined_value());
1387 return result;
1388}
1389
1390
ager@chromium.org870a0b62008-11-04 11:43:05 +00001391Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001392 String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001393 int first_length = first->length();
1394 int second_length = second->length();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001395 int length = first_length + second_length;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001396 bool is_ascii = StringShape(first).IsAsciiRepresentation()
1397 && StringShape(second).IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001398
1399 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001400 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001401 ASSERT(first->IsFlat());
1402 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001403 if (is_ascii) {
1404 Object* result = AllocateRawAsciiString(length);
1405 if (result->IsFailure()) return result;
1406 // Copy the characters into the new object.
1407 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001408 String::WriteToFlat(first, dest, 0, first_length);
1409 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001410 return result;
1411 } else {
1412 Object* result = AllocateRawTwoByteString(length);
1413 if (result->IsFailure()) return result;
1414 // Copy the characters into the new object.
1415 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001416 String::WriteToFlat(first, dest, 0, first_length);
1417 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001418 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001419 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420 }
1421
1422 Map* map;
1423 if (length <= String::kMaxShortStringSize) {
1424 map = is_ascii ? short_cons_ascii_string_map()
1425 : short_cons_string_map();
1426 } else if (length <= String::kMaxMediumStringSize) {
1427 map = is_ascii ? medium_cons_ascii_string_map()
1428 : medium_cons_string_map();
1429 } else {
1430 map = is_ascii ? long_cons_ascii_string_map()
1431 : long_cons_string_map();
1432 }
1433
1434 Object* result = Allocate(map, NEW_SPACE);
1435 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001436 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001437 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001438 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1439 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001440 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 return result;
1442}
1443
1444
ager@chromium.org870a0b62008-11-04 11:43:05 +00001445Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001446 int start,
1447 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001448 int length = end - start;
1449
1450 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001451 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001452 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001453 }
1454
1455 Map* map;
1456 if (length <= String::kMaxShortStringSize) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001457 map = StringShape(buffer).IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001458 short_sliced_ascii_string_map() :
1459 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001460 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001461 map = StringShape(buffer).IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001462 medium_sliced_ascii_string_map() :
1463 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001464 } else {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001465 map = StringShape(buffer).IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001466 long_sliced_ascii_string_map() :
1467 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001468 }
1469
1470 Object* result = Allocate(map, NEW_SPACE);
1471 if (result->IsFailure()) return result;
1472
1473 SlicedString* sliced_string = SlicedString::cast(result);
1474 sliced_string->set_buffer(buffer);
1475 sliced_string->set_start(start);
1476 sliced_string->set_length(length);
1477
1478 return result;
1479}
1480
1481
ager@chromium.org870a0b62008-11-04 11:43:05 +00001482Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001483 int start,
1484 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001485 int length = end - start;
1486
ager@chromium.org7c537e22008-10-16 08:43:32 +00001487 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001488 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001489 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001490 }
1491
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001492 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001493 if (!buffer->IsFlat()) {
1494 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001495 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001496
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001497 Object* result = StringShape(buffer).IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001498 ? AllocateRawAsciiString(length)
1499 : AllocateRawTwoByteString(length);
1500 if (result->IsFailure()) return result;
1501
1502 // Copy the characters into the new object.
1503 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001504 StringHasher hasher(length);
1505 int i = 0;
1506 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001507 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001508 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001509 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001510 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001511 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001512 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001513 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001514 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001515 }
1516 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001517 return result;
1518}
1519
1520
1521Object* Heap::AllocateExternalStringFromAscii(
1522 ExternalAsciiString::Resource* resource) {
1523 Map* map;
1524 int length = resource->length();
1525 if (length <= String::kMaxShortStringSize) {
1526 map = short_external_ascii_string_map();
1527 } else if (length <= String::kMaxMediumStringSize) {
1528 map = medium_external_ascii_string_map();
1529 } else {
1530 map = long_external_ascii_string_map();
1531 }
1532
1533 Object* result = Allocate(map, NEW_SPACE);
1534 if (result->IsFailure()) return result;
1535
1536 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1537 external_string->set_length(length);
1538 external_string->set_resource(resource);
1539
1540 return result;
1541}
1542
1543
1544Object* Heap::AllocateExternalStringFromTwoByte(
1545 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001546 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001547
ager@chromium.org6f10e412009-02-13 10:11:16 +00001548 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549 Object* result = Allocate(map, NEW_SPACE);
1550 if (result->IsFailure()) return result;
1551
1552 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1553 external_string->set_length(length);
1554 external_string->set_resource(resource);
1555
1556 return result;
1557}
1558
1559
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001560Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001561 if (code <= String::kMaxAsciiCharCode) {
1562 Object* value = Heap::single_character_string_cache()->get(code);
1563 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001564
1565 char buffer[1];
1566 buffer[0] = static_cast<char>(code);
1567 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1568
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001569 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570 Heap::single_character_string_cache()->set(code, result);
1571 return result;
1572 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574 Object* result = Heap::AllocateRawTwoByteString(1);
1575 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001576 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001577 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001578 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579}
1580
1581
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001582Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1583 if (pretenure == NOT_TENURED) {
1584 return AllocateByteArray(length);
1585 }
1586 int size = ByteArray::SizeFor(length);
1587 AllocationSpace space =
1588 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1589
1590 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1591
1592 if (result->IsFailure()) return result;
1593
1594 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1595 reinterpret_cast<Array*>(result)->set_length(length);
1596 return result;
1597}
1598
1599
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001600Object* Heap::AllocateByteArray(int length) {
1601 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001602 AllocationSpace space =
1603 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001604
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001605 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001606
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001607 if (result->IsFailure()) return result;
1608
1609 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1610 reinterpret_cast<Array*>(result)->set_length(length);
1611 return result;
1612}
1613
1614
ager@chromium.org6f10e412009-02-13 10:11:16 +00001615void Heap::CreateFillerObjectAt(Address addr, int size) {
1616 if (size == 0) return;
1617 HeapObject* filler = HeapObject::FromAddress(addr);
1618 if (size == kPointerSize) {
1619 filler->set_map(Heap::one_word_filler_map());
1620 } else {
1621 filler->set_map(Heap::byte_array_map());
1622 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1623 }
1624}
1625
1626
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001627Object* Heap::CreateCode(const CodeDesc& desc,
1628 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001629 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001630 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001631 // Compute size
1632 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1633 int sinfo_size = 0;
1634 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1635 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001636 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001637 Object* result;
1638 if (obj_size > MaxHeapObjectSize()) {
1639 result = lo_space_->AllocateRawCode(obj_size);
1640 } else {
1641 result = code_space_->AllocateRaw(obj_size);
1642 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001644 if (result->IsFailure()) return result;
1645
1646 // Initialize the object
1647 HeapObject::cast(result)->set_map(code_map());
1648 Code* code = Code::cast(result);
1649 code->set_instruction_size(desc.instr_size);
1650 code->set_relocation_size(desc.reloc_size);
1651 code->set_sinfo_size(sinfo_size);
1652 code->set_flags(flags);
1653 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001654 // Allow self references to created code object by patching the handle to
1655 // point to the newly allocated Code object.
1656 if (!self_reference.is_null()) {
1657 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001658 }
1659 // Migrate generated code.
1660 // The generated code can contain Object** values (typically from handles)
1661 // that are dereferenced during the copy to point directly to the actual heap
1662 // objects. These pointers can include references to the code object itself,
1663 // through the self_reference parameter.
1664 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001666 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001667
1668#ifdef DEBUG
1669 code->Verify();
1670#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001671 return code;
1672}
1673
1674
1675Object* Heap::CopyCode(Code* code) {
1676 // Allocate an object the same size as the code object.
1677 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001678 Object* result;
1679 if (obj_size > MaxHeapObjectSize()) {
1680 result = lo_space_->AllocateRawCode(obj_size);
1681 } else {
1682 result = code_space_->AllocateRaw(obj_size);
1683 }
1684
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001685 if (result->IsFailure()) return result;
1686
1687 // Copy code object.
1688 Address old_addr = code->address();
1689 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001690 CopyBlock(reinterpret_cast<Object**>(new_addr),
1691 reinterpret_cast<Object**>(old_addr),
1692 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001693 // Relocate the copy.
1694 Code* new_code = Code::cast(result);
1695 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001696 return new_code;
1697}
1698
1699
1700Object* Heap::Allocate(Map* map, AllocationSpace space) {
1701 ASSERT(gc_state_ == NOT_IN_GC);
1702 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001703 Object* result = AllocateRaw(map->instance_size(),
1704 space,
1705 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 if (result->IsFailure()) return result;
1707 HeapObject::cast(result)->set_map(map);
1708 return result;
1709}
1710
1711
1712Object* Heap::InitializeFunction(JSFunction* function,
1713 SharedFunctionInfo* shared,
1714 Object* prototype) {
1715 ASSERT(!prototype->IsMap());
1716 function->initialize_properties();
1717 function->initialize_elements();
1718 function->set_shared(shared);
1719 function->set_prototype_or_initial_map(prototype);
1720 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001721 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 return function;
1723}
1724
1725
1726Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001727 // Allocate the prototype. Make sure to use the object function
1728 // from the function's context, since the function can be from a
1729 // different context.
1730 JSFunction* object_function =
1731 function->context()->global_context()->object_function();
1732 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001733 if (prototype->IsFailure()) return prototype;
1734 // When creating the prototype for the function we must set its
1735 // constructor to the function.
1736 Object* result =
1737 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1738 function,
1739 DONT_ENUM);
1740 if (result->IsFailure()) return result;
1741 return prototype;
1742}
1743
1744
1745Object* Heap::AllocateFunction(Map* function_map,
1746 SharedFunctionInfo* shared,
1747 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001748 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001749 if (result->IsFailure()) return result;
1750 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1751}
1752
1753
1754Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001755 // To get fast allocation and map sharing for arguments objects we
1756 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757
1758 // This calls Copy directly rather than using Heap::AllocateRaw so we
1759 // duplicate the check here.
1760 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1761
1762 JSObject* boilerplate =
1763 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001764
1765 // Make the clone.
1766 Map* map = boilerplate->map();
1767 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001768 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001769 if (result->IsFailure()) return result;
1770
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001771 // Copy the content. The arguments boilerplate doesn't have any
1772 // fields that point to new space so it's safe to skip the write
1773 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001774 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1775 reinterpret_cast<Object**>(boilerplate->address()),
1776 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001778 // Set the two properties.
1779 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001780 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001781 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1782 Smi::FromInt(length),
1783 SKIP_WRITE_BARRIER);
1784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001785 // Check the state of the object
1786 ASSERT(JSObject::cast(result)->HasFastProperties());
1787 ASSERT(JSObject::cast(result)->HasFastElements());
1788
1789 return result;
1790}
1791
1792
1793Object* Heap::AllocateInitialMap(JSFunction* fun) {
1794 ASSERT(!fun->has_initial_map());
1795
ager@chromium.org7c537e22008-10-16 08:43:32 +00001796 // First create a new map with the expected number of properties being
1797 // allocated in-object.
1798 int expected_nof_properties = fun->shared()->expected_nof_properties();
1799 int instance_size = JSObject::kHeaderSize +
1800 expected_nof_properties * kPointerSize;
1801 if (instance_size > JSObject::kMaxInstanceSize) {
1802 instance_size = JSObject::kMaxInstanceSize;
1803 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1804 kPointerSize;
1805 }
1806 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001807 if (map_obj->IsFailure()) return map_obj;
1808
1809 // Fetch or allocate prototype.
1810 Object* prototype;
1811 if (fun->has_instance_prototype()) {
1812 prototype = fun->instance_prototype();
1813 } else {
1814 prototype = AllocateFunctionPrototype(fun);
1815 if (prototype->IsFailure()) return prototype;
1816 }
1817 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001818 map->set_inobject_properties(expected_nof_properties);
1819 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001820 map->set_prototype(prototype);
1821 return map;
1822}
1823
1824
1825void Heap::InitializeJSObjectFromMap(JSObject* obj,
1826 FixedArray* properties,
1827 Map* map) {
1828 obj->set_properties(properties);
1829 obj->initialize_elements();
1830 // TODO(1240798): Initialize the object's body using valid initial values
1831 // according to the object's initial map. For example, if the map's
1832 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1833 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1834 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1835 // verification code has to cope with (temporarily) invalid objects. See
1836 // for example, JSArray::JSArrayVerify).
1837 obj->InitializeBody(map->instance_size());
1838}
1839
1840
1841Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1842 // JSFunctions should be allocated using AllocateFunction to be
1843 // properly initialized.
1844 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1845
1846 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001847 int prop_size = map->unused_property_fields() - map->inobject_properties();
1848 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001849 if (properties->IsFailure()) return properties;
1850
1851 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001852 AllocationSpace space =
1853 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1855 Object* obj = Allocate(map, space);
1856 if (obj->IsFailure()) return obj;
1857
1858 // Initialize the JSObject.
1859 InitializeJSObjectFromMap(JSObject::cast(obj),
1860 FixedArray::cast(properties),
1861 map);
1862 return obj;
1863}
1864
1865
1866Object* Heap::AllocateJSObject(JSFunction* constructor,
1867 PretenureFlag pretenure) {
1868 // Allocate the initial map if absent.
1869 if (!constructor->has_initial_map()) {
1870 Object* initial_map = AllocateInitialMap(constructor);
1871 if (initial_map->IsFailure()) return initial_map;
1872 constructor->set_initial_map(Map::cast(initial_map));
1873 Map::cast(initial_map)->set_constructor(constructor);
1874 }
1875 // Allocate the object based on the constructors initial map.
1876 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1877}
1878
1879
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001880Object* Heap::CopyJSObject(JSObject* source) {
1881 // Never used to copy functions. If functions need to be copied we
1882 // have to be careful to clear the literals array.
1883 ASSERT(!source->IsJSFunction());
1884
1885 // Make the clone.
1886 Map* map = source->map();
1887 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001888 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001889
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001890 // If we're forced to always allocate, we use the general allocation
1891 // functions which may leave us with an object in old space.
1892 if (always_allocate()) {
1893 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1894 if (clone->IsFailure()) return clone;
1895 Address clone_address = HeapObject::cast(clone)->address();
1896 CopyBlock(reinterpret_cast<Object**>(clone_address),
1897 reinterpret_cast<Object**>(source->address()),
1898 object_size);
1899 // Update write barrier for all fields that lie beyond the header.
1900 for (int offset = JSObject::kHeaderSize;
1901 offset < object_size;
1902 offset += kPointerSize) {
1903 RecordWrite(clone_address, offset);
1904 }
1905 } else {
1906 clone = new_space_.AllocateRaw(object_size);
1907 if (clone->IsFailure()) return clone;
1908 ASSERT(Heap::InNewSpace(clone));
1909 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00001910 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001911 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1912 reinterpret_cast<Object**>(source->address()),
1913 object_size);
1914 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001915
1916 FixedArray* elements = FixedArray::cast(source->elements());
1917 FixedArray* properties = FixedArray::cast(source->properties());
1918 // Update elements if necessary.
1919 if (elements->length()> 0) {
1920 Object* elem = CopyFixedArray(elements);
1921 if (elem->IsFailure()) return elem;
1922 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1923 }
1924 // Update properties if necessary.
1925 if (properties->length() > 0) {
1926 Object* prop = CopyFixedArray(properties);
1927 if (prop->IsFailure()) return prop;
1928 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1929 }
1930 // Return the new clone.
1931 return clone;
1932}
1933
1934
1935Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1936 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001937 // Allocate initial map if absent.
1938 if (!constructor->has_initial_map()) {
1939 Object* initial_map = AllocateInitialMap(constructor);
1940 if (initial_map->IsFailure()) return initial_map;
1941 constructor->set_initial_map(Map::cast(initial_map));
1942 Map::cast(initial_map)->set_constructor(constructor);
1943 }
1944
1945 Map* map = constructor->initial_map();
1946
1947 // Check that the already allocated object has the same size as
1948 // objects allocated using the constructor.
1949 ASSERT(map->instance_size() == object->map()->instance_size());
1950
1951 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001952 int prop_size = map->unused_property_fields() - map->inobject_properties();
1953 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001954 if (properties->IsFailure()) return properties;
1955
1956 // Reset the map for the object.
1957 object->set_map(constructor->initial_map());
1958
1959 // Reinitialize the object from the constructor map.
1960 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1961 return object;
1962}
1963
1964
1965Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1966 PretenureFlag pretenure) {
1967 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1968 if (result->IsFailure()) return result;
1969
1970 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001971 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001972 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001973 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001974 }
1975 return result;
1976}
1977
1978
1979Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1980 PretenureFlag pretenure) {
1981 // Count the number of characters in the UTF-8 string and check if
1982 // it is an ASCII string.
1983 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1984 decoder->Reset(string.start(), string.length());
1985 int chars = 0;
1986 bool is_ascii = true;
1987 while (decoder->has_more()) {
1988 uc32 r = decoder->GetNext();
1989 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1990 chars++;
1991 }
1992
1993 // If the string is ascii, we do not need to convert the characters
1994 // since UTF8 is backwards compatible with ascii.
1995 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1996
1997 Object* result = AllocateRawTwoByteString(chars, pretenure);
1998 if (result->IsFailure()) return result;
1999
2000 // Convert and copy the characters into the new object.
2001 String* string_result = String::cast(result);
2002 decoder->Reset(string.start(), string.length());
2003 for (int i = 0; i < chars; i++) {
2004 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002005 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002006 }
2007 return result;
2008}
2009
2010
2011Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2012 PretenureFlag pretenure) {
2013 // Check if the string is an ASCII string.
2014 int i = 0;
2015 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2016
2017 Object* result;
2018 if (i == string.length()) { // It's an ASCII string.
2019 result = AllocateRawAsciiString(string.length(), pretenure);
2020 } else { // It's not an ASCII string.
2021 result = AllocateRawTwoByteString(string.length(), pretenure);
2022 }
2023 if (result->IsFailure()) return result;
2024
2025 // Copy the characters into the new object, which may be either ASCII or
2026 // UTF-16.
2027 String* string_result = String::cast(result);
2028 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002029 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002030 }
2031 return result;
2032}
2033
2034
2035Map* Heap::SymbolMapForString(String* string) {
2036 // If the string is in new space it cannot be used as a symbol.
2037 if (InNewSpace(string)) return NULL;
2038
2039 // Find the corresponding symbol map for strings.
2040 Map* map = string->map();
2041
2042 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2043 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2044 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2045
2046 if (map == short_string_map()) return short_symbol_map();
2047 if (map == medium_string_map()) return medium_symbol_map();
2048 if (map == long_string_map()) return long_symbol_map();
2049
2050 if (map == short_cons_string_map()) return short_cons_symbol_map();
2051 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2052 if (map == long_cons_string_map()) return long_cons_symbol_map();
2053
2054 if (map == short_cons_ascii_string_map()) {
2055 return short_cons_ascii_symbol_map();
2056 }
2057 if (map == medium_cons_ascii_string_map()) {
2058 return medium_cons_ascii_symbol_map();
2059 }
2060 if (map == long_cons_ascii_string_map()) {
2061 return long_cons_ascii_symbol_map();
2062 }
2063
2064 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002065 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2066 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067
2068 if (map == short_sliced_ascii_string_map()) {
2069 return short_sliced_ascii_symbol_map();
2070 }
2071 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002072 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002073 }
2074 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002075 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002076 }
2077
ager@chromium.org6f10e412009-02-13 10:11:16 +00002078 if (map == short_external_string_map()) {
2079 return short_external_symbol_map();
2080 }
2081 if (map == medium_external_string_map()) {
2082 return medium_external_symbol_map();
2083 }
2084 if (map == long_external_string_map()) {
2085 return long_external_symbol_map();
2086 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002087
2088 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002089 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002090 }
2091 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002092 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002093 }
2094 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002095 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002096 }
2097
2098 // No match found.
2099 return NULL;
2100}
2101
2102
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002103Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2104 int chars,
2105 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002106 // Ensure the chars matches the number of characters in the buffer.
2107 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2108 // Determine whether the string is ascii.
2109 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002110 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002111 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2112 }
2113 buffer->Rewind();
2114
2115 // Compute map and object size.
2116 int size;
2117 Map* map;
2118
2119 if (is_ascii) {
2120 if (chars <= String::kMaxShortStringSize) {
2121 map = short_ascii_symbol_map();
2122 } else if (chars <= String::kMaxMediumStringSize) {
2123 map = medium_ascii_symbol_map();
2124 } else {
2125 map = long_ascii_symbol_map();
2126 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002127 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002128 } else {
2129 if (chars <= String::kMaxShortStringSize) {
2130 map = short_symbol_map();
2131 } else if (chars <= String::kMaxMediumStringSize) {
2132 map = medium_symbol_map();
2133 } else {
2134 map = long_symbol_map();
2135 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002136 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002137 }
2138
2139 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002140 AllocationSpace space =
2141 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002142 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002143 if (result->IsFailure()) return result;
2144
2145 reinterpret_cast<HeapObject*>(result)->set_map(map);
2146 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002147 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002148 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002149
ager@chromium.org870a0b62008-11-04 11:43:05 +00002150 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002151
2152 // Fill in the characters.
2153 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002154 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002155 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002156 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002157}
2158
2159
2160Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002161 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002162 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002163 if (size > MaxHeapObjectSize()) {
2164 space = LO_SPACE;
2165 }
2166
2167 // Use AllocateRaw rather than Allocate because the object's size cannot be
2168 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002169 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002170 if (result->IsFailure()) return result;
2171
2172 // Determine the map based on the string's length.
2173 Map* map;
2174 if (length <= String::kMaxShortStringSize) {
2175 map = short_ascii_string_map();
2176 } else if (length <= String::kMaxMediumStringSize) {
2177 map = medium_ascii_string_map();
2178 } else {
2179 map = long_ascii_string_map();
2180 }
2181
2182 // Partially initialize the object.
2183 HeapObject::cast(result)->set_map(map);
2184 String::cast(result)->set_length(length);
2185 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2186 return result;
2187}
2188
2189
2190Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002191 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002192 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002193 if (size > MaxHeapObjectSize()) {
2194 space = LO_SPACE;
2195 }
2196
2197 // Use AllocateRaw rather than Allocate because the object's size cannot be
2198 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002199 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002200 if (result->IsFailure()) return result;
2201
2202 // Determine the map based on the string's length.
2203 Map* map;
2204 if (length <= String::kMaxShortStringSize) {
2205 map = short_string_map();
2206 } else if (length <= String::kMaxMediumStringSize) {
2207 map = medium_string_map();
2208 } else {
2209 map = long_string_map();
2210 }
2211
2212 // Partially initialize the object.
2213 HeapObject::cast(result)->set_map(map);
2214 String::cast(result)->set_length(length);
2215 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2216 return result;
2217}
2218
2219
2220Object* Heap::AllocateEmptyFixedArray() {
2221 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002222 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002223 if (result->IsFailure()) return result;
2224 // Initialize the object.
2225 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2226 reinterpret_cast<Array*>(result)->set_length(0);
2227 return result;
2228}
2229
2230
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002231Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002232 // Use the general function if we're forced to always allocate.
2233 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002234 // Allocate the raw data for a fixed array.
2235 int size = FixedArray::SizeFor(length);
2236 return (size > MaxHeapObjectSize())
2237 ? lo_space_->AllocateRawFixedArray(size)
2238 : new_space_.AllocateRaw(size);
2239}
2240
2241
2242Object* Heap::CopyFixedArray(FixedArray* src) {
2243 int len = src->length();
2244 Object* obj = AllocateRawFixedArray(len);
2245 if (obj->IsFailure()) return obj;
2246 if (Heap::InNewSpace(obj)) {
2247 HeapObject* dst = HeapObject::cast(obj);
2248 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2249 reinterpret_cast<Object**>(src->address()),
2250 FixedArray::SizeFor(len));
2251 return obj;
2252 }
2253 HeapObject::cast(obj)->set_map(src->map());
2254 FixedArray* result = FixedArray::cast(obj);
2255 result->set_length(len);
2256 // Copy the content
2257 WriteBarrierMode mode = result->GetWriteBarrierMode();
2258 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2259 return result;
2260}
2261
2262
2263Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002264 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002265 Object* result = AllocateRawFixedArray(length);
2266 if (!result->IsFailure()) {
2267 // Initialize header.
2268 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2269 FixedArray* array = FixedArray::cast(result);
2270 array->set_length(length);
2271 Object* value = undefined_value();
2272 // Initialize body.
2273 for (int index = 0; index < length; index++) {
2274 array->set(index, value, SKIP_WRITE_BARRIER);
2275 }
2276 }
2277 return result;
2278}
2279
2280
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002281Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2282 ASSERT(empty_fixed_array()->IsFixedArray());
2283 if (length == 0) return empty_fixed_array();
2284
2285 int size = FixedArray::SizeFor(length);
2286 Object* result;
2287 if (size > MaxHeapObjectSize()) {
2288 result = lo_space_->AllocateRawFixedArray(size);
2289 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002290 AllocationSpace space =
2291 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002292 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002293 }
2294 if (result->IsFailure()) return result;
2295
2296 // Initialize the object.
2297 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2298 FixedArray* array = FixedArray::cast(result);
2299 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002300 Object* value = undefined_value();
2301 for (int index = 0; index < length; index++) {
2302 array->set(index, value, SKIP_WRITE_BARRIER);
2303 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002304 return array;
2305}
2306
2307
2308Object* Heap::AllocateFixedArrayWithHoles(int length) {
2309 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002310 Object* result = AllocateRawFixedArray(length);
2311 if (!result->IsFailure()) {
2312 // Initialize header.
2313 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2314 FixedArray* array = FixedArray::cast(result);
2315 array->set_length(length);
2316 // Initialize body.
2317 Object* value = the_hole_value();
2318 for (int index = 0; index < length; index++) {
2319 array->set(index, value, SKIP_WRITE_BARRIER);
2320 }
2321 }
2322 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002323}
2324
2325
2326Object* Heap::AllocateHashTable(int length) {
2327 Object* result = Heap::AllocateFixedArray(length);
2328 if (result->IsFailure()) return result;
2329 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2330 ASSERT(result->IsDictionary());
2331 return result;
2332}
2333
2334
2335Object* Heap::AllocateGlobalContext() {
2336 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2337 if (result->IsFailure()) return result;
2338 Context* context = reinterpret_cast<Context*>(result);
2339 context->set_map(global_context_map());
2340 ASSERT(context->IsGlobalContext());
2341 ASSERT(result->IsContext());
2342 return result;
2343}
2344
2345
2346Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2347 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2348 Object* result = Heap::AllocateFixedArray(length);
2349 if (result->IsFailure()) return result;
2350 Context* context = reinterpret_cast<Context*>(result);
2351 context->set_map(context_map());
2352 context->set_closure(function);
2353 context->set_fcontext(context);
2354 context->set_previous(NULL);
2355 context->set_extension(NULL);
2356 context->set_global(function->context()->global());
2357 ASSERT(!context->IsGlobalContext());
2358 ASSERT(context->is_function_context());
2359 ASSERT(result->IsContext());
2360 return result;
2361}
2362
2363
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002364Object* Heap::AllocateWithContext(Context* previous,
2365 JSObject* extension,
2366 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002367 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2368 if (result->IsFailure()) return result;
2369 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002370 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002371 context->set_closure(previous->closure());
2372 context->set_fcontext(previous->fcontext());
2373 context->set_previous(previous);
2374 context->set_extension(extension);
2375 context->set_global(previous->global());
2376 ASSERT(!context->IsGlobalContext());
2377 ASSERT(!context->is_function_context());
2378 ASSERT(result->IsContext());
2379 return result;
2380}
2381
2382
2383Object* Heap::AllocateStruct(InstanceType type) {
2384 Map* map;
2385 switch (type) {
2386#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2387STRUCT_LIST(MAKE_CASE)
2388#undef MAKE_CASE
2389 default:
2390 UNREACHABLE();
2391 return Failure::InternalError();
2392 }
2393 int size = map->instance_size();
2394 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002395 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002396 Object* result = Heap::Allocate(map, space);
2397 if (result->IsFailure()) return result;
2398 Struct::cast(result)->InitializeBody(size);
2399 return result;
2400}
2401
2402
2403#ifdef DEBUG
2404
2405void Heap::Print() {
2406 if (!HasBeenSetup()) return;
2407 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002408 AllSpaces spaces;
2409 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002410}
2411
2412
2413void Heap::ReportCodeStatistics(const char* title) {
2414 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2415 PagedSpace::ResetCodeStatistics();
2416 // We do not look for code in new space, map space, or old space. If code
2417 // somehow ends up in those spaces, we would miss it here.
2418 code_space_->CollectCodeStatistics();
2419 lo_space_->CollectCodeStatistics();
2420 PagedSpace::ReportCodeStatistics();
2421}
2422
2423
2424// This function expects that NewSpace's allocated objects histogram is
2425// populated (via a call to CollectStatistics or else as a side effect of a
2426// just-completed scavenge collection).
2427void Heap::ReportHeapStatistics(const char* title) {
2428 USE(title);
2429 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2430 title, gc_count_);
2431 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002432 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2433 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002434
2435 PrintF("\n");
2436 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2437 GlobalHandles::PrintStats();
2438 PrintF("\n");
2439
2440 PrintF("Heap statistics : ");
2441 MemoryAllocator::ReportStatistics();
2442 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002443 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002444 PrintF("Old pointer space : ");
2445 old_pointer_space_->ReportStatistics();
2446 PrintF("Old data space : ");
2447 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002448 PrintF("Code space : ");
2449 code_space_->ReportStatistics();
2450 PrintF("Map space : ");
2451 map_space_->ReportStatistics();
2452 PrintF("Large object space : ");
2453 lo_space_->ReportStatistics();
2454 PrintF(">>>>>> ========================================= >>>>>>\n");
2455}
2456
2457#endif // DEBUG
2458
2459bool Heap::Contains(HeapObject* value) {
2460 return Contains(value->address());
2461}
2462
2463
2464bool Heap::Contains(Address addr) {
2465 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2466 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002467 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002468 old_pointer_space_->Contains(addr) ||
2469 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002470 code_space_->Contains(addr) ||
2471 map_space_->Contains(addr) ||
2472 lo_space_->SlowContains(addr));
2473}
2474
2475
2476bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2477 return InSpace(value->address(), space);
2478}
2479
2480
2481bool Heap::InSpace(Address addr, AllocationSpace space) {
2482 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2483 if (!HasBeenSetup()) return false;
2484
2485 switch (space) {
2486 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002487 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002488 case OLD_POINTER_SPACE:
2489 return old_pointer_space_->Contains(addr);
2490 case OLD_DATA_SPACE:
2491 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002492 case CODE_SPACE:
2493 return code_space_->Contains(addr);
2494 case MAP_SPACE:
2495 return map_space_->Contains(addr);
2496 case LO_SPACE:
2497 return lo_space_->SlowContains(addr);
2498 }
2499
2500 return false;
2501}
2502
2503
2504#ifdef DEBUG
2505void Heap::Verify() {
2506 ASSERT(HasBeenSetup());
2507
2508 VerifyPointersVisitor visitor;
2509 Heap::IterateRoots(&visitor);
2510
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002511 AllSpaces spaces;
2512 while (Space* space = spaces.next()) {
2513 space->Verify();
2514 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002515}
2516#endif // DEBUG
2517
2518
2519Object* Heap::LookupSymbol(Vector<const char> string) {
2520 Object* symbol = NULL;
2521 Object* new_table =
2522 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2523 if (new_table->IsFailure()) return new_table;
2524 symbol_table_ = new_table;
2525 ASSERT(symbol != NULL);
2526 return symbol;
2527}
2528
2529
2530Object* Heap::LookupSymbol(String* string) {
2531 if (string->IsSymbol()) return string;
2532 Object* symbol = NULL;
2533 Object* new_table =
2534 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2535 if (new_table->IsFailure()) return new_table;
2536 symbol_table_ = new_table;
2537 ASSERT(symbol != NULL);
2538 return symbol;
2539}
2540
2541
ager@chromium.org7c537e22008-10-16 08:43:32 +00002542bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2543 if (string->IsSymbol()) {
2544 *symbol = string;
2545 return true;
2546 }
2547 SymbolTable* table = SymbolTable::cast(symbol_table_);
2548 return table->LookupSymbolIfExists(string, symbol);
2549}
2550
2551
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002552#ifdef DEBUG
2553void Heap::ZapFromSpace() {
2554 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002555 for (Address a = new_space_.FromSpaceLow();
2556 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002557 a += kPointerSize) {
2558 Memory::Address_at(a) = kFromSpaceZapValue;
2559 }
2560}
2561#endif // DEBUG
2562
2563
2564void Heap::IterateRSetRange(Address object_start,
2565 Address object_end,
2566 Address rset_start,
2567 ObjectSlotCallback copy_object_func) {
2568 Address object_address = object_start;
2569 Address rset_address = rset_start;
2570
2571 // Loop over all the pointers in [object_start, object_end).
2572 while (object_address < object_end) {
2573 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002574 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002575 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002576 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002577 // Do not dereference pointers at or past object_end.
2578 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2579 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002580 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002581 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2582 }
2583 // If this pointer does not need to be remembered anymore, clear
2584 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002585 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002586 }
2587 object_address += kPointerSize;
2588 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002589 // Update the remembered set if it has changed.
2590 if (result_rset != rset_word) {
2591 Memory::uint32_at(rset_address) = result_rset;
2592 }
2593 } else {
2594 // No bits in the word were set. This is the common case.
2595 object_address += kPointerSize * kBitsPerInt;
2596 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002597 rset_address += kIntSize;
2598 }
2599}
2600
2601
2602void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2603 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002604 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002605
2606 PageIterator it(space, PageIterator::PAGES_IN_USE);
2607 while (it.has_next()) {
2608 Page* page = it.next();
2609 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2610 page->RSetStart(), copy_object_func);
2611 }
2612}
2613
2614
2615#ifdef DEBUG
2616#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2617#else
2618#define SYNCHRONIZE_TAG(tag)
2619#endif
2620
2621void Heap::IterateRoots(ObjectVisitor* v) {
2622 IterateStrongRoots(v);
2623 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2624 SYNCHRONIZE_TAG("symbol_table");
2625}
2626
2627
2628void Heap::IterateStrongRoots(ObjectVisitor* v) {
2629#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002630 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002631 STRONG_ROOT_LIST(ROOT_ITERATE);
2632#undef ROOT_ITERATE
2633 SYNCHRONIZE_TAG("strong_root_list");
2634
2635#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002636 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002637 STRUCT_LIST(STRUCT_MAP_ITERATE);
2638#undef STRUCT_MAP_ITERATE
2639 SYNCHRONIZE_TAG("struct_map");
2640
2641#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002642 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002643 SYMBOL_LIST(SYMBOL_ITERATE)
2644#undef SYMBOL_ITERATE
ager@chromium.org3b45ab52009-03-19 22:21:34 +00002645 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002646 SYNCHRONIZE_TAG("symbol");
2647
2648 Bootstrapper::Iterate(v);
2649 SYNCHRONIZE_TAG("bootstrapper");
2650 Top::Iterate(v);
2651 SYNCHRONIZE_TAG("top");
2652 Debug::Iterate(v);
2653 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002654 CompilationCache::Iterate(v);
2655 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002656
2657 // Iterate over local handles in handle scopes.
2658 HandleScopeImplementer::Iterate(v);
2659 SYNCHRONIZE_TAG("handlescope");
2660
2661 // Iterate over the builtin code objects and code stubs in the heap. Note
2662 // that it is not strictly necessary to iterate over code objects on
2663 // scavenge collections. We still do it here because this same function
2664 // is used by the mark-sweep collector and the deserializer.
2665 Builtins::IterateBuiltins(v);
2666 SYNCHRONIZE_TAG("builtins");
2667
2668 // Iterate over global handles.
2669 GlobalHandles::IterateRoots(v);
2670 SYNCHRONIZE_TAG("globalhandles");
2671
2672 // Iterate over pointers being held by inactive threads.
2673 ThreadManager::Iterate(v);
2674 SYNCHRONIZE_TAG("threadmanager");
2675}
2676#undef SYNCHRONIZE_TAG
2677
2678
2679// Flag is set when the heap has been configured. The heap can be repeatedly
2680// configured through the API until it is setup.
2681static bool heap_configured = false;
2682
2683// TODO(1236194): Since the heap size is configurable on the command line
2684// and through the API, we should gracefully handle the case that the heap
2685// size is not big enough to fit all the initial objects.
2686bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2687 if (HasBeenSetup()) return false;
2688
2689 if (semispace_size > 0) semispace_size_ = semispace_size;
2690 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2691
2692 // The new space size must be a power of two to support single-bit testing
2693 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002694 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002695 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2696 young_generation_size_ = 2 * semispace_size_;
2697
2698 // The old generation is paged.
2699 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2700
2701 heap_configured = true;
2702 return true;
2703}
2704
2705
kasper.lund7276f142008-07-30 08:49:36 +00002706bool Heap::ConfigureHeapDefault() {
2707 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2708}
2709
2710
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002711int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002712 return old_pointer_space_->Size()
2713 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002714 + code_space_->Size()
2715 + map_space_->Size()
2716 + lo_space_->Size();
2717}
2718
2719
kasper.lund7276f142008-07-30 08:49:36 +00002720int Heap::PromotedExternalMemorySize() {
2721 if (amount_of_external_allocated_memory_
2722 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2723 return amount_of_external_allocated_memory_
2724 - amount_of_external_allocated_memory_at_last_global_gc_;
2725}
2726
2727
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002728bool Heap::Setup(bool create_heap_objects) {
2729 // Initialize heap spaces and initial maps and objects. Whenever something
2730 // goes wrong, just return false. The caller should check the results and
2731 // call Heap::TearDown() to release allocated memory.
2732 //
2733 // If the heap is not yet configured (eg, through the API), configure it.
2734 // Configuration is based on the flags new-space-size (really the semispace
2735 // size) and old-space-size if set or the initial values of semispace_size_
2736 // and old_generation_size_ otherwise.
2737 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002738 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002739 }
2740
2741 // Setup memory allocator and allocate an initial chunk of memory. The
2742 // initial chunk is double the size of the new space to ensure that we can
2743 // find a pair of semispaces that are contiguous and aligned to their size.
2744 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2745 void* chunk
2746 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2747 if (chunk == NULL) return false;
2748
2749 // Put the initial chunk of the old space at the start of the initial
2750 // chunk, then the two new space semispaces, then the initial chunk of
2751 // code space. Align the pair of semispaces to their size, which must be
2752 // a power of 2.
2753 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002754 Address code_space_start = reinterpret_cast<Address>(chunk);
2755 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2756 Address old_space_start = new_space_start + young_generation_size_;
2757 int code_space_size = new_space_start - code_space_start;
2758 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002759
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002760 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002761 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002762
2763 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002764 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002765 old_pointer_space_ =
2766 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2767 if (old_pointer_space_ == NULL) return false;
2768 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2769 return false;
2770 }
2771 old_data_space_ =
2772 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2773 if (old_data_space_ == NULL) return false;
2774 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2775 old_space_size >> 1)) {
2776 return false;
2777 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002778
2779 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002780 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002781 code_space_ =
2782 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002783 if (code_space_ == NULL) return false;
2784 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2785
2786 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002787 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002788 if (map_space_ == NULL) return false;
2789 // Setting up a paged space without giving it a virtual memory range big
2790 // enough to hold at least a page will cause it to allocate.
2791 if (!map_space_->Setup(NULL, 0)) return false;
2792
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002793 // The large object code space may contain code or data. We set the memory
2794 // to be non-executable here for safety, but this means we need to enable it
2795 // explicitly when allocating large code objects.
2796 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002797 if (lo_space_ == NULL) return false;
2798 if (!lo_space_->Setup()) return false;
2799
2800 if (create_heap_objects) {
2801 // Create initial maps.
2802 if (!CreateInitialMaps()) return false;
2803 if (!CreateApiObjects()) return false;
2804
2805 // Create initial objects
2806 if (!CreateInitialObjects()) return false;
2807 }
2808
2809 LOG(IntEvent("heap-capacity", Capacity()));
2810 LOG(IntEvent("heap-available", Available()));
2811
2812 return true;
2813}
2814
2815
2816void Heap::TearDown() {
2817 GlobalHandles::TearDown();
2818
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002819 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002820
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002821 if (old_pointer_space_ != NULL) {
2822 old_pointer_space_->TearDown();
2823 delete old_pointer_space_;
2824 old_pointer_space_ = NULL;
2825 }
2826
2827 if (old_data_space_ != NULL) {
2828 old_data_space_->TearDown();
2829 delete old_data_space_;
2830 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002831 }
2832
2833 if (code_space_ != NULL) {
2834 code_space_->TearDown();
2835 delete code_space_;
2836 code_space_ = NULL;
2837 }
2838
2839 if (map_space_ != NULL) {
2840 map_space_->TearDown();
2841 delete map_space_;
2842 map_space_ = NULL;
2843 }
2844
2845 if (lo_space_ != NULL) {
2846 lo_space_->TearDown();
2847 delete lo_space_;
2848 lo_space_ = NULL;
2849 }
2850
2851 MemoryAllocator::TearDown();
2852}
2853
2854
2855void Heap::Shrink() {
2856 // Try to shrink map, old, and code spaces.
2857 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002858 old_pointer_space_->Shrink();
2859 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002860 code_space_->Shrink();
2861}
2862
2863
2864#ifdef DEBUG
2865
2866class PrintHandleVisitor: public ObjectVisitor {
2867 public:
2868 void VisitPointers(Object** start, Object** end) {
2869 for (Object** p = start; p < end; p++)
2870 PrintF(" handle %p to %p\n", p, *p);
2871 }
2872};
2873
2874void Heap::PrintHandles() {
2875 PrintF("Handles:\n");
2876 PrintHandleVisitor v;
2877 HandleScopeImplementer::Iterate(&v);
2878}
2879
2880#endif
2881
2882
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002883Space* AllSpaces::next() {
2884 switch (counter_++) {
2885 case NEW_SPACE:
2886 return Heap::new_space();
2887 case OLD_POINTER_SPACE:
2888 return Heap::old_pointer_space();
2889 case OLD_DATA_SPACE:
2890 return Heap::old_data_space();
2891 case CODE_SPACE:
2892 return Heap::code_space();
2893 case MAP_SPACE:
2894 return Heap::map_space();
2895 case LO_SPACE:
2896 return Heap::lo_space();
2897 default:
2898 return NULL;
2899 }
2900}
2901
2902
2903PagedSpace* PagedSpaces::next() {
2904 switch (counter_++) {
2905 case OLD_POINTER_SPACE:
2906 return Heap::old_pointer_space();
2907 case OLD_DATA_SPACE:
2908 return Heap::old_data_space();
2909 case CODE_SPACE:
2910 return Heap::code_space();
2911 case MAP_SPACE:
2912 return Heap::map_space();
2913 default:
2914 return NULL;
2915 }
2916}
2917
2918
2919
2920OldSpace* OldSpaces::next() {
2921 switch (counter_++) {
2922 case OLD_POINTER_SPACE:
2923 return Heap::old_pointer_space();
2924 case OLD_DATA_SPACE:
2925 return Heap::old_data_space();
2926 case CODE_SPACE:
2927 return Heap::code_space();
2928 default:
2929 return NULL;
2930 }
2931}
2932
2933
kasper.lund7276f142008-07-30 08:49:36 +00002934SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2935}
2936
2937
2938SpaceIterator::~SpaceIterator() {
2939 // Delete active iterator if any.
2940 delete iterator_;
2941}
2942
2943
2944bool SpaceIterator::has_next() {
2945 // Iterate until no more spaces.
2946 return current_space_ != LAST_SPACE;
2947}
2948
2949
2950ObjectIterator* SpaceIterator::next() {
2951 if (iterator_ != NULL) {
2952 delete iterator_;
2953 iterator_ = NULL;
2954 // Move to the next space
2955 current_space_++;
2956 if (current_space_ > LAST_SPACE) {
2957 return NULL;
2958 }
2959 }
2960
2961 // Return iterator for the new current space.
2962 return CreateIterator();
2963}
2964
2965
2966// Create an iterator for the space to iterate.
2967ObjectIterator* SpaceIterator::CreateIterator() {
2968 ASSERT(iterator_ == NULL);
2969
2970 switch (current_space_) {
2971 case NEW_SPACE:
2972 iterator_ = new SemiSpaceIterator(Heap::new_space());
2973 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002974 case OLD_POINTER_SPACE:
2975 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2976 break;
2977 case OLD_DATA_SPACE:
2978 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002979 break;
2980 case CODE_SPACE:
2981 iterator_ = new HeapObjectIterator(Heap::code_space());
2982 break;
2983 case MAP_SPACE:
2984 iterator_ = new HeapObjectIterator(Heap::map_space());
2985 break;
2986 case LO_SPACE:
2987 iterator_ = new LargeObjectIterator(Heap::lo_space());
2988 break;
2989 }
2990
2991 // Return the newly allocated iterator;
2992 ASSERT(iterator_ != NULL);
2993 return iterator_;
2994}
2995
2996
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002997HeapIterator::HeapIterator() {
2998 Init();
2999}
3000
3001
3002HeapIterator::~HeapIterator() {
3003 Shutdown();
3004}
3005
3006
3007void HeapIterator::Init() {
3008 // Start the iteration.
3009 space_iterator_ = new SpaceIterator();
3010 object_iterator_ = space_iterator_->next();
3011}
3012
3013
3014void HeapIterator::Shutdown() {
3015 // Make sure the last iterator is deallocated.
3016 delete space_iterator_;
3017 space_iterator_ = NULL;
3018 object_iterator_ = NULL;
3019}
3020
3021
3022bool HeapIterator::has_next() {
3023 // No iterator means we are done.
3024 if (object_iterator_ == NULL) return false;
3025
3026 if (object_iterator_->has_next_object()) {
3027 // If the current iterator has more objects we are fine.
3028 return true;
3029 } else {
3030 // Go though the spaces looking for one that has objects.
3031 while (space_iterator_->has_next()) {
3032 object_iterator_ = space_iterator_->next();
3033 if (object_iterator_->has_next_object()) {
3034 return true;
3035 }
3036 }
3037 }
3038 // Done with the last space.
3039 object_iterator_ = NULL;
3040 return false;
3041}
3042
3043
3044HeapObject* HeapIterator::next() {
3045 if (has_next()) {
3046 return object_iterator_->next_object();
3047 } else {
3048 return NULL;
3049 }
3050}
3051
3052
3053void HeapIterator::reset() {
3054 // Restart the iterator.
3055 Shutdown();
3056 Init();
3057}
3058
3059
3060//
3061// HeapProfiler class implementation.
3062//
3063#ifdef ENABLE_LOGGING_AND_PROFILING
3064void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3065 InstanceType type = obj->map()->instance_type();
3066 ASSERT(0 <= type && type <= LAST_TYPE);
3067 info[type].increment_number(1);
3068 info[type].increment_bytes(obj->Size());
3069}
3070#endif
3071
3072
3073#ifdef ENABLE_LOGGING_AND_PROFILING
3074void HeapProfiler::WriteSample() {
3075 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3076
3077 HistogramInfo info[LAST_TYPE+1];
3078#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3079 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3080#undef DEF_TYPE_NAME
3081
3082 HeapIterator iterator;
3083 while (iterator.has_next()) {
3084 CollectStats(iterator.next(), info);
3085 }
3086
3087 // Lump all the string types together.
3088 int string_number = 0;
3089 int string_bytes = 0;
3090#define INCREMENT_SIZE(type, size, name) \
3091 string_number += info[type].number(); \
3092 string_bytes += info[type].bytes();
3093 STRING_TYPE_LIST(INCREMENT_SIZE)
3094#undef INCREMENT_SIZE
3095 if (string_bytes > 0) {
3096 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3097 }
3098
3099 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3100 if (info[i].bytes() > 0) {
3101 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3102 info[i].bytes()));
3103 }
3104 }
3105
3106 LOG(HeapSampleEndEvent("Heap", "allocated"));
3107}
3108
3109
3110#endif
3111
3112
3113
3114#ifdef DEBUG
3115
3116static bool search_for_any_global;
3117static Object* search_target;
3118static bool found_target;
3119static List<Object*> object_stack(20);
3120
3121
3122// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3123static const int kMarkTag = 2;
3124
3125static void MarkObjectRecursively(Object** p);
3126class MarkObjectVisitor : public ObjectVisitor {
3127 public:
3128 void VisitPointers(Object** start, Object** end) {
3129 // Copy all HeapObject pointers in [start, end)
3130 for (Object** p = start; p < end; p++) {
3131 if ((*p)->IsHeapObject())
3132 MarkObjectRecursively(p);
3133 }
3134 }
3135};
3136
3137static MarkObjectVisitor mark_visitor;
3138
3139static void MarkObjectRecursively(Object** p) {
3140 if (!(*p)->IsHeapObject()) return;
3141
3142 HeapObject* obj = HeapObject::cast(*p);
3143
3144 Object* map = obj->map();
3145
3146 if (!map->IsHeapObject()) return; // visited before
3147
3148 if (found_target) return; // stop if target found
3149 object_stack.Add(obj);
3150 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3151 (!search_for_any_global && (obj == search_target))) {
3152 found_target = true;
3153 return;
3154 }
3155
3156 if (obj->IsCode()) {
3157 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3158 }
3159
3160 // not visited yet
3161 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3162
3163 Address map_addr = map_p->address();
3164
3165 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3166
3167 MarkObjectRecursively(&map);
3168
3169 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3170 &mark_visitor);
3171
3172 if (!found_target) // don't pop if found the target
3173 object_stack.RemoveLast();
3174}
3175
3176
3177static void UnmarkObjectRecursively(Object** p);
3178class UnmarkObjectVisitor : public ObjectVisitor {
3179 public:
3180 void VisitPointers(Object** start, Object** end) {
3181 // Copy all HeapObject pointers in [start, end)
3182 for (Object** p = start; p < end; p++) {
3183 if ((*p)->IsHeapObject())
3184 UnmarkObjectRecursively(p);
3185 }
3186 }
3187};
3188
3189static UnmarkObjectVisitor unmark_visitor;
3190
3191static void UnmarkObjectRecursively(Object** p) {
3192 if (!(*p)->IsHeapObject()) return;
3193
3194 HeapObject* obj = HeapObject::cast(*p);
3195
3196 Object* map = obj->map();
3197
3198 if (map->IsHeapObject()) return; // unmarked already
3199
3200 Address map_addr = reinterpret_cast<Address>(map);
3201
3202 map_addr -= kMarkTag;
3203
3204 ASSERT_TAG_ALIGNED(map_addr);
3205
3206 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3207
3208 obj->set_map(reinterpret_cast<Map*>(map_p));
3209
3210 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3211
3212 obj->IterateBody(Map::cast(map_p)->instance_type(),
3213 obj->SizeFromMap(Map::cast(map_p)),
3214 &unmark_visitor);
3215
3216 if (obj->IsCode()) {
3217 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3218 }
3219}
3220
3221
3222static void MarkRootObjectRecursively(Object** root) {
3223 if (search_for_any_global) {
3224 ASSERT(search_target == NULL);
3225 } else {
3226 ASSERT(search_target->IsHeapObject());
3227 }
3228 found_target = false;
3229 object_stack.Clear();
3230
3231 MarkObjectRecursively(root);
3232 UnmarkObjectRecursively(root);
3233
3234 if (found_target) {
3235 PrintF("=====================================\n");
3236 PrintF("==== Path to object ====\n");
3237 PrintF("=====================================\n\n");
3238
3239 ASSERT(!object_stack.is_empty());
3240 for (int i = 0; i < object_stack.length(); i++) {
3241 if (i > 0) PrintF("\n |\n |\n V\n\n");
3242 Object* obj = object_stack[i];
3243 obj->Print();
3244 }
3245 PrintF("=====================================\n");
3246 }
3247}
3248
3249
3250// Helper class for visiting HeapObjects recursively.
3251class MarkRootVisitor: public ObjectVisitor {
3252 public:
3253 void VisitPointers(Object** start, Object** end) {
3254 // Visit all HeapObject pointers in [start, end)
3255 for (Object** p = start; p < end; p++) {
3256 if ((*p)->IsHeapObject())
3257 MarkRootObjectRecursively(p);
3258 }
3259 }
3260};
3261
3262
3263// Triggers a depth-first traversal of reachable objects from roots
3264// and finds a path to a specific heap object and prints it.
3265void Heap::TracePathToObject() {
3266 search_target = NULL;
3267 search_for_any_global = false;
3268
3269 MarkRootVisitor root_visitor;
3270 IterateRoots(&root_visitor);
3271}
3272
3273
3274// Triggers a depth-first traversal of reachable objects from roots
3275// and finds a path to any global object and prints it. Useful for
3276// determining the source for leaks of global objects.
3277void Heap::TracePathToGlobal() {
3278 search_target = NULL;
3279 search_for_any_global = true;
3280
3281 MarkRootVisitor root_visitor;
3282 IterateRoots(&root_visitor);
3283}
3284#endif
3285
3286
kasper.lund7276f142008-07-30 08:49:36 +00003287GCTracer::GCTracer()
3288 : start_time_(0.0),
3289 start_size_(0.0),
3290 gc_count_(0),
3291 full_gc_count_(0),
3292 is_compacting_(false),
3293 marked_count_(0) {
3294 // These two fields reflect the state of the previous full collection.
3295 // Set them before they are changed by the collector.
3296 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3297 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3298 if (!FLAG_trace_gc) return;
3299 start_time_ = OS::TimeCurrentMillis();
3300 start_size_ = SizeOfHeapObjects();
3301}
3302
3303
3304GCTracer::~GCTracer() {
3305 if (!FLAG_trace_gc) return;
3306 // Printf ONE line iff flag is set.
3307 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3308 CollectorString(),
3309 start_size_, SizeOfHeapObjects(),
3310 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3311}
3312
3313
3314const char* GCTracer::CollectorString() {
3315 switch (collector_) {
3316 case SCAVENGER:
3317 return "Scavenge";
3318 case MARK_COMPACTOR:
3319 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3320 : "Mark-sweep";
3321 }
3322 return "Unknown GC";
3323}
3324
3325
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003326#ifdef DEBUG
3327bool Heap::GarbageCollectionGreedyCheck() {
3328 ASSERT(FLAG_gc_greedy);
3329 if (Bootstrapper::IsActive()) return true;
3330 if (disallow_allocation_failure()) return true;
3331 return CollectGarbage(0, NEW_SPACE);
3332}
3333#endif
3334
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003335} } // namespace v8::internal