blob: 53b0774ff1c192edc16686e3370d69ce2a45fe70 [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"
37#include "jsregexp.h"
38#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
42#include "v8threads.h"
43
44namespace v8 { namespace internal {
45
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
47 ROOT_LIST(ROOT_ALLOCATION)
48#undef ROOT_ALLOCATION
49
50
51#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
52 STRUCT_LIST(STRUCT_ALLOCATION)
53#undef STRUCT_ALLOCATION
54
55
56#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
57 SYMBOL_LIST(SYMBOL_ALLOCATION)
58#undef SYMBOL_ALLOCATION
59
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000060NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000061OldSpace* Heap::old_pointer_space_ = NULL;
62OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063OldSpace* Heap::code_space_ = NULL;
64MapSpace* Heap::map_space_ = NULL;
65LargeObjectSpace* Heap::lo_space_ = NULL;
66
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000067static const int kMinimumPromotionLimit = 2*MB;
68static const int kMinimumAllocationLimit = 8*MB;
69
70int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
71int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
72
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073int Heap::old_gen_exhausted_ = false;
74
kasper.lund7276f142008-07-30 08:49:36 +000075int Heap::amount_of_external_allocated_memory_ = 0;
76int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
77
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078// semispace_size_ should be a power of 2 and old_generation_size_ should be
79// a multiple of Page::kPageSize.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000080int Heap::semispace_size_ = 2*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081int Heap::old_generation_size_ = 512*MB;
82int Heap::initial_semispace_size_ = 256*KB;
83
84GCCallback Heap::global_gc_prologue_callback_ = NULL;
85GCCallback Heap::global_gc_epilogue_callback_ = NULL;
86
ager@chromium.orga74f0da2008-12-03 16:05:52 +000087ExternalSymbolCallback Heap::global_external_symbol_callback_ = NULL;
88
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000089// Variables set based on semispace_size_ and old_generation_size_ in
90// ConfigureHeap.
91int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
92
93// Double the new space after this many scavenge collections.
94int Heap::new_space_growth_limit_ = 8;
95int Heap::scavenge_count_ = 0;
96Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
97
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000098int Heap::mc_count_ = 0;
99int Heap::gc_count_ = 0;
100
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000101int Heap::always_allocate_scope_depth_ = 0;
102
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() {
232 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000233 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000234#ifdef DEBUG
235 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
236 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000237
238 if (FLAG_verify_heap) {
239 Verify();
240 }
241
242 if (FLAG_gc_verbose) Print();
243
244 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000245 // Not all spaces have remembered set bits that we care about.
246 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000247 map_space_->PrintRSet();
248 lo_space_->PrintRSet();
249 }
250#endif
251
252#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
253 ReportStatisticsBeforeGC();
254#endif
255}
256
257int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000258 int total = 0;
259 AllSpaces spaces;
260 while (Space* space = spaces.next()) total += space->Size();
261 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262}
263
264void Heap::GarbageCollectionEpilogue() {
265#ifdef DEBUG
266 allow_allocation(true);
267 ZapFromSpace();
268
269 if (FLAG_verify_heap) {
270 Verify();
271 }
272
273 if (FLAG_print_global_handles) GlobalHandles::Print();
274 if (FLAG_print_handles) PrintHandles();
275 if (FLAG_gc_verbose) Print();
276 if (FLAG_code_stats) ReportCodeStatistics("After GC");
277#endif
278
279 Counters::alive_after_last_gc.Set(SizeOfObjects());
280
281 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
282 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
283 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
284#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
285 ReportStatisticsAfterGC();
286#endif
287}
288
289
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000290void Heap::CollectAllGarbage() {
291 // Since we are ignoring the return value, the exact choice of space does
292 // not matter, so long as we do not specify NEW_SPACE, which would not
293 // cause a full GC.
294 CollectGarbage(0, OLD_POINTER_SPACE);
295}
296
297
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
299 // The VM is in the GC state until exiting this function.
300 VMState state(GC);
301
302#ifdef DEBUG
303 // Reset the allocation timeout to the GC interval, but make sure to
304 // allow at least a few allocations after a collection. The reason
305 // for this is that we have a lot of allocation sequences and we
306 // assume that a garbage collection will allow the subsequent
307 // allocation attempts to go through.
308 allocation_timeout_ = Max(6, FLAG_gc_interval);
309#endif
310
311 { GCTracer tracer;
312 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000313 // The GC count was incremented in the prologue. Tell the tracer about
314 // it.
315 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316
317 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000318 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319 tracer.set_collector(collector);
320
321 StatsRate* rate = (collector == SCAVENGER)
322 ? &Counters::gc_scavenger
323 : &Counters::gc_compactor;
324 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000325 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000326 rate->Stop();
327
328 GarbageCollectionEpilogue();
329 }
330
331
332#ifdef ENABLE_LOGGING_AND_PROFILING
333 if (FLAG_log_gc) HeapProfiler::WriteSample();
334#endif
335
336 switch (space) {
337 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000338 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000339 case OLD_POINTER_SPACE:
340 return old_pointer_space_->Available() >= requested_size;
341 case OLD_DATA_SPACE:
342 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 case CODE_SPACE:
344 return code_space_->Available() >= requested_size;
345 case MAP_SPACE:
346 return map_space_->Available() >= requested_size;
347 case LO_SPACE:
348 return lo_space_->Available() >= requested_size;
349 }
350 return false;
351}
352
353
kasper.lund7276f142008-07-30 08:49:36 +0000354void Heap::PerformScavenge() {
355 GCTracer tracer;
356 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
357}
358
359
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000361 GarbageCollector collector,
362 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
364 ASSERT(!allocation_allowed_);
365 global_gc_prologue_callback_();
366 }
367
368 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000369 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000371 int old_gen_size = PromotedSpaceSize();
372 old_gen_promotion_limit_ =
373 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
374 old_gen_allocation_limit_ =
375 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000376 old_gen_exhausted_ = false;
377
378 // If we have used the mark-compact collector to collect the new
379 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000380 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000381 // case where (1) a new space collection was requested, (2) the
382 // collector selection policy selected the mark-compact collector,
383 // and (3) the mark-compact collector policy selected not to
384 // compact the new space. In that case, there is no more (usable)
385 // free space in the new space after the collection compared to
386 // before.
387 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
388 Scavenge();
389 }
390 } else {
391 Scavenge();
392 }
393 Counters::objs_since_last_young.Set(0);
394
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000395 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396
kasper.lund7276f142008-07-30 08:49:36 +0000397 if (collector == MARK_COMPACTOR) {
398 // Register the amount of external allocated memory.
399 amount_of_external_allocated_memory_at_last_global_gc_ =
400 amount_of_external_allocated_memory_;
401 }
402
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000403 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
404 ASSERT(!allocation_allowed_);
405 global_gc_epilogue_callback_();
406 }
407}
408
409
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000410void Heap::PostGarbageCollectionProcessing() {
411 // Process weak handles post gc.
412 GlobalHandles::PostGarbageCollectionProcessing();
413 // Update flat string readers.
414 FlatStringReader::PostGarbageCollectionProcessing();
415}
416
417
kasper.lund7276f142008-07-30 08:49:36 +0000418void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000421 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000422 LOG(ResourceEvent("markcompact", "begin"));
423
424 MarkCompactPrologue();
425
kasper.lund7276f142008-07-30 08:49:36 +0000426 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427
428 MarkCompactEpilogue();
429
430 LOG(ResourceEvent("markcompact", "end"));
431
432 gc_state_ = NOT_IN_GC;
433
434 Shrink();
435
436 Counters::objs_since_last_full.Set(0);
437}
438
439
440void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000441 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000442 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443 RegExpImpl::OldSpaceCollectionPrologue();
444 Top::MarkCompactPrologue();
445 ThreadManager::MarkCompactPrologue();
446}
447
448
449void Heap::MarkCompactEpilogue() {
450 Top::MarkCompactEpilogue();
451 ThreadManager::MarkCompactEpilogue();
452}
453
454
455Object* Heap::FindCodeObject(Address a) {
456 Object* obj = code_space_->FindObject(a);
457 if (obj->IsFailure()) {
458 obj = lo_space_->FindObject(a);
459 }
kasper.lund7276f142008-07-30 08:49:36 +0000460 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461 return obj;
462}
463
464
465// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000466class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000467 public:
468
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000469 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470
471 void VisitPointers(Object** start, Object** end) {
472 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000473 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474 }
475
476 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000477 void ScavengePointer(Object** p) {
478 Object* object = *p;
479 if (!Heap::InNewSpace(object)) return;
480 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
481 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482 }
483};
484
485
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000486// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487static Address promoted_top = NULL;
488
489
490#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000491// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000493class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000494 public:
495 void VisitPointers(Object** start, Object**end) {
496 for (Object** current = start; current < end; current++) {
497 if ((*current)->IsHeapObject()) {
498 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
499 }
500 }
501 }
502};
503#endif
504
505void Heap::Scavenge() {
506#ifdef DEBUG
507 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000508 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000509 HeapObjectIterator it(code_space_);
510 while (it.has_next()) {
511 HeapObject* object = it.next();
512 if (object->IsCode()) {
513 Code::cast(object)->ConvertICTargetsFromAddressToObject();
514 }
515 object->Iterate(&v);
516 if (object->IsCode()) {
517 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
518 }
519 }
520 }
521#endif
522
523 gc_state_ = SCAVENGE;
524
525 // Implements Cheney's copying algorithm
526 LOG(ResourceEvent("scavenge", "begin"));
527
528 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000529 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000530 scavenge_count_ > new_space_growth_limit_) {
531 // Double the size of the new space, and double the limit. The next
532 // doubling attempt will occur after the current new_space_growth_limit_
533 // more collections.
534 // TODO(1240712): NewSpace::Double has a return value which is
535 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000536 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000537 new_space_growth_limit_ *= 2;
538 }
539
540 // Flip the semispaces. After flipping, to space is empty, from space has
541 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000542 new_space_.Flip();
543 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544
545 // We need to sweep newly copied objects which can be in either the to space
546 // or the old space. For to space objects, we use a mark. Newly copied
547 // objects lie between the mark and the allocation top. For objects
548 // promoted to old space, we write their addresses downward from the top of
549 // the new space. Sweeping newly promoted objects requires an allocation
550 // pointer and a mark. Note that the allocation pointer 'top' actually
551 // moves downward from the high address in the to space.
552 //
553 // There is guaranteed to be enough room at the top of the to space for the
554 // addresses of promoted objects: every object promoted frees up its size in
555 // bytes from the top of the new space, and objects are at least one pointer
556 // in size. Using the new space to record promoted addresses makes the
557 // scavenge collector agnostic to the allocation strategy (eg, linear or
558 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000559 Address new_mark = new_space_.ToSpaceLow();
560 Address promoted_mark = new_space_.ToSpaceHigh();
561 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000563 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000565 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566
567 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000568 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000569 IterateRSet(old_pointer_space_, &ScavengePointer);
570 IterateRSet(map_space_, &ScavengePointer);
571 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572
573 bool has_processed_weak_pointers = false;
574
575 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000576 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000577 ASSERT(promoted_mark >= promoted_top);
578
579 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000580 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581 // Sweep newly copied objects in the to space. The allocation pointer
582 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000583 Address previous_top = new_space_.top();
584 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000586 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587 }
588 new_mark = previous_top;
589
590 // Sweep newly copied objects in the old space. The promotion 'top'
591 // pointer could change during sweeping.
592 previous_top = promoted_top;
593 for (Address current = promoted_mark - kPointerSize;
594 current >= previous_top;
595 current -= kPointerSize) {
596 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000597 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598 UpdateRSet(object);
599 }
600 promoted_mark = previous_top;
601 }
602
603 if (has_processed_weak_pointers) break; // We are done.
604 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000605 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 has_processed_weak_pointers = true;
607 }
608
609 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000610 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611
612 LOG(ResourceEvent("scavenge", "end"));
613
614 gc_state_ = NOT_IN_GC;
615}
616
617
618void Heap::ClearRSetRange(Address start, int size_in_bytes) {
619 uint32_t start_bit;
620 Address start_word_address =
621 Page::ComputeRSetBitPosition(start, 0, &start_bit);
622 uint32_t end_bit;
623 Address end_word_address =
624 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
625 0,
626 &end_bit);
627
628 // We want to clear the bits in the starting word starting with the
629 // first bit, and in the ending word up to and including the last
630 // bit. Build a pair of bitmasks to do that.
631 uint32_t start_bitmask = start_bit - 1;
632 uint32_t end_bitmask = ~((end_bit << 1) - 1);
633
634 // If the start address and end address are the same, we mask that
635 // word once, otherwise mask the starting and ending word
636 // separately and all the ones in between.
637 if (start_word_address == end_word_address) {
638 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
639 } else {
640 Memory::uint32_at(start_word_address) &= start_bitmask;
641 Memory::uint32_at(end_word_address) &= end_bitmask;
642 start_word_address += kIntSize;
643 memset(start_word_address, 0, end_word_address - start_word_address);
644 }
645}
646
647
648class UpdateRSetVisitor: public ObjectVisitor {
649 public:
650
651 void VisitPointer(Object** p) {
652 UpdateRSet(p);
653 }
654
655 void VisitPointers(Object** start, Object** end) {
656 // Update a store into slots [start, end), used (a) to update remembered
657 // set when promoting a young object to old space or (b) to rebuild
658 // remembered sets after a mark-compact collection.
659 for (Object** p = start; p < end; p++) UpdateRSet(p);
660 }
661 private:
662
663 void UpdateRSet(Object** p) {
664 // The remembered set should not be set. It should be clear for objects
665 // newly copied to old space, and it is cleared before rebuilding in the
666 // mark-compact collector.
667 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
668 if (Heap::InNewSpace(*p)) {
669 Page::SetRSet(reinterpret_cast<Address>(p), 0);
670 }
671 }
672};
673
674
675int Heap::UpdateRSet(HeapObject* obj) {
676 ASSERT(!InNewSpace(obj));
677 // Special handling of fixed arrays to iterate the body based on the start
678 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
679 // will not work because Page::SetRSet needs to have the start of the
680 // object.
681 if (obj->IsFixedArray()) {
682 FixedArray* array = FixedArray::cast(obj);
683 int length = array->length();
684 for (int i = 0; i < length; i++) {
685 int offset = FixedArray::kHeaderSize + i * kPointerSize;
686 ASSERT(!Page::IsRSetSet(obj->address(), offset));
687 if (Heap::InNewSpace(array->get(i))) {
688 Page::SetRSet(obj->address(), offset);
689 }
690 }
691 } else if (!obj->IsCode()) {
692 // Skip code object, we know it does not contain inter-generational
693 // pointers.
694 UpdateRSetVisitor v;
695 obj->Iterate(&v);
696 }
697 return obj->Size();
698}
699
700
701void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000702 // By definition, we do not care about remembered set bits in code or data
703 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704 map_space_->ClearRSet();
705 RebuildRSets(map_space_);
706
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000707 old_pointer_space_->ClearRSet();
708 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709
710 Heap::lo_space_->ClearRSet();
711 RebuildRSets(lo_space_);
712}
713
714
715void Heap::RebuildRSets(PagedSpace* space) {
716 HeapObjectIterator it(space);
717 while (it.has_next()) Heap::UpdateRSet(it.next());
718}
719
720
721void Heap::RebuildRSets(LargeObjectSpace* space) {
722 LargeObjectIterator it(space);
723 while (it.has_next()) Heap::UpdateRSet(it.next());
724}
725
726
727#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
728void Heap::RecordCopiedObject(HeapObject* obj) {
729 bool should_record = false;
730#ifdef DEBUG
731 should_record = FLAG_heap_stats;
732#endif
733#ifdef ENABLE_LOGGING_AND_PROFILING
734 should_record = should_record || FLAG_log_gc;
735#endif
736 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000737 if (new_space_.Contains(obj)) {
738 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000740 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000741 }
742 }
743}
744#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
745
746
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000747
748HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000749 HeapObject* target,
750 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000751 // Copy the content of source to target.
752 CopyBlock(reinterpret_cast<Object**>(target->address()),
753 reinterpret_cast<Object**>(source->address()),
754 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000755
kasper.lund7276f142008-07-30 08:49:36 +0000756 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000757 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758
759 // Update NewSpace stats if necessary.
760#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
761 RecordCopiedObject(target);
762#endif
763
764 return target;
765}
766
767
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000768// Inlined function.
769void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
770 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000771
kasper.lund7276f142008-07-30 08:49:36 +0000772 // We use the first word (where the map pointer usually is) of a heap
773 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000774 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000776 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000777
kasper.lund7276f142008-07-30 08:49:36 +0000778 // If the first word is a forwarding address, the object has already been
779 // copied.
780 if (first_word.IsForwardingAddress()) {
781 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782 return;
783 }
784
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000785 // Call the slow part of scavenge object.
786 return ScavengeObjectSlow(p, object);
787}
788
ager@chromium.org870a0b62008-11-04 11:43:05 +0000789
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000790static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000791 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000792 // is a candidate for being shortcut by the scavenger.
793 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000794 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
ager@chromium.orgc3e50d82008-11-05 11:53:10 +0000795 return (StringShape(map).representation_tag() == kConsStringTag) &&
ager@chromium.org870a0b62008-11-04 11:43:05 +0000796 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000797}
798
799
800void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
801 ASSERT(InFromSpace(object));
802 MapWord first_word = object->map_word();
803 ASSERT(!first_word.IsForwardingAddress());
804
805 // Optimization: Bypass flattened ConsString objects.
806 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000807 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808 *p = object;
809 // After patching *p we have to repeat the checks that object is in the
810 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000811 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000812 first_word = object->map_word();
813 if (first_word.IsForwardingAddress()) {
814 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000815 return;
816 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 }
818
kasper.lund7276f142008-07-30 08:49:36 +0000819 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820 // If the object should be promoted, we try to copy it to old space.
821 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000822 OldSpace* target_space = Heap::TargetSpace(object);
823 ASSERT(target_space == Heap::old_pointer_space_ ||
824 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000825 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000827 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000828 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000829 // Record the object's address at the top of the to space, to allow
830 // it to be swept by the scavenger.
831 promoted_top -= kPointerSize;
832 Memory::Object_at(promoted_top) = *p;
833 } else {
834#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000835 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000837 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838 (*p)->Iterate(&v);
839#endif
840 }
841 return;
842 }
843 }
844
845 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000846 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847 // Failed allocation at this point is utterly unexpected.
848 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000849 *p = MigrateObject(object, HeapObject::cast(result), object_size);
850}
851
852
853void Heap::ScavengePointer(HeapObject** p) {
854 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000855}
856
857
858Object* Heap::AllocatePartialMap(InstanceType instance_type,
859 int instance_size) {
860 Object* result = AllocateRawMap(Map::kSize);
861 if (result->IsFailure()) return result;
862
863 // Map::cast cannot be used due to uninitialized map field.
864 reinterpret_cast<Map*>(result)->set_map(meta_map());
865 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
866 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000867 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
869 return result;
870}
871
872
873Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
874 Object* result = AllocateRawMap(Map::kSize);
875 if (result->IsFailure()) return result;
876
877 Map* map = reinterpret_cast<Map*>(result);
878 map->set_map(meta_map());
879 map->set_instance_type(instance_type);
880 map->set_prototype(null_value());
881 map->set_constructor(null_value());
882 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000883 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000884 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000885 map->set_code_cache(empty_fixed_array());
886 map->set_unused_property_fields(0);
887 map->set_bit_field(0);
888 return map;
889}
890
891
892bool Heap::CreateInitialMaps() {
893 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
894 if (obj->IsFailure()) return false;
895
896 // Map::cast cannot be used due to uninitialized map field.
897 meta_map_ = reinterpret_cast<Map*>(obj);
898 meta_map()->set_map(meta_map());
899
900 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
901 if (obj->IsFailure()) return false;
902 fixed_array_map_ = Map::cast(obj);
903
904 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
905 if (obj->IsFailure()) return false;
906 oddball_map_ = Map::cast(obj);
907
908 // Allocate the empty array
909 obj = AllocateEmptyFixedArray();
910 if (obj->IsFailure()) return false;
911 empty_fixed_array_ = FixedArray::cast(obj);
912
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000913 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914 if (obj->IsFailure()) return false;
915 null_value_ = obj;
916
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000917 // Allocate the empty descriptor array. AllocateMap can now be used.
918 obj = AllocateEmptyFixedArray();
919 if (obj->IsFailure()) return false;
920 // There is a check against empty_descriptor_array() in cast().
921 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000922
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000923 // Fix the instance_descriptors for the existing maps.
924 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 meta_map()->set_code_cache(empty_fixed_array());
926
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000927 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000928 fixed_array_map()->set_code_cache(empty_fixed_array());
929
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000930 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 oddball_map()->set_code_cache(empty_fixed_array());
932
933 // Fix prototype object for existing maps.
934 meta_map()->set_prototype(null_value());
935 meta_map()->set_constructor(null_value());
936
937 fixed_array_map()->set_prototype(null_value());
938 fixed_array_map()->set_constructor(null_value());
939 oddball_map()->set_prototype(null_value());
940 oddball_map()->set_constructor(null_value());
941
942 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
943 if (obj->IsFailure()) return false;
944 heap_number_map_ = Map::cast(obj);
945
946 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
947 if (obj->IsFailure()) return false;
948 proxy_map_ = Map::cast(obj);
949
950#define ALLOCATE_STRING_MAP(type, size, name) \
951 obj = AllocateMap(type, size); \
952 if (obj->IsFailure()) return false; \
953 name##_map_ = Map::cast(obj);
954 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
955#undef ALLOCATE_STRING_MAP
956
ager@chromium.org7c537e22008-10-16 08:43:32 +0000957 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958 if (obj->IsFailure()) return false;
959 undetectable_short_string_map_ = Map::cast(obj);
960 undetectable_short_string_map_->set_is_undetectable();
961
ager@chromium.org7c537e22008-10-16 08:43:32 +0000962 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963 if (obj->IsFailure()) return false;
964 undetectable_medium_string_map_ = Map::cast(obj);
965 undetectable_medium_string_map_->set_is_undetectable();
966
ager@chromium.org7c537e22008-10-16 08:43:32 +0000967 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000968 if (obj->IsFailure()) return false;
969 undetectable_long_string_map_ = Map::cast(obj);
970 undetectable_long_string_map_->set_is_undetectable();
971
ager@chromium.org7c537e22008-10-16 08:43:32 +0000972 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000973 if (obj->IsFailure()) return false;
974 undetectable_short_ascii_string_map_ = Map::cast(obj);
975 undetectable_short_ascii_string_map_->set_is_undetectable();
976
ager@chromium.org7c537e22008-10-16 08:43:32 +0000977 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000978 if (obj->IsFailure()) return false;
979 undetectable_medium_ascii_string_map_ = Map::cast(obj);
980 undetectable_medium_ascii_string_map_->set_is_undetectable();
981
ager@chromium.org7c537e22008-10-16 08:43:32 +0000982 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983 if (obj->IsFailure()) return false;
984 undetectable_long_ascii_string_map_ = Map::cast(obj);
985 undetectable_long_ascii_string_map_->set_is_undetectable();
986
987 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
988 if (obj->IsFailure()) return false;
989 byte_array_map_ = Map::cast(obj);
990
991 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
992 if (obj->IsFailure()) return false;
993 code_map_ = Map::cast(obj);
994
995 obj = AllocateMap(FILLER_TYPE, kPointerSize);
996 if (obj->IsFailure()) return false;
997 one_word_filler_map_ = Map::cast(obj);
998
999 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1000 if (obj->IsFailure()) return false;
1001 two_word_filler_map_ = Map::cast(obj);
1002
1003#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1004 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1005 if (obj->IsFailure()) return false; \
1006 name##_map_ = Map::cast(obj);
1007 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1008#undef ALLOCATE_STRUCT_MAP
1009
ager@chromium.org236ad962008-09-25 09:45:57 +00001010 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001011 if (obj->IsFailure()) return false;
1012 hash_table_map_ = Map::cast(obj);
1013
ager@chromium.org236ad962008-09-25 09:45:57 +00001014 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001015 if (obj->IsFailure()) return false;
1016 context_map_ = Map::cast(obj);
1017
ager@chromium.org236ad962008-09-25 09:45:57 +00001018 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001019 if (obj->IsFailure()) return false;
1020 global_context_map_ = Map::cast(obj);
1021
1022 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1023 if (obj->IsFailure()) return false;
1024 boilerplate_function_map_ = Map::cast(obj);
1025
1026 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1027 if (obj->IsFailure()) return false;
1028 shared_function_info_map_ = Map::cast(obj);
1029
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001030 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001031 return true;
1032}
1033
1034
1035Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1036 // Statically ensure that it is safe to allocate heap numbers in paged
1037 // spaces.
1038 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001039 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001040 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001041 if (result->IsFailure()) return result;
1042
1043 HeapObject::cast(result)->set_map(heap_number_map());
1044 HeapNumber::cast(result)->set_value(value);
1045 return result;
1046}
1047
1048
1049Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001050 // Use general version, if we're forced to always allocate.
1051 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001052 // This version of AllocateHeapNumber is optimized for
1053 // allocation in new space.
1054 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1055 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001056 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001057 if (result->IsFailure()) return result;
1058 HeapObject::cast(result)->set_map(heap_number_map());
1059 HeapNumber::cast(result)->set_value(value);
1060 return result;
1061}
1062
1063
1064Object* Heap::CreateOddball(Map* map,
1065 const char* to_string,
1066 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001067 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001068 if (result->IsFailure()) return result;
1069 return Oddball::cast(result)->Initialize(to_string, to_number);
1070}
1071
1072
1073bool Heap::CreateApiObjects() {
1074 Object* obj;
1075
1076 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1077 if (obj->IsFailure()) return false;
1078 neander_map_ = Map::cast(obj);
1079
1080 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1081 if (obj->IsFailure()) return false;
1082 Object* elements = AllocateFixedArray(2);
1083 if (elements->IsFailure()) return false;
1084 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1085 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1086 message_listeners_ = JSObject::cast(obj);
1087
1088 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1089 if (obj->IsFailure()) return false;
1090 elements = AllocateFixedArray(2);
1091 if (elements->IsFailure()) return false;
1092 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1093 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1094 debug_event_listeners_ = JSObject::cast(obj);
1095
1096 return true;
1097}
1098
1099void Heap::CreateFixedStubs() {
1100 // Here we create roots for fixed stubs. They are needed at GC
1101 // for cooking and uncooking (check out frames.cc).
1102 // The eliminates the need for doing dictionary lookup in the
1103 // stub cache for these stubs.
1104 HandleScope scope;
1105 {
1106 CEntryStub stub;
1107 c_entry_code_ = *stub.GetCode();
1108 }
1109 {
1110 CEntryDebugBreakStub stub;
1111 c_entry_debug_break_code_ = *stub.GetCode();
1112 }
1113 {
1114 JSEntryStub stub;
1115 js_entry_code_ = *stub.GetCode();
1116 }
1117 {
1118 JSConstructEntryStub stub;
1119 js_construct_entry_code_ = *stub.GetCode();
1120 }
1121}
1122
1123
1124bool Heap::CreateInitialObjects() {
1125 Object* obj;
1126
1127 // The -0 value must be set before NumberFromDouble works.
1128 obj = AllocateHeapNumber(-0.0, TENURED);
1129 if (obj->IsFailure()) return false;
1130 minus_zero_value_ = obj;
1131 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1132
1133 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1134 if (obj->IsFailure()) return false;
1135 nan_value_ = obj;
1136
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001137 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001138 if (obj->IsFailure()) return false;
1139 undefined_value_ = obj;
1140 ASSERT(!InNewSpace(undefined_value()));
1141
1142 // Allocate initial symbol table.
1143 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1144 if (obj->IsFailure()) return false;
1145 symbol_table_ = obj;
1146
1147 // Assign the print strings for oddballs after creating symboltable.
1148 Object* symbol = LookupAsciiSymbol("undefined");
1149 if (symbol->IsFailure()) return false;
1150 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1151 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1152
1153 // Assign the print strings for oddballs after creating symboltable.
1154 symbol = LookupAsciiSymbol("null");
1155 if (symbol->IsFailure()) return false;
1156 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1157 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1158
1159 // Allocate the null_value
1160 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1161 if (obj->IsFailure()) return false;
1162
1163 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1164 if (obj->IsFailure()) return false;
1165 true_value_ = obj;
1166
1167 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1168 if (obj->IsFailure()) return false;
1169 false_value_ = obj;
1170
1171 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1172 if (obj->IsFailure()) return false;
1173 the_hole_value_ = obj;
1174
1175 // Allocate the empty string.
1176 obj = AllocateRawAsciiString(0, TENURED);
1177 if (obj->IsFailure()) return false;
1178 empty_string_ = String::cast(obj);
1179
1180#define SYMBOL_INITIALIZE(name, string) \
1181 obj = LookupAsciiSymbol(string); \
1182 if (obj->IsFailure()) return false; \
1183 (name##_) = String::cast(obj);
1184 SYMBOL_LIST(SYMBOL_INITIALIZE)
1185#undef SYMBOL_INITIALIZE
1186
1187 // Allocate the proxy for __proto__.
1188 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1189 if (obj->IsFailure()) return false;
1190 prototype_accessors_ = Proxy::cast(obj);
1191
1192 // Allocate the code_stubs dictionary.
1193 obj = Dictionary::Allocate(4);
1194 if (obj->IsFailure()) return false;
1195 code_stubs_ = Dictionary::cast(obj);
1196
1197 // Allocate the non_monomorphic_cache used in stub-cache.cc
1198 obj = Dictionary::Allocate(4);
1199 if (obj->IsFailure()) return false;
1200 non_monomorphic_cache_ = Dictionary::cast(obj);
1201
1202 CreateFixedStubs();
1203
1204 // Allocate the number->string conversion cache
1205 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1206 if (obj->IsFailure()) return false;
1207 number_string_cache_ = FixedArray::cast(obj);
1208
1209 // Allocate cache for single character strings.
1210 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1211 if (obj->IsFailure()) return false;
1212 single_character_string_cache_ = FixedArray::cast(obj);
1213
1214 // Allocate cache for external strings pointing to native source code.
1215 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1216 if (obj->IsFailure()) return false;
1217 natives_source_cache_ = FixedArray::cast(obj);
1218
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001219 // Initialize keyed lookup cache.
1220 ClearKeyedLookupCache();
1221
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001222 // Initialize compilation cache.
1223 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001224
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001225 return true;
1226}
1227
1228
1229static inline int double_get_hash(double d) {
1230 DoubleRepresentation rep(d);
1231 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1232 (Heap::kNumberStringCacheSize - 1));
1233}
1234
1235
1236static inline int smi_get_hash(Smi* smi) {
1237 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1238}
1239
1240
1241
1242Object* Heap::GetNumberStringCache(Object* number) {
1243 int hash;
1244 if (number->IsSmi()) {
1245 hash = smi_get_hash(Smi::cast(number));
1246 } else {
1247 hash = double_get_hash(number->Number());
1248 }
1249 Object* key = number_string_cache_->get(hash * 2);
1250 if (key == number) {
1251 return String::cast(number_string_cache_->get(hash * 2 + 1));
1252 } else if (key->IsHeapNumber() &&
1253 number->IsHeapNumber() &&
1254 key->Number() == number->Number()) {
1255 return String::cast(number_string_cache_->get(hash * 2 + 1));
1256 }
1257 return undefined_value();
1258}
1259
1260
1261void Heap::SetNumberStringCache(Object* number, String* string) {
1262 int hash;
1263 if (number->IsSmi()) {
1264 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001265 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001266 } else {
1267 hash = double_get_hash(number->Number());
1268 number_string_cache_->set(hash * 2, number);
1269 }
1270 number_string_cache_->set(hash * 2 + 1, string);
1271}
1272
1273
1274Object* Heap::SmiOrNumberFromDouble(double value,
1275 bool new_object,
1276 PretenureFlag pretenure) {
1277 // We need to distinguish the minus zero value and this cannot be
1278 // done after conversion to int. Doing this by comparing bit
1279 // patterns is faster than using fpclassify() et al.
1280 static const DoubleRepresentation plus_zero(0.0);
1281 static const DoubleRepresentation minus_zero(-0.0);
1282 static const DoubleRepresentation nan(OS::nan_value());
1283 ASSERT(minus_zero_value_ != NULL);
1284 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1285
1286 DoubleRepresentation rep(value);
1287 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1288 if (rep.bits == minus_zero.bits) {
1289 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1290 : minus_zero_value_;
1291 }
1292 if (rep.bits == nan.bits) {
1293 return new_object
1294 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1295 : nan_value_;
1296 }
1297
1298 // Try to represent the value as a tagged small integer.
1299 int int_value = FastD2I(value);
1300 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1301 return Smi::FromInt(int_value);
1302 }
1303
1304 // Materialize the value in the heap.
1305 return AllocateHeapNumber(value, pretenure);
1306}
1307
1308
1309Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1310 return SmiOrNumberFromDouble(value,
1311 true /* number object must be new */,
1312 pretenure);
1313}
1314
1315
1316Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1317 return SmiOrNumberFromDouble(value,
1318 false /* use preallocated NaN, -0.0 */,
1319 pretenure);
1320}
1321
1322
1323Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1324 // Statically ensure that it is safe to allocate proxies in paged spaces.
1325 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001326 AllocationSpace space =
1327 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001328 Object* result = Allocate(proxy_map(), space);
1329 if (result->IsFailure()) return result;
1330
1331 Proxy::cast(result)->set_proxy(proxy);
1332 return result;
1333}
1334
1335
1336Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1337 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1338 if (result->IsFailure()) return result;
1339
1340 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1341 share->set_name(name);
1342 Code* illegal = Builtins::builtin(Builtins::Illegal);
1343 share->set_code(illegal);
1344 share->set_expected_nof_properties(0);
1345 share->set_length(0);
1346 share->set_formal_parameter_count(0);
1347 share->set_instance_class_name(Object_symbol());
1348 share->set_function_data(undefined_value());
1349 share->set_lazy_load_data(undefined_value());
1350 share->set_script(undefined_value());
1351 share->set_start_position_and_type(0);
1352 share->set_debug_info(undefined_value());
1353 return result;
1354}
1355
1356
ager@chromium.org870a0b62008-11-04 11:43:05 +00001357Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001358 String* second) {
1359 StringShape first_shape(first);
1360 StringShape second_shape(second);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001361 int first_length = first->length(first_shape);
1362 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001363 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001364 bool is_ascii = first_shape.IsAsciiRepresentation()
1365 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001366
1367 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001368 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001369 ASSERT(first->IsFlat(first_shape));
1370 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001371 if (is_ascii) {
1372 Object* result = AllocateRawAsciiString(length);
1373 if (result->IsFailure()) return result;
1374 // Copy the characters into the new object.
1375 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001376 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1377 String::WriteToFlat(second,
1378 second_shape,
1379 dest + first_length,
1380 0,
1381 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001382 return result;
1383 } else {
1384 Object* result = AllocateRawTwoByteString(length);
1385 if (result->IsFailure()) return result;
1386 // Copy the characters into the new object.
1387 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001388 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1389 String::WriteToFlat(second,
1390 second_shape,
1391 dest + first_length,
1392 0,
1393 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001394 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001395 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396 }
1397
1398 Map* map;
1399 if (length <= String::kMaxShortStringSize) {
1400 map = is_ascii ? short_cons_ascii_string_map()
1401 : short_cons_string_map();
1402 } else if (length <= String::kMaxMediumStringSize) {
1403 map = is_ascii ? medium_cons_ascii_string_map()
1404 : medium_cons_string_map();
1405 } else {
1406 map = is_ascii ? long_cons_ascii_string_map()
1407 : long_cons_string_map();
1408 }
1409
1410 Object* result = Allocate(map, NEW_SPACE);
1411 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001412 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001413 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001414 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1415 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001416 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 return result;
1418}
1419
1420
ager@chromium.org870a0b62008-11-04 11:43:05 +00001421Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001422 int start,
1423 int end) {
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001424 StringShape buffer_shape(buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001425 int length = end - start;
1426
1427 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001428 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001429 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001430 }
1431
1432 Map* map;
1433 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001434 map = buffer_shape.IsAsciiRepresentation() ?
1435 short_sliced_ascii_string_map() :
1436 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001437 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001438 map = buffer_shape.IsAsciiRepresentation() ?
1439 medium_sliced_ascii_string_map() :
1440 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001442 map = buffer_shape.IsAsciiRepresentation() ?
1443 long_sliced_ascii_string_map() :
1444 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001445 }
1446
1447 Object* result = Allocate(map, NEW_SPACE);
1448 if (result->IsFailure()) return result;
1449
1450 SlicedString* sliced_string = SlicedString::cast(result);
1451 sliced_string->set_buffer(buffer);
1452 sliced_string->set_start(start);
1453 sliced_string->set_length(length);
1454
1455 return result;
1456}
1457
1458
ager@chromium.org870a0b62008-11-04 11:43:05 +00001459Object* Heap::AllocateSubString(String* buffer,
1460 StringShape buffer_shape,
1461 int start,
1462 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463 int length = end - start;
1464
ager@chromium.org7c537e22008-10-16 08:43:32 +00001465 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001466 return Heap::LookupSingleCharacterStringFromCode(
1467 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001468 }
1469
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001470 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001471 if (!buffer->IsFlat(buffer_shape)) {
1472 buffer->TryFlatten(buffer_shape);
1473 buffer_shape = StringShape(buffer);
1474 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475
ager@chromium.org870a0b62008-11-04 11:43:05 +00001476 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001477 ? AllocateRawAsciiString(length)
1478 : AllocateRawTwoByteString(length);
1479 if (result->IsFailure()) return result;
1480
1481 // Copy the characters into the new object.
1482 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001483 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001484 StringHasher hasher(length);
1485 int i = 0;
1486 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001487 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001488 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001489 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001490 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001491 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001492 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001493 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001494 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001495 }
1496 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001497 return result;
1498}
1499
1500
1501Object* Heap::AllocateExternalStringFromAscii(
1502 ExternalAsciiString::Resource* resource) {
1503 Map* map;
1504 int length = resource->length();
1505 if (length <= String::kMaxShortStringSize) {
1506 map = short_external_ascii_string_map();
1507 } else if (length <= String::kMaxMediumStringSize) {
1508 map = medium_external_ascii_string_map();
1509 } else {
1510 map = long_external_ascii_string_map();
1511 }
1512
1513 Object* result = Allocate(map, NEW_SPACE);
1514 if (result->IsFailure()) return result;
1515
1516 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1517 external_string->set_length(length);
1518 external_string->set_resource(resource);
1519
1520 return result;
1521}
1522
1523
1524Object* Heap::AllocateExternalStringFromTwoByte(
1525 ExternalTwoByteString::Resource* resource) {
1526 Map* map;
1527 int length = resource->length();
1528 if (length <= String::kMaxShortStringSize) {
1529 map = short_external_string_map();
1530 } else if (length <= String::kMaxMediumStringSize) {
1531 map = medium_external_string_map();
1532 } else {
1533 map = long_external_string_map();
1534 }
1535
1536 Object* result = Allocate(map, NEW_SPACE);
1537 if (result->IsFailure()) return result;
1538
1539 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1540 external_string->set_length(length);
1541 external_string->set_resource(resource);
1542
1543 return result;
1544}
1545
1546
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001547Object* Heap::AllocateExternalSymbolFromTwoByte(
1548 ExternalTwoByteString::Resource* resource) {
1549 Map* map;
1550 int length = resource->length();
1551 if (length <= String::kMaxShortStringSize) {
1552 map = short_external_symbol_map();
1553 } else if (length <= String::kMaxMediumStringSize) {
1554 map = medium_external_symbol_map();
1555 } else {
1556 map = long_external_symbol_map();
1557 }
1558
1559 Object* result = Allocate(map, OLD_DATA_SPACE);
1560 if (result->IsFailure()) return result;
1561
1562 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1563 external_string->set_length(length);
1564 external_string->set_resource(resource);
1565
1566 return result;
1567}
1568
1569
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001570Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001571 if (code <= String::kMaxAsciiCharCode) {
1572 Object* value = Heap::single_character_string_cache()->get(code);
1573 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001574
1575 char buffer[1];
1576 buffer[0] = static_cast<char>(code);
1577 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1578
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001580 Heap::single_character_string_cache()->set(code, result);
1581 return result;
1582 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001583
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 Object* result = Heap::AllocateRawTwoByteString(1);
1585 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001586 String* answer = String::cast(result);
1587 answer->Set(StringShape(answer), 0, code);
1588 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001589}
1590
1591
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001592Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1593 if (pretenure == NOT_TENURED) {
1594 return AllocateByteArray(length);
1595 }
1596 int size = ByteArray::SizeFor(length);
1597 AllocationSpace space =
1598 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1599
1600 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1601
1602 if (result->IsFailure()) return result;
1603
1604 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1605 reinterpret_cast<Array*>(result)->set_length(length);
1606 return result;
1607}
1608
1609
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001610Object* Heap::AllocateByteArray(int length) {
1611 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001612 AllocationSpace space =
1613 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001615 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001616
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001617 if (result->IsFailure()) return result;
1618
1619 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1620 reinterpret_cast<Array*>(result)->set_length(length);
1621 return result;
1622}
1623
1624
1625Object* Heap::CreateCode(const CodeDesc& desc,
1626 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001627 Code::Flags flags,
1628 Code** self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629 // Compute size
1630 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1631 int sinfo_size = 0;
1632 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1633 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001634 Object* result;
1635 if (obj_size > MaxHeapObjectSize()) {
1636 result = lo_space_->AllocateRawCode(obj_size);
1637 } else {
1638 result = code_space_->AllocateRaw(obj_size);
1639 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001640
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001641 if (result->IsFailure()) return result;
1642
1643 // Initialize the object
1644 HeapObject::cast(result)->set_map(code_map());
1645 Code* code = Code::cast(result);
1646 code->set_instruction_size(desc.instr_size);
1647 code->set_relocation_size(desc.reloc_size);
1648 code->set_sinfo_size(sinfo_size);
1649 code->set_flags(flags);
1650 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001651 // Allow self references to created code object.
1652 if (self_reference != NULL) {
1653 *self_reference = code;
1654 }
1655 // Migrate generated code.
1656 // The generated code can contain Object** values (typically from handles)
1657 // that are dereferenced during the copy to point directly to the actual heap
1658 // objects. These pointers can include references to the code object itself,
1659 // through the self_reference parameter.
1660 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001661 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1662
1663#ifdef DEBUG
1664 code->Verify();
1665#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001666 return code;
1667}
1668
1669
1670Object* Heap::CopyCode(Code* code) {
1671 // Allocate an object the same size as the code object.
1672 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001673 Object* result;
1674 if (obj_size > MaxHeapObjectSize()) {
1675 result = lo_space_->AllocateRawCode(obj_size);
1676 } else {
1677 result = code_space_->AllocateRaw(obj_size);
1678 }
1679
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001680 if (result->IsFailure()) return result;
1681
1682 // Copy code object.
1683 Address old_addr = code->address();
1684 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001685 CopyBlock(reinterpret_cast<Object**>(new_addr),
1686 reinterpret_cast<Object**>(old_addr),
1687 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001688 // Relocate the copy.
1689 Code* new_code = Code::cast(result);
1690 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001691 return new_code;
1692}
1693
1694
1695Object* Heap::Allocate(Map* map, AllocationSpace space) {
1696 ASSERT(gc_state_ == NOT_IN_GC);
1697 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001698 Object* result = AllocateRaw(map->instance_size(),
1699 space,
1700 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001701 if (result->IsFailure()) return result;
1702 HeapObject::cast(result)->set_map(map);
1703 return result;
1704}
1705
1706
1707Object* Heap::InitializeFunction(JSFunction* function,
1708 SharedFunctionInfo* shared,
1709 Object* prototype) {
1710 ASSERT(!prototype->IsMap());
1711 function->initialize_properties();
1712 function->initialize_elements();
1713 function->set_shared(shared);
1714 function->set_prototype_or_initial_map(prototype);
1715 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001716 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001717 return function;
1718}
1719
1720
1721Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1722 // Allocate the prototype.
1723 Object* prototype =
1724 AllocateJSObject(Top::context()->global_context()->object_function());
1725 if (prototype->IsFailure()) return prototype;
1726 // When creating the prototype for the function we must set its
1727 // constructor to the function.
1728 Object* result =
1729 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1730 function,
1731 DONT_ENUM);
1732 if (result->IsFailure()) return result;
1733 return prototype;
1734}
1735
1736
1737Object* Heap::AllocateFunction(Map* function_map,
1738 SharedFunctionInfo* shared,
1739 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001740 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001741 if (result->IsFailure()) return result;
1742 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1743}
1744
1745
1746Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001747 // To get fast allocation and map sharing for arguments objects we
1748 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001749
1750 // This calls Copy directly rather than using Heap::AllocateRaw so we
1751 // duplicate the check here.
1752 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1753
1754 JSObject* boilerplate =
1755 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001756
1757 // Make the clone.
1758 Map* map = boilerplate->map();
1759 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001760 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001761 if (result->IsFailure()) return result;
1762
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001763 // Copy the content. The arguments boilerplate doesn't have any
1764 // fields that point to new space so it's safe to skip the write
1765 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001766 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1767 reinterpret_cast<Object**>(boilerplate->address()),
1768 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001769
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001770 // Set the two properties.
1771 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001772 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001773 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1774 Smi::FromInt(length),
1775 SKIP_WRITE_BARRIER);
1776
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777 // Check the state of the object
1778 ASSERT(JSObject::cast(result)->HasFastProperties());
1779 ASSERT(JSObject::cast(result)->HasFastElements());
1780
1781 return result;
1782}
1783
1784
1785Object* Heap::AllocateInitialMap(JSFunction* fun) {
1786 ASSERT(!fun->has_initial_map());
1787
ager@chromium.org7c537e22008-10-16 08:43:32 +00001788 // First create a new map with the expected number of properties being
1789 // allocated in-object.
1790 int expected_nof_properties = fun->shared()->expected_nof_properties();
1791 int instance_size = JSObject::kHeaderSize +
1792 expected_nof_properties * kPointerSize;
1793 if (instance_size > JSObject::kMaxInstanceSize) {
1794 instance_size = JSObject::kMaxInstanceSize;
1795 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1796 kPointerSize;
1797 }
1798 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001799 if (map_obj->IsFailure()) return map_obj;
1800
1801 // Fetch or allocate prototype.
1802 Object* prototype;
1803 if (fun->has_instance_prototype()) {
1804 prototype = fun->instance_prototype();
1805 } else {
1806 prototype = AllocateFunctionPrototype(fun);
1807 if (prototype->IsFailure()) return prototype;
1808 }
1809 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001810 map->set_inobject_properties(expected_nof_properties);
1811 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001812 map->set_prototype(prototype);
1813 return map;
1814}
1815
1816
1817void Heap::InitializeJSObjectFromMap(JSObject* obj,
1818 FixedArray* properties,
1819 Map* map) {
1820 obj->set_properties(properties);
1821 obj->initialize_elements();
1822 // TODO(1240798): Initialize the object's body using valid initial values
1823 // according to the object's initial map. For example, if the map's
1824 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1825 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1826 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1827 // verification code has to cope with (temporarily) invalid objects. See
1828 // for example, JSArray::JSArrayVerify).
1829 obj->InitializeBody(map->instance_size());
1830}
1831
1832
1833Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1834 // JSFunctions should be allocated using AllocateFunction to be
1835 // properly initialized.
1836 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1837
1838 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001839 int prop_size = map->unused_property_fields() - map->inobject_properties();
1840 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001841 if (properties->IsFailure()) return properties;
1842
1843 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001844 AllocationSpace space =
1845 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001846 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1847 Object* obj = Allocate(map, space);
1848 if (obj->IsFailure()) return obj;
1849
1850 // Initialize the JSObject.
1851 InitializeJSObjectFromMap(JSObject::cast(obj),
1852 FixedArray::cast(properties),
1853 map);
1854 return obj;
1855}
1856
1857
1858Object* Heap::AllocateJSObject(JSFunction* constructor,
1859 PretenureFlag pretenure) {
1860 // Allocate the initial map if absent.
1861 if (!constructor->has_initial_map()) {
1862 Object* initial_map = AllocateInitialMap(constructor);
1863 if (initial_map->IsFailure()) return initial_map;
1864 constructor->set_initial_map(Map::cast(initial_map));
1865 Map::cast(initial_map)->set_constructor(constructor);
1866 }
1867 // Allocate the object based on the constructors initial map.
1868 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1869}
1870
1871
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001872Object* Heap::CopyJSObject(JSObject* source) {
1873 // Never used to copy functions. If functions need to be copied we
1874 // have to be careful to clear the literals array.
1875 ASSERT(!source->IsJSFunction());
1876
1877 // Make the clone.
1878 Map* map = source->map();
1879 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001880 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001881
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001882 // If we're forced to always allocate, we use the general allocation
1883 // functions which may leave us with an object in old space.
1884 if (always_allocate()) {
1885 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1886 if (clone->IsFailure()) return clone;
1887 Address clone_address = HeapObject::cast(clone)->address();
1888 CopyBlock(reinterpret_cast<Object**>(clone_address),
1889 reinterpret_cast<Object**>(source->address()),
1890 object_size);
1891 // Update write barrier for all fields that lie beyond the header.
1892 for (int offset = JSObject::kHeaderSize;
1893 offset < object_size;
1894 offset += kPointerSize) {
1895 RecordWrite(clone_address, offset);
1896 }
1897 } else {
1898 clone = new_space_.AllocateRaw(object_size);
1899 if (clone->IsFailure()) return clone;
1900 ASSERT(Heap::InNewSpace(clone));
1901 // Since we know the clone is allocated in new space, we can copy
1902 // the contents without worring about updating the write barrier.
1903 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1904 reinterpret_cast<Object**>(source->address()),
1905 object_size);
1906 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001907
1908 FixedArray* elements = FixedArray::cast(source->elements());
1909 FixedArray* properties = FixedArray::cast(source->properties());
1910 // Update elements if necessary.
1911 if (elements->length()> 0) {
1912 Object* elem = CopyFixedArray(elements);
1913 if (elem->IsFailure()) return elem;
1914 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1915 }
1916 // Update properties if necessary.
1917 if (properties->length() > 0) {
1918 Object* prop = CopyFixedArray(properties);
1919 if (prop->IsFailure()) return prop;
1920 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1921 }
1922 // Return the new clone.
1923 return clone;
1924}
1925
1926
1927Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1928 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001929 // Allocate initial map if absent.
1930 if (!constructor->has_initial_map()) {
1931 Object* initial_map = AllocateInitialMap(constructor);
1932 if (initial_map->IsFailure()) return initial_map;
1933 constructor->set_initial_map(Map::cast(initial_map));
1934 Map::cast(initial_map)->set_constructor(constructor);
1935 }
1936
1937 Map* map = constructor->initial_map();
1938
1939 // Check that the already allocated object has the same size as
1940 // objects allocated using the constructor.
1941 ASSERT(map->instance_size() == object->map()->instance_size());
1942
1943 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001944 int prop_size = map->unused_property_fields() - map->inobject_properties();
1945 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001946 if (properties->IsFailure()) return properties;
1947
1948 // Reset the map for the object.
1949 object->set_map(constructor->initial_map());
1950
1951 // Reinitialize the object from the constructor map.
1952 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1953 return object;
1954}
1955
1956
1957Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1958 PretenureFlag pretenure) {
1959 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1960 if (result->IsFailure()) return result;
1961
1962 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001963 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001964 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001965 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001966 }
1967 return result;
1968}
1969
1970
1971Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1972 PretenureFlag pretenure) {
1973 // Count the number of characters in the UTF-8 string and check if
1974 // it is an ASCII string.
1975 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1976 decoder->Reset(string.start(), string.length());
1977 int chars = 0;
1978 bool is_ascii = true;
1979 while (decoder->has_more()) {
1980 uc32 r = decoder->GetNext();
1981 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1982 chars++;
1983 }
1984
1985 // If the string is ascii, we do not need to convert the characters
1986 // since UTF8 is backwards compatible with ascii.
1987 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1988
1989 Object* result = AllocateRawTwoByteString(chars, pretenure);
1990 if (result->IsFailure()) return result;
1991
1992 // Convert and copy the characters into the new object.
1993 String* string_result = String::cast(result);
1994 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00001995 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001996 for (int i = 0; i < chars; i++) {
1997 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001998 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001999 }
2000 return result;
2001}
2002
2003
2004Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2005 PretenureFlag pretenure) {
2006 // Check if the string is an ASCII string.
2007 int i = 0;
2008 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2009
2010 Object* result;
2011 if (i == string.length()) { // It's an ASCII string.
2012 result = AllocateRawAsciiString(string.length(), pretenure);
2013 } else { // It's not an ASCII string.
2014 result = AllocateRawTwoByteString(string.length(), pretenure);
2015 }
2016 if (result->IsFailure()) return result;
2017
2018 // Copy the characters into the new object, which may be either ASCII or
2019 // UTF-16.
2020 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002021 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002022 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002023 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002024 }
2025 return result;
2026}
2027
2028
2029Map* Heap::SymbolMapForString(String* string) {
2030 // If the string is in new space it cannot be used as a symbol.
2031 if (InNewSpace(string)) return NULL;
2032
2033 // Find the corresponding symbol map for strings.
2034 Map* map = string->map();
2035
2036 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2037 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2038 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2039
2040 if (map == short_string_map()) return short_symbol_map();
2041 if (map == medium_string_map()) return medium_symbol_map();
2042 if (map == long_string_map()) return long_symbol_map();
2043
2044 if (map == short_cons_string_map()) return short_cons_symbol_map();
2045 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2046 if (map == long_cons_string_map()) return long_cons_symbol_map();
2047
2048 if (map == short_cons_ascii_string_map()) {
2049 return short_cons_ascii_symbol_map();
2050 }
2051 if (map == medium_cons_ascii_string_map()) {
2052 return medium_cons_ascii_symbol_map();
2053 }
2054 if (map == long_cons_ascii_string_map()) {
2055 return long_cons_ascii_symbol_map();
2056 }
2057
2058 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002059 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2060 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002061
2062 if (map == short_sliced_ascii_string_map()) {
2063 return short_sliced_ascii_symbol_map();
2064 }
2065 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002066 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067 }
2068 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002069 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002070 }
2071
2072 if (map == short_external_string_map()) return short_external_string_map();
2073 if (map == medium_external_string_map()) return medium_external_string_map();
2074 if (map == long_external_string_map()) return long_external_string_map();
2075
2076 if (map == short_external_ascii_string_map()) {
2077 return short_external_ascii_string_map();
2078 }
2079 if (map == medium_external_ascii_string_map()) {
2080 return medium_external_ascii_string_map();
2081 }
2082 if (map == long_external_ascii_string_map()) {
2083 return long_external_ascii_string_map();
2084 }
2085
2086 // No match found.
2087 return NULL;
2088}
2089
2090
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002091Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2092 int chars,
2093 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002094 // Ensure the chars matches the number of characters in the buffer.
2095 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2096 // Determine whether the string is ascii.
2097 bool is_ascii = true;
2098 while (buffer->has_more()) {
2099 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2100 }
2101 buffer->Rewind();
2102
2103 // Compute map and object size.
2104 int size;
2105 Map* map;
2106
2107 if (is_ascii) {
2108 if (chars <= String::kMaxShortStringSize) {
2109 map = short_ascii_symbol_map();
2110 } else if (chars <= String::kMaxMediumStringSize) {
2111 map = medium_ascii_symbol_map();
2112 } else {
2113 map = long_ascii_symbol_map();
2114 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002115 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002116 } else {
2117 if (chars <= String::kMaxShortStringSize) {
2118 map = short_symbol_map();
2119 } else if (chars <= String::kMaxMediumStringSize) {
2120 map = medium_symbol_map();
2121 } else {
2122 map = long_symbol_map();
2123 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002124 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002125 }
2126
2127 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002128 AllocationSpace space =
2129 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002130 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002131 if (result->IsFailure()) return result;
2132
2133 reinterpret_cast<HeapObject*>(result)->set_map(map);
2134 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002135 String* answer = String::cast(result);
2136 StringShape answer_shape(answer);
2137 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138
ager@chromium.org870a0b62008-11-04 11:43:05 +00002139 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002140
2141 // Fill in the characters.
2142 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002143 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002144 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002145 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002146}
2147
2148
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002149// External string resource that only contains a length field. These
2150// are used temporarily when allocating external symbols.
2151class DummyExternalStringResource
2152 : public v8::String::ExternalStringResource {
2153 public:
2154 explicit DummyExternalStringResource(size_t length) : length_(length) { }
2155
2156 virtual const uint16_t* data() const {
2157 UNREACHABLE();
2158 return NULL;
2159 }
2160
2161 virtual size_t length() const { return length_; }
2162 private:
2163 size_t length_;
2164};
2165
2166
2167Object* Heap::AllocateExternalSymbol(Vector<const char> string, int chars) {
2168 // Attempt to allocate the resulting external string first. Use a
2169 // dummy string resource that has the correct length so that we only
2170 // have to patch the external string resource after the callback.
2171 DummyExternalStringResource dummy_resource(chars);
2172 Object* obj = AllocateExternalSymbolFromTwoByte(&dummy_resource);
2173 if (obj->IsFailure()) return obj;
2174 // Perform callback.
2175 v8::String::ExternalStringResource* resource =
2176 global_external_symbol_callback_(string.start(), string.length());
2177 // Patch the resource pointer of the result.
2178 ExternalTwoByteString* result = ExternalTwoByteString::cast(obj);
2179 result->set_resource(resource);
2180 // Force hash code to be computed.
2181 result->Hash();
2182 ASSERT(result->IsEqualTo(string));
2183 return result;
2184}
2185
2186
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002187Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002188 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002189 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002190 if (size > MaxHeapObjectSize()) {
2191 space = LO_SPACE;
2192 }
2193
2194 // Use AllocateRaw rather than Allocate because the object's size cannot be
2195 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002196 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002197 if (result->IsFailure()) return result;
2198
2199 // Determine the map based on the string's length.
2200 Map* map;
2201 if (length <= String::kMaxShortStringSize) {
2202 map = short_ascii_string_map();
2203 } else if (length <= String::kMaxMediumStringSize) {
2204 map = medium_ascii_string_map();
2205 } else {
2206 map = long_ascii_string_map();
2207 }
2208
2209 // Partially initialize the object.
2210 HeapObject::cast(result)->set_map(map);
2211 String::cast(result)->set_length(length);
2212 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2213 return result;
2214}
2215
2216
2217Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002218 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002219 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002220 if (size > MaxHeapObjectSize()) {
2221 space = LO_SPACE;
2222 }
2223
2224 // Use AllocateRaw rather than Allocate because the object's size cannot be
2225 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002226 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002227 if (result->IsFailure()) return result;
2228
2229 // Determine the map based on the string's length.
2230 Map* map;
2231 if (length <= String::kMaxShortStringSize) {
2232 map = short_string_map();
2233 } else if (length <= String::kMaxMediumStringSize) {
2234 map = medium_string_map();
2235 } else {
2236 map = long_string_map();
2237 }
2238
2239 // Partially initialize the object.
2240 HeapObject::cast(result)->set_map(map);
2241 String::cast(result)->set_length(length);
2242 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2243 return result;
2244}
2245
2246
2247Object* Heap::AllocateEmptyFixedArray() {
2248 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002249 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002250 if (result->IsFailure()) return result;
2251 // Initialize the object.
2252 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2253 reinterpret_cast<Array*>(result)->set_length(0);
2254 return result;
2255}
2256
2257
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002258Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002259 // Use the general function if we're forced to always allocate.
2260 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002261 // Allocate the raw data for a fixed array.
2262 int size = FixedArray::SizeFor(length);
2263 return (size > MaxHeapObjectSize())
2264 ? lo_space_->AllocateRawFixedArray(size)
2265 : new_space_.AllocateRaw(size);
2266}
2267
2268
2269Object* Heap::CopyFixedArray(FixedArray* src) {
2270 int len = src->length();
2271 Object* obj = AllocateRawFixedArray(len);
2272 if (obj->IsFailure()) return obj;
2273 if (Heap::InNewSpace(obj)) {
2274 HeapObject* dst = HeapObject::cast(obj);
2275 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2276 reinterpret_cast<Object**>(src->address()),
2277 FixedArray::SizeFor(len));
2278 return obj;
2279 }
2280 HeapObject::cast(obj)->set_map(src->map());
2281 FixedArray* result = FixedArray::cast(obj);
2282 result->set_length(len);
2283 // Copy the content
2284 WriteBarrierMode mode = result->GetWriteBarrierMode();
2285 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2286 return result;
2287}
2288
2289
2290Object* Heap::AllocateFixedArray(int length) {
2291 Object* result = AllocateRawFixedArray(length);
2292 if (!result->IsFailure()) {
2293 // Initialize header.
2294 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2295 FixedArray* array = FixedArray::cast(result);
2296 array->set_length(length);
2297 Object* value = undefined_value();
2298 // Initialize body.
2299 for (int index = 0; index < length; index++) {
2300 array->set(index, value, SKIP_WRITE_BARRIER);
2301 }
2302 }
2303 return result;
2304}
2305
2306
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002307Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2308 ASSERT(empty_fixed_array()->IsFixedArray());
2309 if (length == 0) return empty_fixed_array();
2310
2311 int size = FixedArray::SizeFor(length);
2312 Object* result;
2313 if (size > MaxHeapObjectSize()) {
2314 result = lo_space_->AllocateRawFixedArray(size);
2315 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002316 AllocationSpace space =
2317 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002318 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002319 }
2320 if (result->IsFailure()) return result;
2321
2322 // Initialize the object.
2323 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2324 FixedArray* array = FixedArray::cast(result);
2325 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002326 Object* value = undefined_value();
2327 for (int index = 0; index < length; index++) {
2328 array->set(index, value, SKIP_WRITE_BARRIER);
2329 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002330 return array;
2331}
2332
2333
2334Object* Heap::AllocateFixedArrayWithHoles(int length) {
2335 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002336 Object* result = AllocateRawFixedArray(length);
2337 if (!result->IsFailure()) {
2338 // Initialize header.
2339 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2340 FixedArray* array = FixedArray::cast(result);
2341 array->set_length(length);
2342 // Initialize body.
2343 Object* value = the_hole_value();
2344 for (int index = 0; index < length; index++) {
2345 array->set(index, value, SKIP_WRITE_BARRIER);
2346 }
2347 }
2348 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002349}
2350
2351
2352Object* Heap::AllocateHashTable(int length) {
2353 Object* result = Heap::AllocateFixedArray(length);
2354 if (result->IsFailure()) return result;
2355 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2356 ASSERT(result->IsDictionary());
2357 return result;
2358}
2359
2360
2361Object* Heap::AllocateGlobalContext() {
2362 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2363 if (result->IsFailure()) return result;
2364 Context* context = reinterpret_cast<Context*>(result);
2365 context->set_map(global_context_map());
2366 ASSERT(context->IsGlobalContext());
2367 ASSERT(result->IsContext());
2368 return result;
2369}
2370
2371
2372Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2373 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2374 Object* result = Heap::AllocateFixedArray(length);
2375 if (result->IsFailure()) return result;
2376 Context* context = reinterpret_cast<Context*>(result);
2377 context->set_map(context_map());
2378 context->set_closure(function);
2379 context->set_fcontext(context);
2380 context->set_previous(NULL);
2381 context->set_extension(NULL);
2382 context->set_global(function->context()->global());
2383 ASSERT(!context->IsGlobalContext());
2384 ASSERT(context->is_function_context());
2385 ASSERT(result->IsContext());
2386 return result;
2387}
2388
2389
2390Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2391 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2392 if (result->IsFailure()) return result;
2393 Context* context = reinterpret_cast<Context*>(result);
2394 context->set_map(context_map());
2395 context->set_closure(previous->closure());
2396 context->set_fcontext(previous->fcontext());
2397 context->set_previous(previous);
2398 context->set_extension(extension);
2399 context->set_global(previous->global());
2400 ASSERT(!context->IsGlobalContext());
2401 ASSERT(!context->is_function_context());
2402 ASSERT(result->IsContext());
2403 return result;
2404}
2405
2406
2407Object* Heap::AllocateStruct(InstanceType type) {
2408 Map* map;
2409 switch (type) {
2410#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2411STRUCT_LIST(MAKE_CASE)
2412#undef MAKE_CASE
2413 default:
2414 UNREACHABLE();
2415 return Failure::InternalError();
2416 }
2417 int size = map->instance_size();
2418 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002419 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002420 Object* result = Heap::Allocate(map, space);
2421 if (result->IsFailure()) return result;
2422 Struct::cast(result)->InitializeBody(size);
2423 return result;
2424}
2425
2426
2427#ifdef DEBUG
2428
2429void Heap::Print() {
2430 if (!HasBeenSetup()) return;
2431 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002432 AllSpaces spaces;
2433 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002434}
2435
2436
2437void Heap::ReportCodeStatistics(const char* title) {
2438 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2439 PagedSpace::ResetCodeStatistics();
2440 // We do not look for code in new space, map space, or old space. If code
2441 // somehow ends up in those spaces, we would miss it here.
2442 code_space_->CollectCodeStatistics();
2443 lo_space_->CollectCodeStatistics();
2444 PagedSpace::ReportCodeStatistics();
2445}
2446
2447
2448// This function expects that NewSpace's allocated objects histogram is
2449// populated (via a call to CollectStatistics or else as a side effect of a
2450// just-completed scavenge collection).
2451void Heap::ReportHeapStatistics(const char* title) {
2452 USE(title);
2453 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2454 title, gc_count_);
2455 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002456 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2457 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002458
2459 PrintF("\n");
2460 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2461 GlobalHandles::PrintStats();
2462 PrintF("\n");
2463
2464 PrintF("Heap statistics : ");
2465 MemoryAllocator::ReportStatistics();
2466 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002467 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002468 PrintF("Old pointer space : ");
2469 old_pointer_space_->ReportStatistics();
2470 PrintF("Old data space : ");
2471 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002472 PrintF("Code space : ");
2473 code_space_->ReportStatistics();
2474 PrintF("Map space : ");
2475 map_space_->ReportStatistics();
2476 PrintF("Large object space : ");
2477 lo_space_->ReportStatistics();
2478 PrintF(">>>>>> ========================================= >>>>>>\n");
2479}
2480
2481#endif // DEBUG
2482
2483bool Heap::Contains(HeapObject* value) {
2484 return Contains(value->address());
2485}
2486
2487
2488bool Heap::Contains(Address addr) {
2489 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2490 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002491 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002492 old_pointer_space_->Contains(addr) ||
2493 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002494 code_space_->Contains(addr) ||
2495 map_space_->Contains(addr) ||
2496 lo_space_->SlowContains(addr));
2497}
2498
2499
2500bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2501 return InSpace(value->address(), space);
2502}
2503
2504
2505bool Heap::InSpace(Address addr, AllocationSpace space) {
2506 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2507 if (!HasBeenSetup()) return false;
2508
2509 switch (space) {
2510 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002511 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002512 case OLD_POINTER_SPACE:
2513 return old_pointer_space_->Contains(addr);
2514 case OLD_DATA_SPACE:
2515 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002516 case CODE_SPACE:
2517 return code_space_->Contains(addr);
2518 case MAP_SPACE:
2519 return map_space_->Contains(addr);
2520 case LO_SPACE:
2521 return lo_space_->SlowContains(addr);
2522 }
2523
2524 return false;
2525}
2526
2527
2528#ifdef DEBUG
2529void Heap::Verify() {
2530 ASSERT(HasBeenSetup());
2531
2532 VerifyPointersVisitor visitor;
2533 Heap::IterateRoots(&visitor);
2534
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002535 AllSpaces spaces;
2536 while (Space* space = spaces.next()) {
2537 space->Verify();
2538 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002539}
2540#endif // DEBUG
2541
2542
2543Object* Heap::LookupSymbol(Vector<const char> string) {
2544 Object* symbol = NULL;
2545 Object* new_table =
2546 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2547 if (new_table->IsFailure()) return new_table;
2548 symbol_table_ = new_table;
2549 ASSERT(symbol != NULL);
2550 return symbol;
2551}
2552
2553
2554Object* Heap::LookupSymbol(String* string) {
2555 if (string->IsSymbol()) return string;
2556 Object* symbol = NULL;
2557 Object* new_table =
2558 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2559 if (new_table->IsFailure()) return new_table;
2560 symbol_table_ = new_table;
2561 ASSERT(symbol != NULL);
2562 return symbol;
2563}
2564
2565
ager@chromium.org7c537e22008-10-16 08:43:32 +00002566bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2567 if (string->IsSymbol()) {
2568 *symbol = string;
2569 return true;
2570 }
2571 SymbolTable* table = SymbolTable::cast(symbol_table_);
2572 return table->LookupSymbolIfExists(string, symbol);
2573}
2574
2575
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002576#ifdef DEBUG
2577void Heap::ZapFromSpace() {
2578 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002579 for (Address a = new_space_.FromSpaceLow();
2580 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002581 a += kPointerSize) {
2582 Memory::Address_at(a) = kFromSpaceZapValue;
2583 }
2584}
2585#endif // DEBUG
2586
2587
2588void Heap::IterateRSetRange(Address object_start,
2589 Address object_end,
2590 Address rset_start,
2591 ObjectSlotCallback copy_object_func) {
2592 Address object_address = object_start;
2593 Address rset_address = rset_start;
2594
2595 // Loop over all the pointers in [object_start, object_end).
2596 while (object_address < object_end) {
2597 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002598 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002599 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002600 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002601 // Do not dereference pointers at or past object_end.
2602 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2603 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002604 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002605 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2606 }
2607 // If this pointer does not need to be remembered anymore, clear
2608 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002609 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002610 }
2611 object_address += kPointerSize;
2612 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002613 // Update the remembered set if it has changed.
2614 if (result_rset != rset_word) {
2615 Memory::uint32_at(rset_address) = result_rset;
2616 }
2617 } else {
2618 // No bits in the word were set. This is the common case.
2619 object_address += kPointerSize * kBitsPerInt;
2620 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002621 rset_address += kIntSize;
2622 }
2623}
2624
2625
2626void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2627 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002628 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002629
2630 PageIterator it(space, PageIterator::PAGES_IN_USE);
2631 while (it.has_next()) {
2632 Page* page = it.next();
2633 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2634 page->RSetStart(), copy_object_func);
2635 }
2636}
2637
2638
2639#ifdef DEBUG
2640#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2641#else
2642#define SYNCHRONIZE_TAG(tag)
2643#endif
2644
2645void Heap::IterateRoots(ObjectVisitor* v) {
2646 IterateStrongRoots(v);
2647 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2648 SYNCHRONIZE_TAG("symbol_table");
2649}
2650
2651
2652void Heap::IterateStrongRoots(ObjectVisitor* v) {
2653#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002654 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002655 STRONG_ROOT_LIST(ROOT_ITERATE);
2656#undef ROOT_ITERATE
2657 SYNCHRONIZE_TAG("strong_root_list");
2658
2659#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002660 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002661 STRUCT_LIST(STRUCT_MAP_ITERATE);
2662#undef STRUCT_MAP_ITERATE
2663 SYNCHRONIZE_TAG("struct_map");
2664
2665#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002666 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002667 SYMBOL_LIST(SYMBOL_ITERATE)
2668#undef SYMBOL_ITERATE
2669 SYNCHRONIZE_TAG("symbol");
2670
2671 Bootstrapper::Iterate(v);
2672 SYNCHRONIZE_TAG("bootstrapper");
2673 Top::Iterate(v);
2674 SYNCHRONIZE_TAG("top");
2675 Debug::Iterate(v);
2676 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002677 CompilationCache::Iterate(v);
2678 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002679
2680 // Iterate over local handles in handle scopes.
2681 HandleScopeImplementer::Iterate(v);
2682 SYNCHRONIZE_TAG("handlescope");
2683
2684 // Iterate over the builtin code objects and code stubs in the heap. Note
2685 // that it is not strictly necessary to iterate over code objects on
2686 // scavenge collections. We still do it here because this same function
2687 // is used by the mark-sweep collector and the deserializer.
2688 Builtins::IterateBuiltins(v);
2689 SYNCHRONIZE_TAG("builtins");
2690
2691 // Iterate over global handles.
2692 GlobalHandles::IterateRoots(v);
2693 SYNCHRONIZE_TAG("globalhandles");
2694
2695 // Iterate over pointers being held by inactive threads.
2696 ThreadManager::Iterate(v);
2697 SYNCHRONIZE_TAG("threadmanager");
2698}
2699#undef SYNCHRONIZE_TAG
2700
2701
2702// Flag is set when the heap has been configured. The heap can be repeatedly
2703// configured through the API until it is setup.
2704static bool heap_configured = false;
2705
2706// TODO(1236194): Since the heap size is configurable on the command line
2707// and through the API, we should gracefully handle the case that the heap
2708// size is not big enough to fit all the initial objects.
2709bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2710 if (HasBeenSetup()) return false;
2711
2712 if (semispace_size > 0) semispace_size_ = semispace_size;
2713 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2714
2715 // The new space size must be a power of two to support single-bit testing
2716 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002717 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002718 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2719 young_generation_size_ = 2 * semispace_size_;
2720
2721 // The old generation is paged.
2722 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2723
2724 heap_configured = true;
2725 return true;
2726}
2727
2728
kasper.lund7276f142008-07-30 08:49:36 +00002729bool Heap::ConfigureHeapDefault() {
2730 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2731}
2732
2733
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002734int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002735 return old_pointer_space_->Size()
2736 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002737 + code_space_->Size()
2738 + map_space_->Size()
2739 + lo_space_->Size();
2740}
2741
2742
kasper.lund7276f142008-07-30 08:49:36 +00002743int Heap::PromotedExternalMemorySize() {
2744 if (amount_of_external_allocated_memory_
2745 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2746 return amount_of_external_allocated_memory_
2747 - amount_of_external_allocated_memory_at_last_global_gc_;
2748}
2749
2750
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002751bool Heap::Setup(bool create_heap_objects) {
2752 // Initialize heap spaces and initial maps and objects. Whenever something
2753 // goes wrong, just return false. The caller should check the results and
2754 // call Heap::TearDown() to release allocated memory.
2755 //
2756 // If the heap is not yet configured (eg, through the API), configure it.
2757 // Configuration is based on the flags new-space-size (really the semispace
2758 // size) and old-space-size if set or the initial values of semispace_size_
2759 // and old_generation_size_ otherwise.
2760 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002761 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002762 }
2763
2764 // Setup memory allocator and allocate an initial chunk of memory. The
2765 // initial chunk is double the size of the new space to ensure that we can
2766 // find a pair of semispaces that are contiguous and aligned to their size.
2767 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2768 void* chunk
2769 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2770 if (chunk == NULL) return false;
2771
2772 // Put the initial chunk of the old space at the start of the initial
2773 // chunk, then the two new space semispaces, then the initial chunk of
2774 // code space. Align the pair of semispaces to their size, which must be
2775 // a power of 2.
2776 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002777 Address code_space_start = reinterpret_cast<Address>(chunk);
2778 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2779 Address old_space_start = new_space_start + young_generation_size_;
2780 int code_space_size = new_space_start - code_space_start;
2781 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002782
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002783 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002784 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002785
2786 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002787 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002788 old_pointer_space_ =
2789 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2790 if (old_pointer_space_ == NULL) return false;
2791 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2792 return false;
2793 }
2794 old_data_space_ =
2795 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2796 if (old_data_space_ == NULL) return false;
2797 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2798 old_space_size >> 1)) {
2799 return false;
2800 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002801
2802 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002803 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002804 code_space_ =
2805 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002806 if (code_space_ == NULL) return false;
2807 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2808
2809 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002810 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002811 if (map_space_ == NULL) return false;
2812 // Setting up a paged space without giving it a virtual memory range big
2813 // enough to hold at least a page will cause it to allocate.
2814 if (!map_space_->Setup(NULL, 0)) return false;
2815
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002816 // The large object code space may contain code or data. We set the memory
2817 // to be non-executable here for safety, but this means we need to enable it
2818 // explicitly when allocating large code objects.
2819 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002820 if (lo_space_ == NULL) return false;
2821 if (!lo_space_->Setup()) return false;
2822
2823 if (create_heap_objects) {
2824 // Create initial maps.
2825 if (!CreateInitialMaps()) return false;
2826 if (!CreateApiObjects()) return false;
2827
2828 // Create initial objects
2829 if (!CreateInitialObjects()) return false;
2830 }
2831
2832 LOG(IntEvent("heap-capacity", Capacity()));
2833 LOG(IntEvent("heap-available", Available()));
2834
2835 return true;
2836}
2837
2838
2839void Heap::TearDown() {
2840 GlobalHandles::TearDown();
2841
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002842 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002843
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002844 if (old_pointer_space_ != NULL) {
2845 old_pointer_space_->TearDown();
2846 delete old_pointer_space_;
2847 old_pointer_space_ = NULL;
2848 }
2849
2850 if (old_data_space_ != NULL) {
2851 old_data_space_->TearDown();
2852 delete old_data_space_;
2853 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002854 }
2855
2856 if (code_space_ != NULL) {
2857 code_space_->TearDown();
2858 delete code_space_;
2859 code_space_ = NULL;
2860 }
2861
2862 if (map_space_ != NULL) {
2863 map_space_->TearDown();
2864 delete map_space_;
2865 map_space_ = NULL;
2866 }
2867
2868 if (lo_space_ != NULL) {
2869 lo_space_->TearDown();
2870 delete lo_space_;
2871 lo_space_ = NULL;
2872 }
2873
2874 MemoryAllocator::TearDown();
2875}
2876
2877
2878void Heap::Shrink() {
2879 // Try to shrink map, old, and code spaces.
2880 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002881 old_pointer_space_->Shrink();
2882 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002883 code_space_->Shrink();
2884}
2885
2886
2887#ifdef DEBUG
2888
2889class PrintHandleVisitor: public ObjectVisitor {
2890 public:
2891 void VisitPointers(Object** start, Object** end) {
2892 for (Object** p = start; p < end; p++)
2893 PrintF(" handle %p to %p\n", p, *p);
2894 }
2895};
2896
2897void Heap::PrintHandles() {
2898 PrintF("Handles:\n");
2899 PrintHandleVisitor v;
2900 HandleScopeImplementer::Iterate(&v);
2901}
2902
2903#endif
2904
2905
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002906Space* AllSpaces::next() {
2907 switch (counter_++) {
2908 case NEW_SPACE:
2909 return Heap::new_space();
2910 case OLD_POINTER_SPACE:
2911 return Heap::old_pointer_space();
2912 case OLD_DATA_SPACE:
2913 return Heap::old_data_space();
2914 case CODE_SPACE:
2915 return Heap::code_space();
2916 case MAP_SPACE:
2917 return Heap::map_space();
2918 case LO_SPACE:
2919 return Heap::lo_space();
2920 default:
2921 return NULL;
2922 }
2923}
2924
2925
2926PagedSpace* PagedSpaces::next() {
2927 switch (counter_++) {
2928 case OLD_POINTER_SPACE:
2929 return Heap::old_pointer_space();
2930 case OLD_DATA_SPACE:
2931 return Heap::old_data_space();
2932 case CODE_SPACE:
2933 return Heap::code_space();
2934 case MAP_SPACE:
2935 return Heap::map_space();
2936 default:
2937 return NULL;
2938 }
2939}
2940
2941
2942
2943OldSpace* OldSpaces::next() {
2944 switch (counter_++) {
2945 case OLD_POINTER_SPACE:
2946 return Heap::old_pointer_space();
2947 case OLD_DATA_SPACE:
2948 return Heap::old_data_space();
2949 case CODE_SPACE:
2950 return Heap::code_space();
2951 default:
2952 return NULL;
2953 }
2954}
2955
2956
kasper.lund7276f142008-07-30 08:49:36 +00002957SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2958}
2959
2960
2961SpaceIterator::~SpaceIterator() {
2962 // Delete active iterator if any.
2963 delete iterator_;
2964}
2965
2966
2967bool SpaceIterator::has_next() {
2968 // Iterate until no more spaces.
2969 return current_space_ != LAST_SPACE;
2970}
2971
2972
2973ObjectIterator* SpaceIterator::next() {
2974 if (iterator_ != NULL) {
2975 delete iterator_;
2976 iterator_ = NULL;
2977 // Move to the next space
2978 current_space_++;
2979 if (current_space_ > LAST_SPACE) {
2980 return NULL;
2981 }
2982 }
2983
2984 // Return iterator for the new current space.
2985 return CreateIterator();
2986}
2987
2988
2989// Create an iterator for the space to iterate.
2990ObjectIterator* SpaceIterator::CreateIterator() {
2991 ASSERT(iterator_ == NULL);
2992
2993 switch (current_space_) {
2994 case NEW_SPACE:
2995 iterator_ = new SemiSpaceIterator(Heap::new_space());
2996 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002997 case OLD_POINTER_SPACE:
2998 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2999 break;
3000 case OLD_DATA_SPACE:
3001 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003002 break;
3003 case CODE_SPACE:
3004 iterator_ = new HeapObjectIterator(Heap::code_space());
3005 break;
3006 case MAP_SPACE:
3007 iterator_ = new HeapObjectIterator(Heap::map_space());
3008 break;
3009 case LO_SPACE:
3010 iterator_ = new LargeObjectIterator(Heap::lo_space());
3011 break;
3012 }
3013
3014 // Return the newly allocated iterator;
3015 ASSERT(iterator_ != NULL);
3016 return iterator_;
3017}
3018
3019
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003020HeapIterator::HeapIterator() {
3021 Init();
3022}
3023
3024
3025HeapIterator::~HeapIterator() {
3026 Shutdown();
3027}
3028
3029
3030void HeapIterator::Init() {
3031 // Start the iteration.
3032 space_iterator_ = new SpaceIterator();
3033 object_iterator_ = space_iterator_->next();
3034}
3035
3036
3037void HeapIterator::Shutdown() {
3038 // Make sure the last iterator is deallocated.
3039 delete space_iterator_;
3040 space_iterator_ = NULL;
3041 object_iterator_ = NULL;
3042}
3043
3044
3045bool HeapIterator::has_next() {
3046 // No iterator means we are done.
3047 if (object_iterator_ == NULL) return false;
3048
3049 if (object_iterator_->has_next_object()) {
3050 // If the current iterator has more objects we are fine.
3051 return true;
3052 } else {
3053 // Go though the spaces looking for one that has objects.
3054 while (space_iterator_->has_next()) {
3055 object_iterator_ = space_iterator_->next();
3056 if (object_iterator_->has_next_object()) {
3057 return true;
3058 }
3059 }
3060 }
3061 // Done with the last space.
3062 object_iterator_ = NULL;
3063 return false;
3064}
3065
3066
3067HeapObject* HeapIterator::next() {
3068 if (has_next()) {
3069 return object_iterator_->next_object();
3070 } else {
3071 return NULL;
3072 }
3073}
3074
3075
3076void HeapIterator::reset() {
3077 // Restart the iterator.
3078 Shutdown();
3079 Init();
3080}
3081
3082
3083//
3084// HeapProfiler class implementation.
3085//
3086#ifdef ENABLE_LOGGING_AND_PROFILING
3087void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3088 InstanceType type = obj->map()->instance_type();
3089 ASSERT(0 <= type && type <= LAST_TYPE);
3090 info[type].increment_number(1);
3091 info[type].increment_bytes(obj->Size());
3092}
3093#endif
3094
3095
3096#ifdef ENABLE_LOGGING_AND_PROFILING
3097void HeapProfiler::WriteSample() {
3098 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3099
3100 HistogramInfo info[LAST_TYPE+1];
3101#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3102 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3103#undef DEF_TYPE_NAME
3104
3105 HeapIterator iterator;
3106 while (iterator.has_next()) {
3107 CollectStats(iterator.next(), info);
3108 }
3109
3110 // Lump all the string types together.
3111 int string_number = 0;
3112 int string_bytes = 0;
3113#define INCREMENT_SIZE(type, size, name) \
3114 string_number += info[type].number(); \
3115 string_bytes += info[type].bytes();
3116 STRING_TYPE_LIST(INCREMENT_SIZE)
3117#undef INCREMENT_SIZE
3118 if (string_bytes > 0) {
3119 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3120 }
3121
3122 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3123 if (info[i].bytes() > 0) {
3124 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3125 info[i].bytes()));
3126 }
3127 }
3128
3129 LOG(HeapSampleEndEvent("Heap", "allocated"));
3130}
3131
3132
3133#endif
3134
3135
3136
3137#ifdef DEBUG
3138
3139static bool search_for_any_global;
3140static Object* search_target;
3141static bool found_target;
3142static List<Object*> object_stack(20);
3143
3144
3145// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3146static const int kMarkTag = 2;
3147
3148static void MarkObjectRecursively(Object** p);
3149class MarkObjectVisitor : public ObjectVisitor {
3150 public:
3151 void VisitPointers(Object** start, Object** end) {
3152 // Copy all HeapObject pointers in [start, end)
3153 for (Object** p = start; p < end; p++) {
3154 if ((*p)->IsHeapObject())
3155 MarkObjectRecursively(p);
3156 }
3157 }
3158};
3159
3160static MarkObjectVisitor mark_visitor;
3161
3162static void MarkObjectRecursively(Object** p) {
3163 if (!(*p)->IsHeapObject()) return;
3164
3165 HeapObject* obj = HeapObject::cast(*p);
3166
3167 Object* map = obj->map();
3168
3169 if (!map->IsHeapObject()) return; // visited before
3170
3171 if (found_target) return; // stop if target found
3172 object_stack.Add(obj);
3173 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3174 (!search_for_any_global && (obj == search_target))) {
3175 found_target = true;
3176 return;
3177 }
3178
3179 if (obj->IsCode()) {
3180 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3181 }
3182
3183 // not visited yet
3184 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3185
3186 Address map_addr = map_p->address();
3187
3188 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3189
3190 MarkObjectRecursively(&map);
3191
3192 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3193 &mark_visitor);
3194
3195 if (!found_target) // don't pop if found the target
3196 object_stack.RemoveLast();
3197}
3198
3199
3200static void UnmarkObjectRecursively(Object** p);
3201class UnmarkObjectVisitor : public ObjectVisitor {
3202 public:
3203 void VisitPointers(Object** start, Object** end) {
3204 // Copy all HeapObject pointers in [start, end)
3205 for (Object** p = start; p < end; p++) {
3206 if ((*p)->IsHeapObject())
3207 UnmarkObjectRecursively(p);
3208 }
3209 }
3210};
3211
3212static UnmarkObjectVisitor unmark_visitor;
3213
3214static void UnmarkObjectRecursively(Object** p) {
3215 if (!(*p)->IsHeapObject()) return;
3216
3217 HeapObject* obj = HeapObject::cast(*p);
3218
3219 Object* map = obj->map();
3220
3221 if (map->IsHeapObject()) return; // unmarked already
3222
3223 Address map_addr = reinterpret_cast<Address>(map);
3224
3225 map_addr -= kMarkTag;
3226
3227 ASSERT_TAG_ALIGNED(map_addr);
3228
3229 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3230
3231 obj->set_map(reinterpret_cast<Map*>(map_p));
3232
3233 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3234
3235 obj->IterateBody(Map::cast(map_p)->instance_type(),
3236 obj->SizeFromMap(Map::cast(map_p)),
3237 &unmark_visitor);
3238
3239 if (obj->IsCode()) {
3240 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3241 }
3242}
3243
3244
3245static void MarkRootObjectRecursively(Object** root) {
3246 if (search_for_any_global) {
3247 ASSERT(search_target == NULL);
3248 } else {
3249 ASSERT(search_target->IsHeapObject());
3250 }
3251 found_target = false;
3252 object_stack.Clear();
3253
3254 MarkObjectRecursively(root);
3255 UnmarkObjectRecursively(root);
3256
3257 if (found_target) {
3258 PrintF("=====================================\n");
3259 PrintF("==== Path to object ====\n");
3260 PrintF("=====================================\n\n");
3261
3262 ASSERT(!object_stack.is_empty());
3263 for (int i = 0; i < object_stack.length(); i++) {
3264 if (i > 0) PrintF("\n |\n |\n V\n\n");
3265 Object* obj = object_stack[i];
3266 obj->Print();
3267 }
3268 PrintF("=====================================\n");
3269 }
3270}
3271
3272
3273// Helper class for visiting HeapObjects recursively.
3274class MarkRootVisitor: public ObjectVisitor {
3275 public:
3276 void VisitPointers(Object** start, Object** end) {
3277 // Visit all HeapObject pointers in [start, end)
3278 for (Object** p = start; p < end; p++) {
3279 if ((*p)->IsHeapObject())
3280 MarkRootObjectRecursively(p);
3281 }
3282 }
3283};
3284
3285
3286// Triggers a depth-first traversal of reachable objects from roots
3287// and finds a path to a specific heap object and prints it.
3288void Heap::TracePathToObject() {
3289 search_target = NULL;
3290 search_for_any_global = false;
3291
3292 MarkRootVisitor root_visitor;
3293 IterateRoots(&root_visitor);
3294}
3295
3296
3297// Triggers a depth-first traversal of reachable objects from roots
3298// and finds a path to any global object and prints it. Useful for
3299// determining the source for leaks of global objects.
3300void Heap::TracePathToGlobal() {
3301 search_target = NULL;
3302 search_for_any_global = true;
3303
3304 MarkRootVisitor root_visitor;
3305 IterateRoots(&root_visitor);
3306}
3307#endif
3308
3309
kasper.lund7276f142008-07-30 08:49:36 +00003310GCTracer::GCTracer()
3311 : start_time_(0.0),
3312 start_size_(0.0),
3313 gc_count_(0),
3314 full_gc_count_(0),
3315 is_compacting_(false),
3316 marked_count_(0) {
3317 // These two fields reflect the state of the previous full collection.
3318 // Set them before they are changed by the collector.
3319 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3320 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3321 if (!FLAG_trace_gc) return;
3322 start_time_ = OS::TimeCurrentMillis();
3323 start_size_ = SizeOfHeapObjects();
3324}
3325
3326
3327GCTracer::~GCTracer() {
3328 if (!FLAG_trace_gc) return;
3329 // Printf ONE line iff flag is set.
3330 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3331 CollectorString(),
3332 start_size_, SizeOfHeapObjects(),
3333 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3334}
3335
3336
3337const char* GCTracer::CollectorString() {
3338 switch (collector_) {
3339 case SCAVENGER:
3340 return "Scavenge";
3341 case MARK_COMPACTOR:
3342 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3343 : "Mark-sweep";
3344 }
3345 return "Unknown GC";
3346}
3347
3348
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003349#ifdef DEBUG
3350bool Heap::GarbageCollectionGreedyCheck() {
3351 ASSERT(FLAG_gc_greedy);
3352 if (Bootstrapper::IsActive()) return true;
3353 if (disallow_allocation_failure()) return true;
3354 return CollectGarbage(0, NEW_SPACE);
3355}
3356#endif
3357
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003358} } // namespace v8::internal