blob: c4a860bedc5d7ce6207837170e746521b22f83ce [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;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001020 catch_context_map_ = Map::cast(obj);
1021
1022 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1023 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 global_context_map_ = Map::cast(obj);
1025
1026 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1027 if (obj->IsFailure()) return false;
1028 boilerplate_function_map_ = Map::cast(obj);
1029
1030 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1031 if (obj->IsFailure()) return false;
1032 shared_function_info_map_ = Map::cast(obj);
1033
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001034 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001035 return true;
1036}
1037
1038
1039Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1040 // Statically ensure that it is safe to allocate heap numbers in paged
1041 // spaces.
1042 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001043 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001044 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001045 if (result->IsFailure()) return result;
1046
1047 HeapObject::cast(result)->set_map(heap_number_map());
1048 HeapNumber::cast(result)->set_value(value);
1049 return result;
1050}
1051
1052
1053Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001054 // Use general version, if we're forced to always allocate.
1055 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001056 // This version of AllocateHeapNumber is optimized for
1057 // allocation in new space.
1058 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1059 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001060 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061 if (result->IsFailure()) return result;
1062 HeapObject::cast(result)->set_map(heap_number_map());
1063 HeapNumber::cast(result)->set_value(value);
1064 return result;
1065}
1066
1067
1068Object* Heap::CreateOddball(Map* map,
1069 const char* to_string,
1070 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001071 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001072 if (result->IsFailure()) return result;
1073 return Oddball::cast(result)->Initialize(to_string, to_number);
1074}
1075
1076
1077bool Heap::CreateApiObjects() {
1078 Object* obj;
1079
1080 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1081 if (obj->IsFailure()) return false;
1082 neander_map_ = Map::cast(obj);
1083
1084 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1085 if (obj->IsFailure()) return false;
1086 Object* elements = AllocateFixedArray(2);
1087 if (elements->IsFailure()) return false;
1088 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1089 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1090 message_listeners_ = JSObject::cast(obj);
1091
1092 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1093 if (obj->IsFailure()) return false;
1094 elements = AllocateFixedArray(2);
1095 if (elements->IsFailure()) return false;
1096 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1097 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1098 debug_event_listeners_ = JSObject::cast(obj);
1099
1100 return true;
1101}
1102
1103void Heap::CreateFixedStubs() {
1104 // Here we create roots for fixed stubs. They are needed at GC
1105 // for cooking and uncooking (check out frames.cc).
1106 // The eliminates the need for doing dictionary lookup in the
1107 // stub cache for these stubs.
1108 HandleScope scope;
1109 {
1110 CEntryStub stub;
1111 c_entry_code_ = *stub.GetCode();
1112 }
1113 {
1114 CEntryDebugBreakStub stub;
1115 c_entry_debug_break_code_ = *stub.GetCode();
1116 }
1117 {
1118 JSEntryStub stub;
1119 js_entry_code_ = *stub.GetCode();
1120 }
1121 {
1122 JSConstructEntryStub stub;
1123 js_construct_entry_code_ = *stub.GetCode();
1124 }
1125}
1126
1127
1128bool Heap::CreateInitialObjects() {
1129 Object* obj;
1130
1131 // The -0 value must be set before NumberFromDouble works.
1132 obj = AllocateHeapNumber(-0.0, TENURED);
1133 if (obj->IsFailure()) return false;
1134 minus_zero_value_ = obj;
1135 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1136
1137 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1138 if (obj->IsFailure()) return false;
1139 nan_value_ = obj;
1140
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001141 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001142 if (obj->IsFailure()) return false;
1143 undefined_value_ = obj;
1144 ASSERT(!InNewSpace(undefined_value()));
1145
1146 // Allocate initial symbol table.
1147 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1148 if (obj->IsFailure()) return false;
1149 symbol_table_ = obj;
1150
1151 // Assign the print strings for oddballs after creating symboltable.
1152 Object* symbol = LookupAsciiSymbol("undefined");
1153 if (symbol->IsFailure()) return false;
1154 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1155 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1156
1157 // Assign the print strings for oddballs after creating symboltable.
1158 symbol = LookupAsciiSymbol("null");
1159 if (symbol->IsFailure()) return false;
1160 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1161 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1162
1163 // Allocate the null_value
1164 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1165 if (obj->IsFailure()) return false;
1166
1167 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1168 if (obj->IsFailure()) return false;
1169 true_value_ = obj;
1170
1171 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1172 if (obj->IsFailure()) return false;
1173 false_value_ = obj;
1174
1175 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1176 if (obj->IsFailure()) return false;
1177 the_hole_value_ = obj;
1178
1179 // Allocate the empty string.
1180 obj = AllocateRawAsciiString(0, TENURED);
1181 if (obj->IsFailure()) return false;
1182 empty_string_ = String::cast(obj);
1183
1184#define SYMBOL_INITIALIZE(name, string) \
1185 obj = LookupAsciiSymbol(string); \
1186 if (obj->IsFailure()) return false; \
1187 (name##_) = String::cast(obj);
1188 SYMBOL_LIST(SYMBOL_INITIALIZE)
1189#undef SYMBOL_INITIALIZE
1190
1191 // Allocate the proxy for __proto__.
1192 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1193 if (obj->IsFailure()) return false;
1194 prototype_accessors_ = Proxy::cast(obj);
1195
1196 // Allocate the code_stubs dictionary.
1197 obj = Dictionary::Allocate(4);
1198 if (obj->IsFailure()) return false;
1199 code_stubs_ = Dictionary::cast(obj);
1200
1201 // Allocate the non_monomorphic_cache used in stub-cache.cc
1202 obj = Dictionary::Allocate(4);
1203 if (obj->IsFailure()) return false;
1204 non_monomorphic_cache_ = Dictionary::cast(obj);
1205
1206 CreateFixedStubs();
1207
1208 // Allocate the number->string conversion cache
1209 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1210 if (obj->IsFailure()) return false;
1211 number_string_cache_ = FixedArray::cast(obj);
1212
1213 // Allocate cache for single character strings.
1214 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1215 if (obj->IsFailure()) return false;
1216 single_character_string_cache_ = FixedArray::cast(obj);
1217
1218 // Allocate cache for external strings pointing to native source code.
1219 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1220 if (obj->IsFailure()) return false;
1221 natives_source_cache_ = FixedArray::cast(obj);
1222
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001223 // Initialize keyed lookup cache.
1224 ClearKeyedLookupCache();
1225
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001226 // Initialize compilation cache.
1227 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001228
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229 return true;
1230}
1231
1232
1233static inline int double_get_hash(double d) {
1234 DoubleRepresentation rep(d);
1235 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1236 (Heap::kNumberStringCacheSize - 1));
1237}
1238
1239
1240static inline int smi_get_hash(Smi* smi) {
1241 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1242}
1243
1244
1245
1246Object* Heap::GetNumberStringCache(Object* number) {
1247 int hash;
1248 if (number->IsSmi()) {
1249 hash = smi_get_hash(Smi::cast(number));
1250 } else {
1251 hash = double_get_hash(number->Number());
1252 }
1253 Object* key = number_string_cache_->get(hash * 2);
1254 if (key == number) {
1255 return String::cast(number_string_cache_->get(hash * 2 + 1));
1256 } else if (key->IsHeapNumber() &&
1257 number->IsHeapNumber() &&
1258 key->Number() == number->Number()) {
1259 return String::cast(number_string_cache_->get(hash * 2 + 1));
1260 }
1261 return undefined_value();
1262}
1263
1264
1265void Heap::SetNumberStringCache(Object* number, String* string) {
1266 int hash;
1267 if (number->IsSmi()) {
1268 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001269 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001270 } else {
1271 hash = double_get_hash(number->Number());
1272 number_string_cache_->set(hash * 2, number);
1273 }
1274 number_string_cache_->set(hash * 2 + 1, string);
1275}
1276
1277
1278Object* Heap::SmiOrNumberFromDouble(double value,
1279 bool new_object,
1280 PretenureFlag pretenure) {
1281 // We need to distinguish the minus zero value and this cannot be
1282 // done after conversion to int. Doing this by comparing bit
1283 // patterns is faster than using fpclassify() et al.
1284 static const DoubleRepresentation plus_zero(0.0);
1285 static const DoubleRepresentation minus_zero(-0.0);
1286 static const DoubleRepresentation nan(OS::nan_value());
1287 ASSERT(minus_zero_value_ != NULL);
1288 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1289
1290 DoubleRepresentation rep(value);
1291 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1292 if (rep.bits == minus_zero.bits) {
1293 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1294 : minus_zero_value_;
1295 }
1296 if (rep.bits == nan.bits) {
1297 return new_object
1298 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1299 : nan_value_;
1300 }
1301
1302 // Try to represent the value as a tagged small integer.
1303 int int_value = FastD2I(value);
1304 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1305 return Smi::FromInt(int_value);
1306 }
1307
1308 // Materialize the value in the heap.
1309 return AllocateHeapNumber(value, pretenure);
1310}
1311
1312
1313Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1314 return SmiOrNumberFromDouble(value,
1315 true /* number object must be new */,
1316 pretenure);
1317}
1318
1319
1320Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1321 return SmiOrNumberFromDouble(value,
1322 false /* use preallocated NaN, -0.0 */,
1323 pretenure);
1324}
1325
1326
1327Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1328 // Statically ensure that it is safe to allocate proxies in paged spaces.
1329 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001330 AllocationSpace space =
1331 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001332 Object* result = Allocate(proxy_map(), space);
1333 if (result->IsFailure()) return result;
1334
1335 Proxy::cast(result)->set_proxy(proxy);
1336 return result;
1337}
1338
1339
1340Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1341 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1342 if (result->IsFailure()) return result;
1343
1344 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1345 share->set_name(name);
1346 Code* illegal = Builtins::builtin(Builtins::Illegal);
1347 share->set_code(illegal);
1348 share->set_expected_nof_properties(0);
1349 share->set_length(0);
1350 share->set_formal_parameter_count(0);
1351 share->set_instance_class_name(Object_symbol());
1352 share->set_function_data(undefined_value());
1353 share->set_lazy_load_data(undefined_value());
1354 share->set_script(undefined_value());
1355 share->set_start_position_and_type(0);
1356 share->set_debug_info(undefined_value());
1357 return result;
1358}
1359
1360
ager@chromium.org870a0b62008-11-04 11:43:05 +00001361Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001362 String* second) {
1363 StringShape first_shape(first);
1364 StringShape second_shape(second);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001365 int first_length = first->length(first_shape);
1366 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001367 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001368 bool is_ascii = first_shape.IsAsciiRepresentation()
1369 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001370
1371 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001372 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001373 ASSERT(first->IsFlat(first_shape));
1374 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001375 if (is_ascii) {
1376 Object* result = AllocateRawAsciiString(length);
1377 if (result->IsFailure()) return result;
1378 // Copy the characters into the new object.
1379 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001380 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1381 String::WriteToFlat(second,
1382 second_shape,
1383 dest + first_length,
1384 0,
1385 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001386 return result;
1387 } else {
1388 Object* result = AllocateRawTwoByteString(length);
1389 if (result->IsFailure()) return result;
1390 // Copy the characters into the new object.
1391 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001392 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1393 String::WriteToFlat(second,
1394 second_shape,
1395 dest + first_length,
1396 0,
1397 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001398 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001400 }
1401
1402 Map* map;
1403 if (length <= String::kMaxShortStringSize) {
1404 map = is_ascii ? short_cons_ascii_string_map()
1405 : short_cons_string_map();
1406 } else if (length <= String::kMaxMediumStringSize) {
1407 map = is_ascii ? medium_cons_ascii_string_map()
1408 : medium_cons_string_map();
1409 } else {
1410 map = is_ascii ? long_cons_ascii_string_map()
1411 : long_cons_string_map();
1412 }
1413
1414 Object* result = Allocate(map, NEW_SPACE);
1415 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001416 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001418 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1419 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 return result;
1422}
1423
1424
ager@chromium.org870a0b62008-11-04 11:43:05 +00001425Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001426 int start,
1427 int end) {
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001428 StringShape buffer_shape(buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001429 int length = end - start;
1430
1431 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001432 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001433 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001434 }
1435
1436 Map* map;
1437 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001438 map = buffer_shape.IsAsciiRepresentation() ?
1439 short_sliced_ascii_string_map() :
1440 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001442 map = buffer_shape.IsAsciiRepresentation() ?
1443 medium_sliced_ascii_string_map() :
1444 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001445 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001446 map = buffer_shape.IsAsciiRepresentation() ?
1447 long_sliced_ascii_string_map() :
1448 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001449 }
1450
1451 Object* result = Allocate(map, NEW_SPACE);
1452 if (result->IsFailure()) return result;
1453
1454 SlicedString* sliced_string = SlicedString::cast(result);
1455 sliced_string->set_buffer(buffer);
1456 sliced_string->set_start(start);
1457 sliced_string->set_length(length);
1458
1459 return result;
1460}
1461
1462
ager@chromium.org870a0b62008-11-04 11:43:05 +00001463Object* Heap::AllocateSubString(String* buffer,
1464 StringShape buffer_shape,
1465 int start,
1466 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467 int length = end - start;
1468
ager@chromium.org7c537e22008-10-16 08:43:32 +00001469 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001470 return Heap::LookupSingleCharacterStringFromCode(
1471 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001472 }
1473
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001474 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001475 if (!buffer->IsFlat(buffer_shape)) {
1476 buffer->TryFlatten(buffer_shape);
1477 buffer_shape = StringShape(buffer);
1478 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001479
ager@chromium.org870a0b62008-11-04 11:43:05 +00001480 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001481 ? AllocateRawAsciiString(length)
1482 : AllocateRawTwoByteString(length);
1483 if (result->IsFailure()) return result;
1484
1485 // Copy the characters into the new object.
1486 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001487 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001488 StringHasher hasher(length);
1489 int i = 0;
1490 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001491 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001492 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001493 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001495 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001496 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001497 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001498 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001499 }
1500 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001501 return result;
1502}
1503
1504
1505Object* Heap::AllocateExternalStringFromAscii(
1506 ExternalAsciiString::Resource* resource) {
1507 Map* map;
1508 int length = resource->length();
1509 if (length <= String::kMaxShortStringSize) {
1510 map = short_external_ascii_string_map();
1511 } else if (length <= String::kMaxMediumStringSize) {
1512 map = medium_external_ascii_string_map();
1513 } else {
1514 map = long_external_ascii_string_map();
1515 }
1516
1517 Object* result = Allocate(map, NEW_SPACE);
1518 if (result->IsFailure()) return result;
1519
1520 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1521 external_string->set_length(length);
1522 external_string->set_resource(resource);
1523
1524 return result;
1525}
1526
1527
1528Object* Heap::AllocateExternalStringFromTwoByte(
1529 ExternalTwoByteString::Resource* resource) {
1530 Map* map;
1531 int length = resource->length();
1532 if (length <= String::kMaxShortStringSize) {
1533 map = short_external_string_map();
1534 } else if (length <= String::kMaxMediumStringSize) {
1535 map = medium_external_string_map();
1536 } else {
1537 map = long_external_string_map();
1538 }
1539
1540 Object* result = Allocate(map, NEW_SPACE);
1541 if (result->IsFailure()) return result;
1542
1543 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1544 external_string->set_length(length);
1545 external_string->set_resource(resource);
1546
1547 return result;
1548}
1549
1550
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001551Object* Heap::AllocateExternalSymbolFromTwoByte(
1552 ExternalTwoByteString::Resource* resource) {
1553 Map* map;
1554 int length = resource->length();
1555 if (length <= String::kMaxShortStringSize) {
1556 map = short_external_symbol_map();
1557 } else if (length <= String::kMaxMediumStringSize) {
1558 map = medium_external_symbol_map();
1559 } else {
1560 map = long_external_symbol_map();
1561 }
1562
1563 Object* result = Allocate(map, OLD_DATA_SPACE);
1564 if (result->IsFailure()) return result;
1565
1566 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1567 external_string->set_length(length);
1568 external_string->set_resource(resource);
1569
1570 return result;
1571}
1572
1573
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001574Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575 if (code <= String::kMaxAsciiCharCode) {
1576 Object* value = Heap::single_character_string_cache()->get(code);
1577 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001578
1579 char buffer[1];
1580 buffer[0] = static_cast<char>(code);
1581 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1582
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 Heap::single_character_string_cache()->set(code, result);
1585 return result;
1586 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001587
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001588 Object* result = Heap::AllocateRawTwoByteString(1);
1589 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001590 String* answer = String::cast(result);
1591 answer->Set(StringShape(answer), 0, code);
1592 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001593}
1594
1595
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001596Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1597 if (pretenure == NOT_TENURED) {
1598 return AllocateByteArray(length);
1599 }
1600 int size = ByteArray::SizeFor(length);
1601 AllocationSpace space =
1602 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1603
1604 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1605
1606 if (result->IsFailure()) return result;
1607
1608 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1609 reinterpret_cast<Array*>(result)->set_length(length);
1610 return result;
1611}
1612
1613
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614Object* Heap::AllocateByteArray(int length) {
1615 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001616 AllocationSpace space =
1617 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001619 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001620
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621 if (result->IsFailure()) return result;
1622
1623 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1624 reinterpret_cast<Array*>(result)->set_length(length);
1625 return result;
1626}
1627
1628
1629Object* Heap::CreateCode(const CodeDesc& desc,
1630 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001631 Code::Flags flags,
1632 Code** self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 // Compute size
1634 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1635 int sinfo_size = 0;
1636 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1637 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001638 Object* result;
1639 if (obj_size > MaxHeapObjectSize()) {
1640 result = lo_space_->AllocateRawCode(obj_size);
1641 } else {
1642 result = code_space_->AllocateRaw(obj_size);
1643 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001644
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001645 if (result->IsFailure()) return result;
1646
1647 // Initialize the object
1648 HeapObject::cast(result)->set_map(code_map());
1649 Code* code = Code::cast(result);
1650 code->set_instruction_size(desc.instr_size);
1651 code->set_relocation_size(desc.reloc_size);
1652 code->set_sinfo_size(sinfo_size);
1653 code->set_flags(flags);
1654 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001655 // Allow self references to created code object.
1656 if (self_reference != NULL) {
1657 *self_reference = code;
1658 }
1659 // Migrate generated code.
1660 // The generated code can contain Object** values (typically from handles)
1661 // that are dereferenced during the copy to point directly to the actual heap
1662 // objects. These pointers can include references to the code object itself,
1663 // through the self_reference parameter.
1664 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001666 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001667
1668#ifdef DEBUG
1669 code->Verify();
1670#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001671 return code;
1672}
1673
1674
1675Object* Heap::CopyCode(Code* code) {
1676 // Allocate an object the same size as the code object.
1677 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001678 Object* result;
1679 if (obj_size > MaxHeapObjectSize()) {
1680 result = lo_space_->AllocateRawCode(obj_size);
1681 } else {
1682 result = code_space_->AllocateRaw(obj_size);
1683 }
1684
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001685 if (result->IsFailure()) return result;
1686
1687 // Copy code object.
1688 Address old_addr = code->address();
1689 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001690 CopyBlock(reinterpret_cast<Object**>(new_addr),
1691 reinterpret_cast<Object**>(old_addr),
1692 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001693 // Relocate the copy.
1694 Code* new_code = Code::cast(result);
1695 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001696 return new_code;
1697}
1698
1699
1700Object* Heap::Allocate(Map* map, AllocationSpace space) {
1701 ASSERT(gc_state_ == NOT_IN_GC);
1702 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001703 Object* result = AllocateRaw(map->instance_size(),
1704 space,
1705 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 if (result->IsFailure()) return result;
1707 HeapObject::cast(result)->set_map(map);
1708 return result;
1709}
1710
1711
1712Object* Heap::InitializeFunction(JSFunction* function,
1713 SharedFunctionInfo* shared,
1714 Object* prototype) {
1715 ASSERT(!prototype->IsMap());
1716 function->initialize_properties();
1717 function->initialize_elements();
1718 function->set_shared(shared);
1719 function->set_prototype_or_initial_map(prototype);
1720 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001721 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 return function;
1723}
1724
1725
1726Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1727 // Allocate the prototype.
1728 Object* prototype =
1729 AllocateJSObject(Top::context()->global_context()->object_function());
1730 if (prototype->IsFailure()) return prototype;
1731 // When creating the prototype for the function we must set its
1732 // constructor to the function.
1733 Object* result =
1734 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1735 function,
1736 DONT_ENUM);
1737 if (result->IsFailure()) return result;
1738 return prototype;
1739}
1740
1741
1742Object* Heap::AllocateFunction(Map* function_map,
1743 SharedFunctionInfo* shared,
1744 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001745 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001746 if (result->IsFailure()) return result;
1747 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1748}
1749
1750
1751Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001752 // To get fast allocation and map sharing for arguments objects we
1753 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754
1755 // This calls Copy directly rather than using Heap::AllocateRaw so we
1756 // duplicate the check here.
1757 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1758
1759 JSObject* boilerplate =
1760 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001761
1762 // Make the clone.
1763 Map* map = boilerplate->map();
1764 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001765 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001766 if (result->IsFailure()) return result;
1767
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001768 // Copy the content. The arguments boilerplate doesn't have any
1769 // fields that point to new space so it's safe to skip the write
1770 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001771 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1772 reinterpret_cast<Object**>(boilerplate->address()),
1773 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001774
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001775 // Set the two properties.
1776 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001777 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001778 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1779 Smi::FromInt(length),
1780 SKIP_WRITE_BARRIER);
1781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782 // Check the state of the object
1783 ASSERT(JSObject::cast(result)->HasFastProperties());
1784 ASSERT(JSObject::cast(result)->HasFastElements());
1785
1786 return result;
1787}
1788
1789
1790Object* Heap::AllocateInitialMap(JSFunction* fun) {
1791 ASSERT(!fun->has_initial_map());
1792
ager@chromium.org7c537e22008-10-16 08:43:32 +00001793 // First create a new map with the expected number of properties being
1794 // allocated in-object.
1795 int expected_nof_properties = fun->shared()->expected_nof_properties();
1796 int instance_size = JSObject::kHeaderSize +
1797 expected_nof_properties * kPointerSize;
1798 if (instance_size > JSObject::kMaxInstanceSize) {
1799 instance_size = JSObject::kMaxInstanceSize;
1800 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1801 kPointerSize;
1802 }
1803 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001804 if (map_obj->IsFailure()) return map_obj;
1805
1806 // Fetch or allocate prototype.
1807 Object* prototype;
1808 if (fun->has_instance_prototype()) {
1809 prototype = fun->instance_prototype();
1810 } else {
1811 prototype = AllocateFunctionPrototype(fun);
1812 if (prototype->IsFailure()) return prototype;
1813 }
1814 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001815 map->set_inobject_properties(expected_nof_properties);
1816 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001817 map->set_prototype(prototype);
1818 return map;
1819}
1820
1821
1822void Heap::InitializeJSObjectFromMap(JSObject* obj,
1823 FixedArray* properties,
1824 Map* map) {
1825 obj->set_properties(properties);
1826 obj->initialize_elements();
1827 // TODO(1240798): Initialize the object's body using valid initial values
1828 // according to the object's initial map. For example, if the map's
1829 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1830 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1831 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1832 // verification code has to cope with (temporarily) invalid objects. See
1833 // for example, JSArray::JSArrayVerify).
1834 obj->InitializeBody(map->instance_size());
1835}
1836
1837
1838Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1839 // JSFunctions should be allocated using AllocateFunction to be
1840 // properly initialized.
1841 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1842
1843 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001844 int prop_size = map->unused_property_fields() - map->inobject_properties();
1845 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001846 if (properties->IsFailure()) return properties;
1847
1848 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001849 AllocationSpace space =
1850 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001851 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1852 Object* obj = Allocate(map, space);
1853 if (obj->IsFailure()) return obj;
1854
1855 // Initialize the JSObject.
1856 InitializeJSObjectFromMap(JSObject::cast(obj),
1857 FixedArray::cast(properties),
1858 map);
1859 return obj;
1860}
1861
1862
1863Object* Heap::AllocateJSObject(JSFunction* constructor,
1864 PretenureFlag pretenure) {
1865 // Allocate the initial map if absent.
1866 if (!constructor->has_initial_map()) {
1867 Object* initial_map = AllocateInitialMap(constructor);
1868 if (initial_map->IsFailure()) return initial_map;
1869 constructor->set_initial_map(Map::cast(initial_map));
1870 Map::cast(initial_map)->set_constructor(constructor);
1871 }
1872 // Allocate the object based on the constructors initial map.
1873 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1874}
1875
1876
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001877Object* Heap::CopyJSObject(JSObject* source) {
1878 // Never used to copy functions. If functions need to be copied we
1879 // have to be careful to clear the literals array.
1880 ASSERT(!source->IsJSFunction());
1881
1882 // Make the clone.
1883 Map* map = source->map();
1884 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001885 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001886
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001887 // If we're forced to always allocate, we use the general allocation
1888 // functions which may leave us with an object in old space.
1889 if (always_allocate()) {
1890 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1891 if (clone->IsFailure()) return clone;
1892 Address clone_address = HeapObject::cast(clone)->address();
1893 CopyBlock(reinterpret_cast<Object**>(clone_address),
1894 reinterpret_cast<Object**>(source->address()),
1895 object_size);
1896 // Update write barrier for all fields that lie beyond the header.
1897 for (int offset = JSObject::kHeaderSize;
1898 offset < object_size;
1899 offset += kPointerSize) {
1900 RecordWrite(clone_address, offset);
1901 }
1902 } else {
1903 clone = new_space_.AllocateRaw(object_size);
1904 if (clone->IsFailure()) return clone;
1905 ASSERT(Heap::InNewSpace(clone));
1906 // Since we know the clone is allocated in new space, we can copy
1907 // the contents without worring about updating the write barrier.
1908 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1909 reinterpret_cast<Object**>(source->address()),
1910 object_size);
1911 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001912
1913 FixedArray* elements = FixedArray::cast(source->elements());
1914 FixedArray* properties = FixedArray::cast(source->properties());
1915 // Update elements if necessary.
1916 if (elements->length()> 0) {
1917 Object* elem = CopyFixedArray(elements);
1918 if (elem->IsFailure()) return elem;
1919 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1920 }
1921 // Update properties if necessary.
1922 if (properties->length() > 0) {
1923 Object* prop = CopyFixedArray(properties);
1924 if (prop->IsFailure()) return prop;
1925 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1926 }
1927 // Return the new clone.
1928 return clone;
1929}
1930
1931
1932Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1933 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001934 // Allocate initial map if absent.
1935 if (!constructor->has_initial_map()) {
1936 Object* initial_map = AllocateInitialMap(constructor);
1937 if (initial_map->IsFailure()) return initial_map;
1938 constructor->set_initial_map(Map::cast(initial_map));
1939 Map::cast(initial_map)->set_constructor(constructor);
1940 }
1941
1942 Map* map = constructor->initial_map();
1943
1944 // Check that the already allocated object has the same size as
1945 // objects allocated using the constructor.
1946 ASSERT(map->instance_size() == object->map()->instance_size());
1947
1948 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001949 int prop_size = map->unused_property_fields() - map->inobject_properties();
1950 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001951 if (properties->IsFailure()) return properties;
1952
1953 // Reset the map for the object.
1954 object->set_map(constructor->initial_map());
1955
1956 // Reinitialize the object from the constructor map.
1957 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1958 return object;
1959}
1960
1961
1962Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1963 PretenureFlag pretenure) {
1964 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1965 if (result->IsFailure()) return result;
1966
1967 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001968 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001969 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001970 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001971 }
1972 return result;
1973}
1974
1975
1976Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1977 PretenureFlag pretenure) {
1978 // Count the number of characters in the UTF-8 string and check if
1979 // it is an ASCII string.
1980 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1981 decoder->Reset(string.start(), string.length());
1982 int chars = 0;
1983 bool is_ascii = true;
1984 while (decoder->has_more()) {
1985 uc32 r = decoder->GetNext();
1986 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1987 chars++;
1988 }
1989
1990 // If the string is ascii, we do not need to convert the characters
1991 // since UTF8 is backwards compatible with ascii.
1992 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1993
1994 Object* result = AllocateRawTwoByteString(chars, pretenure);
1995 if (result->IsFailure()) return result;
1996
1997 // Convert and copy the characters into the new object.
1998 String* string_result = String::cast(result);
1999 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00002000 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002001 for (int i = 0; i < chars; i++) {
2002 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00002003 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002004 }
2005 return result;
2006}
2007
2008
2009Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2010 PretenureFlag pretenure) {
2011 // Check if the string is an ASCII string.
2012 int i = 0;
2013 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2014
2015 Object* result;
2016 if (i == string.length()) { // It's an ASCII string.
2017 result = AllocateRawAsciiString(string.length(), pretenure);
2018 } else { // It's not an ASCII string.
2019 result = AllocateRawTwoByteString(string.length(), pretenure);
2020 }
2021 if (result->IsFailure()) return result;
2022
2023 // Copy the characters into the new object, which may be either ASCII or
2024 // UTF-16.
2025 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002026 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002027 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002028 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002029 }
2030 return result;
2031}
2032
2033
2034Map* Heap::SymbolMapForString(String* string) {
2035 // If the string is in new space it cannot be used as a symbol.
2036 if (InNewSpace(string)) return NULL;
2037
2038 // Find the corresponding symbol map for strings.
2039 Map* map = string->map();
2040
2041 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2042 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2043 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2044
2045 if (map == short_string_map()) return short_symbol_map();
2046 if (map == medium_string_map()) return medium_symbol_map();
2047 if (map == long_string_map()) return long_symbol_map();
2048
2049 if (map == short_cons_string_map()) return short_cons_symbol_map();
2050 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2051 if (map == long_cons_string_map()) return long_cons_symbol_map();
2052
2053 if (map == short_cons_ascii_string_map()) {
2054 return short_cons_ascii_symbol_map();
2055 }
2056 if (map == medium_cons_ascii_string_map()) {
2057 return medium_cons_ascii_symbol_map();
2058 }
2059 if (map == long_cons_ascii_string_map()) {
2060 return long_cons_ascii_symbol_map();
2061 }
2062
2063 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002064 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2065 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002066
2067 if (map == short_sliced_ascii_string_map()) {
2068 return short_sliced_ascii_symbol_map();
2069 }
2070 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002071 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002072 }
2073 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002074 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002075 }
2076
2077 if (map == short_external_string_map()) return short_external_string_map();
2078 if (map == medium_external_string_map()) return medium_external_string_map();
2079 if (map == long_external_string_map()) return long_external_string_map();
2080
2081 if (map == short_external_ascii_string_map()) {
2082 return short_external_ascii_string_map();
2083 }
2084 if (map == medium_external_ascii_string_map()) {
2085 return medium_external_ascii_string_map();
2086 }
2087 if (map == long_external_ascii_string_map()) {
2088 return long_external_ascii_string_map();
2089 }
2090
2091 // No match found.
2092 return NULL;
2093}
2094
2095
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002096Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2097 int chars,
2098 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002099 // Ensure the chars matches the number of characters in the buffer.
2100 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2101 // Determine whether the string is ascii.
2102 bool is_ascii = true;
2103 while (buffer->has_more()) {
2104 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2105 }
2106 buffer->Rewind();
2107
2108 // Compute map and object size.
2109 int size;
2110 Map* map;
2111
2112 if (is_ascii) {
2113 if (chars <= String::kMaxShortStringSize) {
2114 map = short_ascii_symbol_map();
2115 } else if (chars <= String::kMaxMediumStringSize) {
2116 map = medium_ascii_symbol_map();
2117 } else {
2118 map = long_ascii_symbol_map();
2119 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002120 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002121 } else {
2122 if (chars <= String::kMaxShortStringSize) {
2123 map = short_symbol_map();
2124 } else if (chars <= String::kMaxMediumStringSize) {
2125 map = medium_symbol_map();
2126 } else {
2127 map = long_symbol_map();
2128 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002129 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002130 }
2131
2132 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002133 AllocationSpace space =
2134 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002135 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002136 if (result->IsFailure()) return result;
2137
2138 reinterpret_cast<HeapObject*>(result)->set_map(map);
2139 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002140 String* answer = String::cast(result);
2141 StringShape answer_shape(answer);
2142 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002143
ager@chromium.org870a0b62008-11-04 11:43:05 +00002144 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002145
2146 // Fill in the characters.
2147 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002148 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002149 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002150 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002151}
2152
2153
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002154// External string resource that only contains a length field. These
2155// are used temporarily when allocating external symbols.
2156class DummyExternalStringResource
2157 : public v8::String::ExternalStringResource {
2158 public:
2159 explicit DummyExternalStringResource(size_t length) : length_(length) { }
2160
2161 virtual const uint16_t* data() const {
2162 UNREACHABLE();
2163 return NULL;
2164 }
2165
2166 virtual size_t length() const { return length_; }
2167 private:
2168 size_t length_;
2169};
2170
2171
2172Object* Heap::AllocateExternalSymbol(Vector<const char> string, int chars) {
2173 // Attempt to allocate the resulting external string first. Use a
2174 // dummy string resource that has the correct length so that we only
2175 // have to patch the external string resource after the callback.
2176 DummyExternalStringResource dummy_resource(chars);
2177 Object* obj = AllocateExternalSymbolFromTwoByte(&dummy_resource);
2178 if (obj->IsFailure()) return obj;
2179 // Perform callback.
2180 v8::String::ExternalStringResource* resource =
2181 global_external_symbol_callback_(string.start(), string.length());
2182 // Patch the resource pointer of the result.
2183 ExternalTwoByteString* result = ExternalTwoByteString::cast(obj);
2184 result->set_resource(resource);
2185 // Force hash code to be computed.
2186 result->Hash();
2187 ASSERT(result->IsEqualTo(string));
2188 return result;
2189}
2190
2191
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002192Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002193 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002194 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002195 if (size > MaxHeapObjectSize()) {
2196 space = LO_SPACE;
2197 }
2198
2199 // Use AllocateRaw rather than Allocate because the object's size cannot be
2200 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002201 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002202 if (result->IsFailure()) return result;
2203
2204 // Determine the map based on the string's length.
2205 Map* map;
2206 if (length <= String::kMaxShortStringSize) {
2207 map = short_ascii_string_map();
2208 } else if (length <= String::kMaxMediumStringSize) {
2209 map = medium_ascii_string_map();
2210 } else {
2211 map = long_ascii_string_map();
2212 }
2213
2214 // Partially initialize the object.
2215 HeapObject::cast(result)->set_map(map);
2216 String::cast(result)->set_length(length);
2217 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2218 return result;
2219}
2220
2221
2222Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002223 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002224 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002225 if (size > MaxHeapObjectSize()) {
2226 space = LO_SPACE;
2227 }
2228
2229 // Use AllocateRaw rather than Allocate because the object's size cannot be
2230 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002231 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002232 if (result->IsFailure()) return result;
2233
2234 // Determine the map based on the string's length.
2235 Map* map;
2236 if (length <= String::kMaxShortStringSize) {
2237 map = short_string_map();
2238 } else if (length <= String::kMaxMediumStringSize) {
2239 map = medium_string_map();
2240 } else {
2241 map = long_string_map();
2242 }
2243
2244 // Partially initialize the object.
2245 HeapObject::cast(result)->set_map(map);
2246 String::cast(result)->set_length(length);
2247 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2248 return result;
2249}
2250
2251
2252Object* Heap::AllocateEmptyFixedArray() {
2253 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002254 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002255 if (result->IsFailure()) return result;
2256 // Initialize the object.
2257 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2258 reinterpret_cast<Array*>(result)->set_length(0);
2259 return result;
2260}
2261
2262
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002263Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002264 // Use the general function if we're forced to always allocate.
2265 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002266 // Allocate the raw data for a fixed array.
2267 int size = FixedArray::SizeFor(length);
2268 return (size > MaxHeapObjectSize())
2269 ? lo_space_->AllocateRawFixedArray(size)
2270 : new_space_.AllocateRaw(size);
2271}
2272
2273
2274Object* Heap::CopyFixedArray(FixedArray* src) {
2275 int len = src->length();
2276 Object* obj = AllocateRawFixedArray(len);
2277 if (obj->IsFailure()) return obj;
2278 if (Heap::InNewSpace(obj)) {
2279 HeapObject* dst = HeapObject::cast(obj);
2280 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2281 reinterpret_cast<Object**>(src->address()),
2282 FixedArray::SizeFor(len));
2283 return obj;
2284 }
2285 HeapObject::cast(obj)->set_map(src->map());
2286 FixedArray* result = FixedArray::cast(obj);
2287 result->set_length(len);
2288 // Copy the content
2289 WriteBarrierMode mode = result->GetWriteBarrierMode();
2290 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2291 return result;
2292}
2293
2294
2295Object* Heap::AllocateFixedArray(int length) {
2296 Object* result = AllocateRawFixedArray(length);
2297 if (!result->IsFailure()) {
2298 // Initialize header.
2299 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2300 FixedArray* array = FixedArray::cast(result);
2301 array->set_length(length);
2302 Object* value = undefined_value();
2303 // Initialize body.
2304 for (int index = 0; index < length; index++) {
2305 array->set(index, value, SKIP_WRITE_BARRIER);
2306 }
2307 }
2308 return result;
2309}
2310
2311
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002312Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2313 ASSERT(empty_fixed_array()->IsFixedArray());
2314 if (length == 0) return empty_fixed_array();
2315
2316 int size = FixedArray::SizeFor(length);
2317 Object* result;
2318 if (size > MaxHeapObjectSize()) {
2319 result = lo_space_->AllocateRawFixedArray(size);
2320 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002321 AllocationSpace space =
2322 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002323 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002324 }
2325 if (result->IsFailure()) return result;
2326
2327 // Initialize the object.
2328 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2329 FixedArray* array = FixedArray::cast(result);
2330 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002331 Object* value = undefined_value();
2332 for (int index = 0; index < length; index++) {
2333 array->set(index, value, SKIP_WRITE_BARRIER);
2334 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002335 return array;
2336}
2337
2338
2339Object* Heap::AllocateFixedArrayWithHoles(int length) {
2340 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002341 Object* result = AllocateRawFixedArray(length);
2342 if (!result->IsFailure()) {
2343 // Initialize header.
2344 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2345 FixedArray* array = FixedArray::cast(result);
2346 array->set_length(length);
2347 // Initialize body.
2348 Object* value = the_hole_value();
2349 for (int index = 0; index < length; index++) {
2350 array->set(index, value, SKIP_WRITE_BARRIER);
2351 }
2352 }
2353 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002354}
2355
2356
2357Object* Heap::AllocateHashTable(int length) {
2358 Object* result = Heap::AllocateFixedArray(length);
2359 if (result->IsFailure()) return result;
2360 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2361 ASSERT(result->IsDictionary());
2362 return result;
2363}
2364
2365
2366Object* Heap::AllocateGlobalContext() {
2367 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2368 if (result->IsFailure()) return result;
2369 Context* context = reinterpret_cast<Context*>(result);
2370 context->set_map(global_context_map());
2371 ASSERT(context->IsGlobalContext());
2372 ASSERT(result->IsContext());
2373 return result;
2374}
2375
2376
2377Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2378 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2379 Object* result = Heap::AllocateFixedArray(length);
2380 if (result->IsFailure()) return result;
2381 Context* context = reinterpret_cast<Context*>(result);
2382 context->set_map(context_map());
2383 context->set_closure(function);
2384 context->set_fcontext(context);
2385 context->set_previous(NULL);
2386 context->set_extension(NULL);
2387 context->set_global(function->context()->global());
2388 ASSERT(!context->IsGlobalContext());
2389 ASSERT(context->is_function_context());
2390 ASSERT(result->IsContext());
2391 return result;
2392}
2393
2394
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002395Object* Heap::AllocateWithContext(Context* previous,
2396 JSObject* extension,
2397 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002398 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2399 if (result->IsFailure()) return result;
2400 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002401 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002402 context->set_closure(previous->closure());
2403 context->set_fcontext(previous->fcontext());
2404 context->set_previous(previous);
2405 context->set_extension(extension);
2406 context->set_global(previous->global());
2407 ASSERT(!context->IsGlobalContext());
2408 ASSERT(!context->is_function_context());
2409 ASSERT(result->IsContext());
2410 return result;
2411}
2412
2413
2414Object* Heap::AllocateStruct(InstanceType type) {
2415 Map* map;
2416 switch (type) {
2417#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2418STRUCT_LIST(MAKE_CASE)
2419#undef MAKE_CASE
2420 default:
2421 UNREACHABLE();
2422 return Failure::InternalError();
2423 }
2424 int size = map->instance_size();
2425 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002426 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002427 Object* result = Heap::Allocate(map, space);
2428 if (result->IsFailure()) return result;
2429 Struct::cast(result)->InitializeBody(size);
2430 return result;
2431}
2432
2433
2434#ifdef DEBUG
2435
2436void Heap::Print() {
2437 if (!HasBeenSetup()) return;
2438 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002439 AllSpaces spaces;
2440 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002441}
2442
2443
2444void Heap::ReportCodeStatistics(const char* title) {
2445 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2446 PagedSpace::ResetCodeStatistics();
2447 // We do not look for code in new space, map space, or old space. If code
2448 // somehow ends up in those spaces, we would miss it here.
2449 code_space_->CollectCodeStatistics();
2450 lo_space_->CollectCodeStatistics();
2451 PagedSpace::ReportCodeStatistics();
2452}
2453
2454
2455// This function expects that NewSpace's allocated objects histogram is
2456// populated (via a call to CollectStatistics or else as a side effect of a
2457// just-completed scavenge collection).
2458void Heap::ReportHeapStatistics(const char* title) {
2459 USE(title);
2460 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2461 title, gc_count_);
2462 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002463 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2464 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002465
2466 PrintF("\n");
2467 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2468 GlobalHandles::PrintStats();
2469 PrintF("\n");
2470
2471 PrintF("Heap statistics : ");
2472 MemoryAllocator::ReportStatistics();
2473 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002474 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002475 PrintF("Old pointer space : ");
2476 old_pointer_space_->ReportStatistics();
2477 PrintF("Old data space : ");
2478 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002479 PrintF("Code space : ");
2480 code_space_->ReportStatistics();
2481 PrintF("Map space : ");
2482 map_space_->ReportStatistics();
2483 PrintF("Large object space : ");
2484 lo_space_->ReportStatistics();
2485 PrintF(">>>>>> ========================================= >>>>>>\n");
2486}
2487
2488#endif // DEBUG
2489
2490bool Heap::Contains(HeapObject* value) {
2491 return Contains(value->address());
2492}
2493
2494
2495bool Heap::Contains(Address addr) {
2496 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2497 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002498 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002499 old_pointer_space_->Contains(addr) ||
2500 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002501 code_space_->Contains(addr) ||
2502 map_space_->Contains(addr) ||
2503 lo_space_->SlowContains(addr));
2504}
2505
2506
2507bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2508 return InSpace(value->address(), space);
2509}
2510
2511
2512bool Heap::InSpace(Address addr, AllocationSpace space) {
2513 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2514 if (!HasBeenSetup()) return false;
2515
2516 switch (space) {
2517 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002518 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002519 case OLD_POINTER_SPACE:
2520 return old_pointer_space_->Contains(addr);
2521 case OLD_DATA_SPACE:
2522 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002523 case CODE_SPACE:
2524 return code_space_->Contains(addr);
2525 case MAP_SPACE:
2526 return map_space_->Contains(addr);
2527 case LO_SPACE:
2528 return lo_space_->SlowContains(addr);
2529 }
2530
2531 return false;
2532}
2533
2534
2535#ifdef DEBUG
2536void Heap::Verify() {
2537 ASSERT(HasBeenSetup());
2538
2539 VerifyPointersVisitor visitor;
2540 Heap::IterateRoots(&visitor);
2541
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002542 AllSpaces spaces;
2543 while (Space* space = spaces.next()) {
2544 space->Verify();
2545 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002546}
2547#endif // DEBUG
2548
2549
2550Object* Heap::LookupSymbol(Vector<const char> string) {
2551 Object* symbol = NULL;
2552 Object* new_table =
2553 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2554 if (new_table->IsFailure()) return new_table;
2555 symbol_table_ = new_table;
2556 ASSERT(symbol != NULL);
2557 return symbol;
2558}
2559
2560
2561Object* Heap::LookupSymbol(String* string) {
2562 if (string->IsSymbol()) return string;
2563 Object* symbol = NULL;
2564 Object* new_table =
2565 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2566 if (new_table->IsFailure()) return new_table;
2567 symbol_table_ = new_table;
2568 ASSERT(symbol != NULL);
2569 return symbol;
2570}
2571
2572
ager@chromium.org7c537e22008-10-16 08:43:32 +00002573bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2574 if (string->IsSymbol()) {
2575 *symbol = string;
2576 return true;
2577 }
2578 SymbolTable* table = SymbolTable::cast(symbol_table_);
2579 return table->LookupSymbolIfExists(string, symbol);
2580}
2581
2582
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002583#ifdef DEBUG
2584void Heap::ZapFromSpace() {
2585 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002586 for (Address a = new_space_.FromSpaceLow();
2587 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002588 a += kPointerSize) {
2589 Memory::Address_at(a) = kFromSpaceZapValue;
2590 }
2591}
2592#endif // DEBUG
2593
2594
2595void Heap::IterateRSetRange(Address object_start,
2596 Address object_end,
2597 Address rset_start,
2598 ObjectSlotCallback copy_object_func) {
2599 Address object_address = object_start;
2600 Address rset_address = rset_start;
2601
2602 // Loop over all the pointers in [object_start, object_end).
2603 while (object_address < object_end) {
2604 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002605 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002606 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002607 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002608 // Do not dereference pointers at or past object_end.
2609 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2610 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002611 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002612 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2613 }
2614 // If this pointer does not need to be remembered anymore, clear
2615 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002616 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002617 }
2618 object_address += kPointerSize;
2619 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002620 // Update the remembered set if it has changed.
2621 if (result_rset != rset_word) {
2622 Memory::uint32_at(rset_address) = result_rset;
2623 }
2624 } else {
2625 // No bits in the word were set. This is the common case.
2626 object_address += kPointerSize * kBitsPerInt;
2627 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002628 rset_address += kIntSize;
2629 }
2630}
2631
2632
2633void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2634 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002635 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002636
2637 PageIterator it(space, PageIterator::PAGES_IN_USE);
2638 while (it.has_next()) {
2639 Page* page = it.next();
2640 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2641 page->RSetStart(), copy_object_func);
2642 }
2643}
2644
2645
2646#ifdef DEBUG
2647#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2648#else
2649#define SYNCHRONIZE_TAG(tag)
2650#endif
2651
2652void Heap::IterateRoots(ObjectVisitor* v) {
2653 IterateStrongRoots(v);
2654 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2655 SYNCHRONIZE_TAG("symbol_table");
2656}
2657
2658
2659void Heap::IterateStrongRoots(ObjectVisitor* v) {
2660#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002661 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002662 STRONG_ROOT_LIST(ROOT_ITERATE);
2663#undef ROOT_ITERATE
2664 SYNCHRONIZE_TAG("strong_root_list");
2665
2666#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002667 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002668 STRUCT_LIST(STRUCT_MAP_ITERATE);
2669#undef STRUCT_MAP_ITERATE
2670 SYNCHRONIZE_TAG("struct_map");
2671
2672#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002673 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002674 SYMBOL_LIST(SYMBOL_ITERATE)
2675#undef SYMBOL_ITERATE
2676 SYNCHRONIZE_TAG("symbol");
2677
2678 Bootstrapper::Iterate(v);
2679 SYNCHRONIZE_TAG("bootstrapper");
2680 Top::Iterate(v);
2681 SYNCHRONIZE_TAG("top");
2682 Debug::Iterate(v);
2683 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002684 CompilationCache::Iterate(v);
2685 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002686
2687 // Iterate over local handles in handle scopes.
2688 HandleScopeImplementer::Iterate(v);
2689 SYNCHRONIZE_TAG("handlescope");
2690
2691 // Iterate over the builtin code objects and code stubs in the heap. Note
2692 // that it is not strictly necessary to iterate over code objects on
2693 // scavenge collections. We still do it here because this same function
2694 // is used by the mark-sweep collector and the deserializer.
2695 Builtins::IterateBuiltins(v);
2696 SYNCHRONIZE_TAG("builtins");
2697
2698 // Iterate over global handles.
2699 GlobalHandles::IterateRoots(v);
2700 SYNCHRONIZE_TAG("globalhandles");
2701
2702 // Iterate over pointers being held by inactive threads.
2703 ThreadManager::Iterate(v);
2704 SYNCHRONIZE_TAG("threadmanager");
2705}
2706#undef SYNCHRONIZE_TAG
2707
2708
2709// Flag is set when the heap has been configured. The heap can be repeatedly
2710// configured through the API until it is setup.
2711static bool heap_configured = false;
2712
2713// TODO(1236194): Since the heap size is configurable on the command line
2714// and through the API, we should gracefully handle the case that the heap
2715// size is not big enough to fit all the initial objects.
2716bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2717 if (HasBeenSetup()) return false;
2718
2719 if (semispace_size > 0) semispace_size_ = semispace_size;
2720 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2721
2722 // The new space size must be a power of two to support single-bit testing
2723 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002724 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002725 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2726 young_generation_size_ = 2 * semispace_size_;
2727
2728 // The old generation is paged.
2729 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2730
2731 heap_configured = true;
2732 return true;
2733}
2734
2735
kasper.lund7276f142008-07-30 08:49:36 +00002736bool Heap::ConfigureHeapDefault() {
2737 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2738}
2739
2740
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002741int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002742 return old_pointer_space_->Size()
2743 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002744 + code_space_->Size()
2745 + map_space_->Size()
2746 + lo_space_->Size();
2747}
2748
2749
kasper.lund7276f142008-07-30 08:49:36 +00002750int Heap::PromotedExternalMemorySize() {
2751 if (amount_of_external_allocated_memory_
2752 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2753 return amount_of_external_allocated_memory_
2754 - amount_of_external_allocated_memory_at_last_global_gc_;
2755}
2756
2757
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002758bool Heap::Setup(bool create_heap_objects) {
2759 // Initialize heap spaces and initial maps and objects. Whenever something
2760 // goes wrong, just return false. The caller should check the results and
2761 // call Heap::TearDown() to release allocated memory.
2762 //
2763 // If the heap is not yet configured (eg, through the API), configure it.
2764 // Configuration is based on the flags new-space-size (really the semispace
2765 // size) and old-space-size if set or the initial values of semispace_size_
2766 // and old_generation_size_ otherwise.
2767 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002768 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002769 }
2770
2771 // Setup memory allocator and allocate an initial chunk of memory. The
2772 // initial chunk is double the size of the new space to ensure that we can
2773 // find a pair of semispaces that are contiguous and aligned to their size.
2774 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2775 void* chunk
2776 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2777 if (chunk == NULL) return false;
2778
2779 // Put the initial chunk of the old space at the start of the initial
2780 // chunk, then the two new space semispaces, then the initial chunk of
2781 // code space. Align the pair of semispaces to their size, which must be
2782 // a power of 2.
2783 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002784 Address code_space_start = reinterpret_cast<Address>(chunk);
2785 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2786 Address old_space_start = new_space_start + young_generation_size_;
2787 int code_space_size = new_space_start - code_space_start;
2788 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002789
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002790 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002791 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002792
2793 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002794 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002795 old_pointer_space_ =
2796 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2797 if (old_pointer_space_ == NULL) return false;
2798 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2799 return false;
2800 }
2801 old_data_space_ =
2802 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2803 if (old_data_space_ == NULL) return false;
2804 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2805 old_space_size >> 1)) {
2806 return false;
2807 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002808
2809 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002810 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002811 code_space_ =
2812 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002813 if (code_space_ == NULL) return false;
2814 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2815
2816 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002817 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002818 if (map_space_ == NULL) return false;
2819 // Setting up a paged space without giving it a virtual memory range big
2820 // enough to hold at least a page will cause it to allocate.
2821 if (!map_space_->Setup(NULL, 0)) return false;
2822
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002823 // The large object code space may contain code or data. We set the memory
2824 // to be non-executable here for safety, but this means we need to enable it
2825 // explicitly when allocating large code objects.
2826 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002827 if (lo_space_ == NULL) return false;
2828 if (!lo_space_->Setup()) return false;
2829
2830 if (create_heap_objects) {
2831 // Create initial maps.
2832 if (!CreateInitialMaps()) return false;
2833 if (!CreateApiObjects()) return false;
2834
2835 // Create initial objects
2836 if (!CreateInitialObjects()) return false;
2837 }
2838
2839 LOG(IntEvent("heap-capacity", Capacity()));
2840 LOG(IntEvent("heap-available", Available()));
2841
2842 return true;
2843}
2844
2845
2846void Heap::TearDown() {
2847 GlobalHandles::TearDown();
2848
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002849 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002850
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002851 if (old_pointer_space_ != NULL) {
2852 old_pointer_space_->TearDown();
2853 delete old_pointer_space_;
2854 old_pointer_space_ = NULL;
2855 }
2856
2857 if (old_data_space_ != NULL) {
2858 old_data_space_->TearDown();
2859 delete old_data_space_;
2860 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002861 }
2862
2863 if (code_space_ != NULL) {
2864 code_space_->TearDown();
2865 delete code_space_;
2866 code_space_ = NULL;
2867 }
2868
2869 if (map_space_ != NULL) {
2870 map_space_->TearDown();
2871 delete map_space_;
2872 map_space_ = NULL;
2873 }
2874
2875 if (lo_space_ != NULL) {
2876 lo_space_->TearDown();
2877 delete lo_space_;
2878 lo_space_ = NULL;
2879 }
2880
2881 MemoryAllocator::TearDown();
2882}
2883
2884
2885void Heap::Shrink() {
2886 // Try to shrink map, old, and code spaces.
2887 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002888 old_pointer_space_->Shrink();
2889 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002890 code_space_->Shrink();
2891}
2892
2893
2894#ifdef DEBUG
2895
2896class PrintHandleVisitor: public ObjectVisitor {
2897 public:
2898 void VisitPointers(Object** start, Object** end) {
2899 for (Object** p = start; p < end; p++)
2900 PrintF(" handle %p to %p\n", p, *p);
2901 }
2902};
2903
2904void Heap::PrintHandles() {
2905 PrintF("Handles:\n");
2906 PrintHandleVisitor v;
2907 HandleScopeImplementer::Iterate(&v);
2908}
2909
2910#endif
2911
2912
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002913Space* AllSpaces::next() {
2914 switch (counter_++) {
2915 case NEW_SPACE:
2916 return Heap::new_space();
2917 case OLD_POINTER_SPACE:
2918 return Heap::old_pointer_space();
2919 case OLD_DATA_SPACE:
2920 return Heap::old_data_space();
2921 case CODE_SPACE:
2922 return Heap::code_space();
2923 case MAP_SPACE:
2924 return Heap::map_space();
2925 case LO_SPACE:
2926 return Heap::lo_space();
2927 default:
2928 return NULL;
2929 }
2930}
2931
2932
2933PagedSpace* PagedSpaces::next() {
2934 switch (counter_++) {
2935 case OLD_POINTER_SPACE:
2936 return Heap::old_pointer_space();
2937 case OLD_DATA_SPACE:
2938 return Heap::old_data_space();
2939 case CODE_SPACE:
2940 return Heap::code_space();
2941 case MAP_SPACE:
2942 return Heap::map_space();
2943 default:
2944 return NULL;
2945 }
2946}
2947
2948
2949
2950OldSpace* OldSpaces::next() {
2951 switch (counter_++) {
2952 case OLD_POINTER_SPACE:
2953 return Heap::old_pointer_space();
2954 case OLD_DATA_SPACE:
2955 return Heap::old_data_space();
2956 case CODE_SPACE:
2957 return Heap::code_space();
2958 default:
2959 return NULL;
2960 }
2961}
2962
2963
kasper.lund7276f142008-07-30 08:49:36 +00002964SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2965}
2966
2967
2968SpaceIterator::~SpaceIterator() {
2969 // Delete active iterator if any.
2970 delete iterator_;
2971}
2972
2973
2974bool SpaceIterator::has_next() {
2975 // Iterate until no more spaces.
2976 return current_space_ != LAST_SPACE;
2977}
2978
2979
2980ObjectIterator* SpaceIterator::next() {
2981 if (iterator_ != NULL) {
2982 delete iterator_;
2983 iterator_ = NULL;
2984 // Move to the next space
2985 current_space_++;
2986 if (current_space_ > LAST_SPACE) {
2987 return NULL;
2988 }
2989 }
2990
2991 // Return iterator for the new current space.
2992 return CreateIterator();
2993}
2994
2995
2996// Create an iterator for the space to iterate.
2997ObjectIterator* SpaceIterator::CreateIterator() {
2998 ASSERT(iterator_ == NULL);
2999
3000 switch (current_space_) {
3001 case NEW_SPACE:
3002 iterator_ = new SemiSpaceIterator(Heap::new_space());
3003 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003004 case OLD_POINTER_SPACE:
3005 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3006 break;
3007 case OLD_DATA_SPACE:
3008 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003009 break;
3010 case CODE_SPACE:
3011 iterator_ = new HeapObjectIterator(Heap::code_space());
3012 break;
3013 case MAP_SPACE:
3014 iterator_ = new HeapObjectIterator(Heap::map_space());
3015 break;
3016 case LO_SPACE:
3017 iterator_ = new LargeObjectIterator(Heap::lo_space());
3018 break;
3019 }
3020
3021 // Return the newly allocated iterator;
3022 ASSERT(iterator_ != NULL);
3023 return iterator_;
3024}
3025
3026
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003027HeapIterator::HeapIterator() {
3028 Init();
3029}
3030
3031
3032HeapIterator::~HeapIterator() {
3033 Shutdown();
3034}
3035
3036
3037void HeapIterator::Init() {
3038 // Start the iteration.
3039 space_iterator_ = new SpaceIterator();
3040 object_iterator_ = space_iterator_->next();
3041}
3042
3043
3044void HeapIterator::Shutdown() {
3045 // Make sure the last iterator is deallocated.
3046 delete space_iterator_;
3047 space_iterator_ = NULL;
3048 object_iterator_ = NULL;
3049}
3050
3051
3052bool HeapIterator::has_next() {
3053 // No iterator means we are done.
3054 if (object_iterator_ == NULL) return false;
3055
3056 if (object_iterator_->has_next_object()) {
3057 // If the current iterator has more objects we are fine.
3058 return true;
3059 } else {
3060 // Go though the spaces looking for one that has objects.
3061 while (space_iterator_->has_next()) {
3062 object_iterator_ = space_iterator_->next();
3063 if (object_iterator_->has_next_object()) {
3064 return true;
3065 }
3066 }
3067 }
3068 // Done with the last space.
3069 object_iterator_ = NULL;
3070 return false;
3071}
3072
3073
3074HeapObject* HeapIterator::next() {
3075 if (has_next()) {
3076 return object_iterator_->next_object();
3077 } else {
3078 return NULL;
3079 }
3080}
3081
3082
3083void HeapIterator::reset() {
3084 // Restart the iterator.
3085 Shutdown();
3086 Init();
3087}
3088
3089
3090//
3091// HeapProfiler class implementation.
3092//
3093#ifdef ENABLE_LOGGING_AND_PROFILING
3094void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3095 InstanceType type = obj->map()->instance_type();
3096 ASSERT(0 <= type && type <= LAST_TYPE);
3097 info[type].increment_number(1);
3098 info[type].increment_bytes(obj->Size());
3099}
3100#endif
3101
3102
3103#ifdef ENABLE_LOGGING_AND_PROFILING
3104void HeapProfiler::WriteSample() {
3105 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3106
3107 HistogramInfo info[LAST_TYPE+1];
3108#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3109 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3110#undef DEF_TYPE_NAME
3111
3112 HeapIterator iterator;
3113 while (iterator.has_next()) {
3114 CollectStats(iterator.next(), info);
3115 }
3116
3117 // Lump all the string types together.
3118 int string_number = 0;
3119 int string_bytes = 0;
3120#define INCREMENT_SIZE(type, size, name) \
3121 string_number += info[type].number(); \
3122 string_bytes += info[type].bytes();
3123 STRING_TYPE_LIST(INCREMENT_SIZE)
3124#undef INCREMENT_SIZE
3125 if (string_bytes > 0) {
3126 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3127 }
3128
3129 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3130 if (info[i].bytes() > 0) {
3131 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3132 info[i].bytes()));
3133 }
3134 }
3135
3136 LOG(HeapSampleEndEvent("Heap", "allocated"));
3137}
3138
3139
3140#endif
3141
3142
3143
3144#ifdef DEBUG
3145
3146static bool search_for_any_global;
3147static Object* search_target;
3148static bool found_target;
3149static List<Object*> object_stack(20);
3150
3151
3152// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3153static const int kMarkTag = 2;
3154
3155static void MarkObjectRecursively(Object** p);
3156class MarkObjectVisitor : public ObjectVisitor {
3157 public:
3158 void VisitPointers(Object** start, Object** end) {
3159 // Copy all HeapObject pointers in [start, end)
3160 for (Object** p = start; p < end; p++) {
3161 if ((*p)->IsHeapObject())
3162 MarkObjectRecursively(p);
3163 }
3164 }
3165};
3166
3167static MarkObjectVisitor mark_visitor;
3168
3169static void MarkObjectRecursively(Object** p) {
3170 if (!(*p)->IsHeapObject()) return;
3171
3172 HeapObject* obj = HeapObject::cast(*p);
3173
3174 Object* map = obj->map();
3175
3176 if (!map->IsHeapObject()) return; // visited before
3177
3178 if (found_target) return; // stop if target found
3179 object_stack.Add(obj);
3180 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3181 (!search_for_any_global && (obj == search_target))) {
3182 found_target = true;
3183 return;
3184 }
3185
3186 if (obj->IsCode()) {
3187 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3188 }
3189
3190 // not visited yet
3191 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3192
3193 Address map_addr = map_p->address();
3194
3195 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3196
3197 MarkObjectRecursively(&map);
3198
3199 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3200 &mark_visitor);
3201
3202 if (!found_target) // don't pop if found the target
3203 object_stack.RemoveLast();
3204}
3205
3206
3207static void UnmarkObjectRecursively(Object** p);
3208class UnmarkObjectVisitor : public ObjectVisitor {
3209 public:
3210 void VisitPointers(Object** start, Object** end) {
3211 // Copy all HeapObject pointers in [start, end)
3212 for (Object** p = start; p < end; p++) {
3213 if ((*p)->IsHeapObject())
3214 UnmarkObjectRecursively(p);
3215 }
3216 }
3217};
3218
3219static UnmarkObjectVisitor unmark_visitor;
3220
3221static void UnmarkObjectRecursively(Object** p) {
3222 if (!(*p)->IsHeapObject()) return;
3223
3224 HeapObject* obj = HeapObject::cast(*p);
3225
3226 Object* map = obj->map();
3227
3228 if (map->IsHeapObject()) return; // unmarked already
3229
3230 Address map_addr = reinterpret_cast<Address>(map);
3231
3232 map_addr -= kMarkTag;
3233
3234 ASSERT_TAG_ALIGNED(map_addr);
3235
3236 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3237
3238 obj->set_map(reinterpret_cast<Map*>(map_p));
3239
3240 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3241
3242 obj->IterateBody(Map::cast(map_p)->instance_type(),
3243 obj->SizeFromMap(Map::cast(map_p)),
3244 &unmark_visitor);
3245
3246 if (obj->IsCode()) {
3247 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3248 }
3249}
3250
3251
3252static void MarkRootObjectRecursively(Object** root) {
3253 if (search_for_any_global) {
3254 ASSERT(search_target == NULL);
3255 } else {
3256 ASSERT(search_target->IsHeapObject());
3257 }
3258 found_target = false;
3259 object_stack.Clear();
3260
3261 MarkObjectRecursively(root);
3262 UnmarkObjectRecursively(root);
3263
3264 if (found_target) {
3265 PrintF("=====================================\n");
3266 PrintF("==== Path to object ====\n");
3267 PrintF("=====================================\n\n");
3268
3269 ASSERT(!object_stack.is_empty());
3270 for (int i = 0; i < object_stack.length(); i++) {
3271 if (i > 0) PrintF("\n |\n |\n V\n\n");
3272 Object* obj = object_stack[i];
3273 obj->Print();
3274 }
3275 PrintF("=====================================\n");
3276 }
3277}
3278
3279
3280// Helper class for visiting HeapObjects recursively.
3281class MarkRootVisitor: public ObjectVisitor {
3282 public:
3283 void VisitPointers(Object** start, Object** end) {
3284 // Visit all HeapObject pointers in [start, end)
3285 for (Object** p = start; p < end; p++) {
3286 if ((*p)->IsHeapObject())
3287 MarkRootObjectRecursively(p);
3288 }
3289 }
3290};
3291
3292
3293// Triggers a depth-first traversal of reachable objects from roots
3294// and finds a path to a specific heap object and prints it.
3295void Heap::TracePathToObject() {
3296 search_target = NULL;
3297 search_for_any_global = false;
3298
3299 MarkRootVisitor root_visitor;
3300 IterateRoots(&root_visitor);
3301}
3302
3303
3304// Triggers a depth-first traversal of reachable objects from roots
3305// and finds a path to any global object and prints it. Useful for
3306// determining the source for leaks of global objects.
3307void Heap::TracePathToGlobal() {
3308 search_target = NULL;
3309 search_for_any_global = true;
3310
3311 MarkRootVisitor root_visitor;
3312 IterateRoots(&root_visitor);
3313}
3314#endif
3315
3316
kasper.lund7276f142008-07-30 08:49:36 +00003317GCTracer::GCTracer()
3318 : start_time_(0.0),
3319 start_size_(0.0),
3320 gc_count_(0),
3321 full_gc_count_(0),
3322 is_compacting_(false),
3323 marked_count_(0) {
3324 // These two fields reflect the state of the previous full collection.
3325 // Set them before they are changed by the collector.
3326 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3327 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3328 if (!FLAG_trace_gc) return;
3329 start_time_ = OS::TimeCurrentMillis();
3330 start_size_ = SizeOfHeapObjects();
3331}
3332
3333
3334GCTracer::~GCTracer() {
3335 if (!FLAG_trace_gc) return;
3336 // Printf ONE line iff flag is set.
3337 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3338 CollectorString(),
3339 start_size_, SizeOfHeapObjects(),
3340 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3341}
3342
3343
3344const char* GCTracer::CollectorString() {
3345 switch (collector_) {
3346 case SCAVENGER:
3347 return "Scavenge";
3348 case MARK_COMPACTOR:
3349 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3350 : "Mark-sweep";
3351 }
3352 return "Unknown GC";
3353}
3354
3355
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003356#ifdef DEBUG
3357bool Heap::GarbageCollectionGreedyCheck() {
3358 ASSERT(FLAG_gc_greedy);
3359 if (Bootstrapper::IsActive()) return true;
3360 if (disallow_allocation_failure()) return true;
3361 return CollectGarbage(0, NEW_SPACE);
3362}
3363#endif
3364
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003365} } // namespace v8::internal