blob: 805ca0948ce90778f7515f5eb305bb7a9cf62e29 [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
87// Variables set based on semispace_size_ and old_generation_size_ in
88// ConfigureHeap.
89int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
90
91// Double the new space after this many scavenge collections.
92int Heap::new_space_growth_limit_ = 8;
93int Heap::scavenge_count_ = 0;
94Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
95
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000096int Heap::mc_count_ = 0;
97int Heap::gc_count_ = 0;
98
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000099int Heap::always_allocate_scope_depth_ = 0;
100
kasper.lund7276f142008-07-30 08:49:36 +0000101#ifdef DEBUG
102bool Heap::allocation_allowed_ = true;
103
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000104int Heap::allocation_timeout_ = 0;
105bool Heap::disallow_allocation_failure_ = false;
106#endif // DEBUG
107
108
109int Heap::Capacity() {
110 if (!HasBeenSetup()) return 0;
111
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000112 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000113 old_pointer_space_->Capacity() +
114 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115 code_space_->Capacity() +
116 map_space_->Capacity();
117}
118
119
120int Heap::Available() {
121 if (!HasBeenSetup()) return 0;
122
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000123 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000124 old_pointer_space_->Available() +
125 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000126 code_space_->Available() +
127 map_space_->Available();
128}
129
130
131bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000132 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000133 old_data_space_ != NULL &&
134 code_space_ != NULL &&
135 map_space_ != NULL &&
136 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000137}
138
139
140GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
141 // Is global GC requested?
142 if (space != NEW_SPACE || FLAG_gc_global) {
143 Counters::gc_compactor_caused_by_request.Increment();
144 return MARK_COMPACTOR;
145 }
146
147 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000148 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000149 Counters::gc_compactor_caused_by_promoted_data.Increment();
150 return MARK_COMPACTOR;
151 }
152
153 // Have allocation in OLD and LO failed?
154 if (old_gen_exhausted_) {
155 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
156 return MARK_COMPACTOR;
157 }
158
159 // Is there enough space left in OLD to guarantee that a scavenge can
160 // succeed?
161 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000162 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000163 // for object promotion. It counts only the bytes that the memory
164 // allocator has not yet allocated from the OS and assigned to any space,
165 // and does not count available bytes already in the old space or code
166 // space. Undercounting is safe---we may get an unrequested full GC when
167 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000168 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000169 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
170 return MARK_COMPACTOR;
171 }
172
173 // Default
174 return SCAVENGER;
175}
176
177
178// TODO(1238405): Combine the infrastructure for --heap-stats and
179// --log-gc to avoid the complicated preprocessor and flag testing.
180#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
181void Heap::ReportStatisticsBeforeGC() {
182 // Heap::ReportHeapStatistics will also log NewSpace statistics when
183 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
184 // following logic is used to avoid double logging.
185#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000186 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187 if (FLAG_heap_stats) {
188 ReportHeapStatistics("Before GC");
189 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000190 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000192 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193#elif defined(DEBUG)
194 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000195 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000196 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 }
199#elif defined(ENABLE_LOGGING_AND_PROFILING)
200 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000201 new_space_.CollectStatistics();
202 new_space_.ReportStatistics();
203 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 }
205#endif
206}
207
208
209// TODO(1238405): Combine the infrastructure for --heap-stats and
210// --log-gc to avoid the complicated preprocessor and flag testing.
211void Heap::ReportStatisticsAfterGC() {
212 // Similar to the before GC, we use some complicated logic to ensure that
213 // NewSpace statistics are logged exactly once when --log-gc is turned on.
214#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
215 if (FLAG_heap_stats) {
216 ReportHeapStatistics("After GC");
217 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000218 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219 }
220#elif defined(DEBUG)
221 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
222#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000223 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000224#endif
225}
226#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
227
228
229void Heap::GarbageCollectionPrologue() {
230 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000231 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232#ifdef DEBUG
233 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
234 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235
236 if (FLAG_verify_heap) {
237 Verify();
238 }
239
240 if (FLAG_gc_verbose) Print();
241
242 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000243 // Not all spaces have remembered set bits that we care about.
244 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 map_space_->PrintRSet();
246 lo_space_->PrintRSet();
247 }
248#endif
249
250#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
251 ReportStatisticsBeforeGC();
252#endif
253}
254
255int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000256 int total = 0;
257 AllSpaces spaces;
258 while (Space* space = spaces.next()) total += space->Size();
259 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000260}
261
262void Heap::GarbageCollectionEpilogue() {
263#ifdef DEBUG
264 allow_allocation(true);
265 ZapFromSpace();
266
267 if (FLAG_verify_heap) {
268 Verify();
269 }
270
271 if (FLAG_print_global_handles) GlobalHandles::Print();
272 if (FLAG_print_handles) PrintHandles();
273 if (FLAG_gc_verbose) Print();
274 if (FLAG_code_stats) ReportCodeStatistics("After GC");
275#endif
276
277 Counters::alive_after_last_gc.Set(SizeOfObjects());
278
279 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
280 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
281 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
282#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
283 ReportStatisticsAfterGC();
284#endif
285}
286
287
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000288void Heap::CollectAllGarbage() {
289 // Since we are ignoring the return value, the exact choice of space does
290 // not matter, so long as we do not specify NEW_SPACE, which would not
291 // cause a full GC.
292 CollectGarbage(0, OLD_POINTER_SPACE);
293}
294
295
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000296bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
297 // The VM is in the GC state until exiting this function.
298 VMState state(GC);
299
300#ifdef DEBUG
301 // Reset the allocation timeout to the GC interval, but make sure to
302 // allow at least a few allocations after a collection. The reason
303 // for this is that we have a lot of allocation sequences and we
304 // assume that a garbage collection will allow the subsequent
305 // allocation attempts to go through.
306 allocation_timeout_ = Max(6, FLAG_gc_interval);
307#endif
308
309 { GCTracer tracer;
310 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000311 // The GC count was incremented in the prologue. Tell the tracer about
312 // it.
313 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000314
315 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000316 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317 tracer.set_collector(collector);
318
319 StatsRate* rate = (collector == SCAVENGER)
320 ? &Counters::gc_scavenger
321 : &Counters::gc_compactor;
322 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000323 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 rate->Stop();
325
326 GarbageCollectionEpilogue();
327 }
328
329
330#ifdef ENABLE_LOGGING_AND_PROFILING
331 if (FLAG_log_gc) HeapProfiler::WriteSample();
332#endif
333
334 switch (space) {
335 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000336 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000337 case OLD_POINTER_SPACE:
338 return old_pointer_space_->Available() >= requested_size;
339 case OLD_DATA_SPACE:
340 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 case CODE_SPACE:
342 return code_space_->Available() >= requested_size;
343 case MAP_SPACE:
344 return map_space_->Available() >= requested_size;
345 case LO_SPACE:
346 return lo_space_->Available() >= requested_size;
347 }
348 return false;
349}
350
351
kasper.lund7276f142008-07-30 08:49:36 +0000352void Heap::PerformScavenge() {
353 GCTracer tracer;
354 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
355}
356
357
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000358void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000359 GarbageCollector collector,
360 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
362 ASSERT(!allocation_allowed_);
363 global_gc_prologue_callback_();
364 }
365
366 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000367 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000369 int old_gen_size = PromotedSpaceSize();
370 old_gen_promotion_limit_ =
371 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
372 old_gen_allocation_limit_ =
373 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374 old_gen_exhausted_ = false;
375
376 // If we have used the mark-compact collector to collect the new
377 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000378 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379 // case where (1) a new space collection was requested, (2) the
380 // collector selection policy selected the mark-compact collector,
381 // and (3) the mark-compact collector policy selected not to
382 // compact the new space. In that case, there is no more (usable)
383 // free space in the new space after the collection compared to
384 // before.
385 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
386 Scavenge();
387 }
388 } else {
389 Scavenge();
390 }
391 Counters::objs_since_last_young.Set(0);
392
393 // Process weak handles post gc.
394 GlobalHandles::PostGarbageCollectionProcessing();
395
kasper.lund7276f142008-07-30 08:49:36 +0000396 if (collector == MARK_COMPACTOR) {
397 // Register the amount of external allocated memory.
398 amount_of_external_allocated_memory_at_last_global_gc_ =
399 amount_of_external_allocated_memory_;
400 }
401
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
403 ASSERT(!allocation_allowed_);
404 global_gc_epilogue_callback_();
405 }
406}
407
408
kasper.lund7276f142008-07-30 08:49:36 +0000409void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000412 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413 LOG(ResourceEvent("markcompact", "begin"));
414
415 MarkCompactPrologue();
416
kasper.lund7276f142008-07-30 08:49:36 +0000417 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418
419 MarkCompactEpilogue();
420
421 LOG(ResourceEvent("markcompact", "end"));
422
423 gc_state_ = NOT_IN_GC;
424
425 Shrink();
426
427 Counters::objs_since_last_full.Set(0);
428}
429
430
431void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000432 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000433 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434 RegExpImpl::OldSpaceCollectionPrologue();
435 Top::MarkCompactPrologue();
436 ThreadManager::MarkCompactPrologue();
437}
438
439
440void Heap::MarkCompactEpilogue() {
441 Top::MarkCompactEpilogue();
442 ThreadManager::MarkCompactEpilogue();
443}
444
445
446Object* Heap::FindCodeObject(Address a) {
447 Object* obj = code_space_->FindObject(a);
448 if (obj->IsFailure()) {
449 obj = lo_space_->FindObject(a);
450 }
kasper.lund7276f142008-07-30 08:49:36 +0000451 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000452 return obj;
453}
454
455
456// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000457class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000458 public:
459
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000460 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461
462 void VisitPointers(Object** start, Object** end) {
463 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000464 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 }
466
467 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000468 void ScavengePointer(Object** p) {
469 Object* object = *p;
470 if (!Heap::InNewSpace(object)) return;
471 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
472 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 }
474};
475
476
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000477// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000478static Address promoted_top = NULL;
479
480
481#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000482// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000483// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000484class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000485 public:
486 void VisitPointers(Object** start, Object**end) {
487 for (Object** current = start; current < end; current++) {
488 if ((*current)->IsHeapObject()) {
489 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
490 }
491 }
492 }
493};
494#endif
495
496void Heap::Scavenge() {
497#ifdef DEBUG
498 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000499 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500 HeapObjectIterator it(code_space_);
501 while (it.has_next()) {
502 HeapObject* object = it.next();
503 if (object->IsCode()) {
504 Code::cast(object)->ConvertICTargetsFromAddressToObject();
505 }
506 object->Iterate(&v);
507 if (object->IsCode()) {
508 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
509 }
510 }
511 }
512#endif
513
514 gc_state_ = SCAVENGE;
515
516 // Implements Cheney's copying algorithm
517 LOG(ResourceEvent("scavenge", "begin"));
518
519 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000520 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521 scavenge_count_ > new_space_growth_limit_) {
522 // Double the size of the new space, and double the limit. The next
523 // doubling attempt will occur after the current new_space_growth_limit_
524 // more collections.
525 // TODO(1240712): NewSpace::Double has a return value which is
526 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000527 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528 new_space_growth_limit_ *= 2;
529 }
530
531 // Flip the semispaces. After flipping, to space is empty, from space has
532 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000533 new_space_.Flip();
534 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000535
536 // We need to sweep newly copied objects which can be in either the to space
537 // or the old space. For to space objects, we use a mark. Newly copied
538 // objects lie between the mark and the allocation top. For objects
539 // promoted to old space, we write their addresses downward from the top of
540 // the new space. Sweeping newly promoted objects requires an allocation
541 // pointer and a mark. Note that the allocation pointer 'top' actually
542 // moves downward from the high address in the to space.
543 //
544 // There is guaranteed to be enough room at the top of the to space for the
545 // addresses of promoted objects: every object promoted frees up its size in
546 // bytes from the top of the new space, and objects are at least one pointer
547 // in size. Using the new space to record promoted addresses makes the
548 // scavenge collector agnostic to the allocation strategy (eg, linear or
549 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000550 Address new_mark = new_space_.ToSpaceLow();
551 Address promoted_mark = new_space_.ToSpaceHigh();
552 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000553
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000554 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000556 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557
558 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000559 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000560 IterateRSet(old_pointer_space_, &ScavengePointer);
561 IterateRSet(map_space_, &ScavengePointer);
562 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563
564 bool has_processed_weak_pointers = false;
565
566 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000567 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 ASSERT(promoted_mark >= promoted_top);
569
570 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000571 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572 // Sweep newly copied objects in the to space. The allocation pointer
573 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000574 Address previous_top = new_space_.top();
575 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000577 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578 }
579 new_mark = previous_top;
580
581 // Sweep newly copied objects in the old space. The promotion 'top'
582 // pointer could change during sweeping.
583 previous_top = promoted_top;
584 for (Address current = promoted_mark - kPointerSize;
585 current >= previous_top;
586 current -= kPointerSize) {
587 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000588 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 UpdateRSet(object);
590 }
591 promoted_mark = previous_top;
592 }
593
594 if (has_processed_weak_pointers) break; // We are done.
595 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000596 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597 has_processed_weak_pointers = true;
598 }
599
600 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000601 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602
603 LOG(ResourceEvent("scavenge", "end"));
604
605 gc_state_ = NOT_IN_GC;
606}
607
608
609void Heap::ClearRSetRange(Address start, int size_in_bytes) {
610 uint32_t start_bit;
611 Address start_word_address =
612 Page::ComputeRSetBitPosition(start, 0, &start_bit);
613 uint32_t end_bit;
614 Address end_word_address =
615 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
616 0,
617 &end_bit);
618
619 // We want to clear the bits in the starting word starting with the
620 // first bit, and in the ending word up to and including the last
621 // bit. Build a pair of bitmasks to do that.
622 uint32_t start_bitmask = start_bit - 1;
623 uint32_t end_bitmask = ~((end_bit << 1) - 1);
624
625 // If the start address and end address are the same, we mask that
626 // word once, otherwise mask the starting and ending word
627 // separately and all the ones in between.
628 if (start_word_address == end_word_address) {
629 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
630 } else {
631 Memory::uint32_at(start_word_address) &= start_bitmask;
632 Memory::uint32_at(end_word_address) &= end_bitmask;
633 start_word_address += kIntSize;
634 memset(start_word_address, 0, end_word_address - start_word_address);
635 }
636}
637
638
639class UpdateRSetVisitor: public ObjectVisitor {
640 public:
641
642 void VisitPointer(Object** p) {
643 UpdateRSet(p);
644 }
645
646 void VisitPointers(Object** start, Object** end) {
647 // Update a store into slots [start, end), used (a) to update remembered
648 // set when promoting a young object to old space or (b) to rebuild
649 // remembered sets after a mark-compact collection.
650 for (Object** p = start; p < end; p++) UpdateRSet(p);
651 }
652 private:
653
654 void UpdateRSet(Object** p) {
655 // The remembered set should not be set. It should be clear for objects
656 // newly copied to old space, and it is cleared before rebuilding in the
657 // mark-compact collector.
658 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
659 if (Heap::InNewSpace(*p)) {
660 Page::SetRSet(reinterpret_cast<Address>(p), 0);
661 }
662 }
663};
664
665
666int Heap::UpdateRSet(HeapObject* obj) {
667 ASSERT(!InNewSpace(obj));
668 // Special handling of fixed arrays to iterate the body based on the start
669 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
670 // will not work because Page::SetRSet needs to have the start of the
671 // object.
672 if (obj->IsFixedArray()) {
673 FixedArray* array = FixedArray::cast(obj);
674 int length = array->length();
675 for (int i = 0; i < length; i++) {
676 int offset = FixedArray::kHeaderSize + i * kPointerSize;
677 ASSERT(!Page::IsRSetSet(obj->address(), offset));
678 if (Heap::InNewSpace(array->get(i))) {
679 Page::SetRSet(obj->address(), offset);
680 }
681 }
682 } else if (!obj->IsCode()) {
683 // Skip code object, we know it does not contain inter-generational
684 // pointers.
685 UpdateRSetVisitor v;
686 obj->Iterate(&v);
687 }
688 return obj->Size();
689}
690
691
692void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000693 // By definition, we do not care about remembered set bits in code or data
694 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695 map_space_->ClearRSet();
696 RebuildRSets(map_space_);
697
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000698 old_pointer_space_->ClearRSet();
699 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000700
701 Heap::lo_space_->ClearRSet();
702 RebuildRSets(lo_space_);
703}
704
705
706void Heap::RebuildRSets(PagedSpace* space) {
707 HeapObjectIterator it(space);
708 while (it.has_next()) Heap::UpdateRSet(it.next());
709}
710
711
712void Heap::RebuildRSets(LargeObjectSpace* space) {
713 LargeObjectIterator it(space);
714 while (it.has_next()) Heap::UpdateRSet(it.next());
715}
716
717
718#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
719void Heap::RecordCopiedObject(HeapObject* obj) {
720 bool should_record = false;
721#ifdef DEBUG
722 should_record = FLAG_heap_stats;
723#endif
724#ifdef ENABLE_LOGGING_AND_PROFILING
725 should_record = should_record || FLAG_log_gc;
726#endif
727 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000728 if (new_space_.Contains(obj)) {
729 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000730 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000731 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000732 }
733 }
734}
735#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
736
737
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000738
739HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000740 HeapObject* target,
741 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000742 // Copy the content of source to target.
743 CopyBlock(reinterpret_cast<Object**>(target->address()),
744 reinterpret_cast<Object**>(source->address()),
745 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000746
kasper.lund7276f142008-07-30 08:49:36 +0000747 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000748 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000749
750 // Update NewSpace stats if necessary.
751#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
752 RecordCopiedObject(target);
753#endif
754
755 return target;
756}
757
758
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000759// Inlined function.
760void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
761 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000762
kasper.lund7276f142008-07-30 08:49:36 +0000763 // We use the first word (where the map pointer usually is) of a heap
764 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000765 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000767 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000768
kasper.lund7276f142008-07-30 08:49:36 +0000769 // If the first word is a forwarding address, the object has already been
770 // copied.
771 if (first_word.IsForwardingAddress()) {
772 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773 return;
774 }
775
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000776 // Call the slow part of scavenge object.
777 return ScavengeObjectSlow(p, object);
778}
779
ager@chromium.org870a0b62008-11-04 11:43:05 +0000780
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000781static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000782 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000783 // is a candidate for being shortcut by the scavenger.
784 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000785 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
786 StringShape shape(map);
787 return (shape.representation_tag() == kConsStringTag) &&
788 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000789}
790
791
792void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
793 ASSERT(InFromSpace(object));
794 MapWord first_word = object->map_word();
795 ASSERT(!first_word.IsForwardingAddress());
796
797 // Optimization: Bypass flattened ConsString objects.
798 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000799 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000800 *p = object;
801 // After patching *p we have to repeat the checks that object is in the
802 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000803 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000804 first_word = object->map_word();
805 if (first_word.IsForwardingAddress()) {
806 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 return;
808 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000809 }
810
kasper.lund7276f142008-07-30 08:49:36 +0000811 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000812 // If the object should be promoted, we try to copy it to old space.
813 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000814 OldSpace* target_space = Heap::TargetSpace(object);
815 ASSERT(target_space == Heap::old_pointer_space_ ||
816 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000817 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000818 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000819 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000820 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000821 // Record the object's address at the top of the to space, to allow
822 // it to be swept by the scavenger.
823 promoted_top -= kPointerSize;
824 Memory::Object_at(promoted_top) = *p;
825 } else {
826#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000827 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000828 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000829 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000830 (*p)->Iterate(&v);
831#endif
832 }
833 return;
834 }
835 }
836
837 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000838 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000839 // Failed allocation at this point is utterly unexpected.
840 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000841 *p = MigrateObject(object, HeapObject::cast(result), object_size);
842}
843
844
845void Heap::ScavengePointer(HeapObject** p) {
846 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847}
848
849
850Object* Heap::AllocatePartialMap(InstanceType instance_type,
851 int instance_size) {
852 Object* result = AllocateRawMap(Map::kSize);
853 if (result->IsFailure()) return result;
854
855 // Map::cast cannot be used due to uninitialized map field.
856 reinterpret_cast<Map*>(result)->set_map(meta_map());
857 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
858 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000859 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000860 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
861 return result;
862}
863
864
865Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
866 Object* result = AllocateRawMap(Map::kSize);
867 if (result->IsFailure()) return result;
868
869 Map* map = reinterpret_cast<Map*>(result);
870 map->set_map(meta_map());
871 map->set_instance_type(instance_type);
872 map->set_prototype(null_value());
873 map->set_constructor(null_value());
874 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000875 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000876 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000877 map->set_code_cache(empty_fixed_array());
878 map->set_unused_property_fields(0);
879 map->set_bit_field(0);
880 return map;
881}
882
883
884bool Heap::CreateInitialMaps() {
885 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
886 if (obj->IsFailure()) return false;
887
888 // Map::cast cannot be used due to uninitialized map field.
889 meta_map_ = reinterpret_cast<Map*>(obj);
890 meta_map()->set_map(meta_map());
891
892 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
893 if (obj->IsFailure()) return false;
894 fixed_array_map_ = Map::cast(obj);
895
896 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
897 if (obj->IsFailure()) return false;
898 oddball_map_ = Map::cast(obj);
899
900 // Allocate the empty array
901 obj = AllocateEmptyFixedArray();
902 if (obj->IsFailure()) return false;
903 empty_fixed_array_ = FixedArray::cast(obj);
904
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000905 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000906 if (obj->IsFailure()) return false;
907 null_value_ = obj;
908
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000909 // Allocate the empty descriptor array. AllocateMap can now be used.
910 obj = AllocateEmptyFixedArray();
911 if (obj->IsFailure()) return false;
912 // There is a check against empty_descriptor_array() in cast().
913 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000915 // Fix the instance_descriptors for the existing maps.
916 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917 meta_map()->set_code_cache(empty_fixed_array());
918
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000919 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000920 fixed_array_map()->set_code_cache(empty_fixed_array());
921
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000922 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000923 oddball_map()->set_code_cache(empty_fixed_array());
924
925 // Fix prototype object for existing maps.
926 meta_map()->set_prototype(null_value());
927 meta_map()->set_constructor(null_value());
928
929 fixed_array_map()->set_prototype(null_value());
930 fixed_array_map()->set_constructor(null_value());
931 oddball_map()->set_prototype(null_value());
932 oddball_map()->set_constructor(null_value());
933
934 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
935 if (obj->IsFailure()) return false;
936 heap_number_map_ = Map::cast(obj);
937
938 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
939 if (obj->IsFailure()) return false;
940 proxy_map_ = Map::cast(obj);
941
942#define ALLOCATE_STRING_MAP(type, size, name) \
943 obj = AllocateMap(type, size); \
944 if (obj->IsFailure()) return false; \
945 name##_map_ = Map::cast(obj);
946 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
947#undef ALLOCATE_STRING_MAP
948
ager@chromium.org7c537e22008-10-16 08:43:32 +0000949 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 if (obj->IsFailure()) return false;
951 undetectable_short_string_map_ = Map::cast(obj);
952 undetectable_short_string_map_->set_is_undetectable();
953
ager@chromium.org7c537e22008-10-16 08:43:32 +0000954 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000955 if (obj->IsFailure()) return false;
956 undetectable_medium_string_map_ = Map::cast(obj);
957 undetectable_medium_string_map_->set_is_undetectable();
958
ager@chromium.org7c537e22008-10-16 08:43:32 +0000959 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000960 if (obj->IsFailure()) return false;
961 undetectable_long_string_map_ = Map::cast(obj);
962 undetectable_long_string_map_->set_is_undetectable();
963
ager@chromium.org7c537e22008-10-16 08:43:32 +0000964 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000965 if (obj->IsFailure()) return false;
966 undetectable_short_ascii_string_map_ = Map::cast(obj);
967 undetectable_short_ascii_string_map_->set_is_undetectable();
968
ager@chromium.org7c537e22008-10-16 08:43:32 +0000969 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000970 if (obj->IsFailure()) return false;
971 undetectable_medium_ascii_string_map_ = Map::cast(obj);
972 undetectable_medium_ascii_string_map_->set_is_undetectable();
973
ager@chromium.org7c537e22008-10-16 08:43:32 +0000974 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000975 if (obj->IsFailure()) return false;
976 undetectable_long_ascii_string_map_ = Map::cast(obj);
977 undetectable_long_ascii_string_map_->set_is_undetectable();
978
979 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
980 if (obj->IsFailure()) return false;
981 byte_array_map_ = Map::cast(obj);
982
983 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
984 if (obj->IsFailure()) return false;
985 code_map_ = Map::cast(obj);
986
987 obj = AllocateMap(FILLER_TYPE, kPointerSize);
988 if (obj->IsFailure()) return false;
989 one_word_filler_map_ = Map::cast(obj);
990
991 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
992 if (obj->IsFailure()) return false;
993 two_word_filler_map_ = Map::cast(obj);
994
995#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
996 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
997 if (obj->IsFailure()) return false; \
998 name##_map_ = Map::cast(obj);
999 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1000#undef ALLOCATE_STRUCT_MAP
1001
ager@chromium.org236ad962008-09-25 09:45:57 +00001002 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001003 if (obj->IsFailure()) return false;
1004 hash_table_map_ = Map::cast(obj);
1005
ager@chromium.org236ad962008-09-25 09:45:57 +00001006 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001007 if (obj->IsFailure()) return false;
1008 context_map_ = Map::cast(obj);
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 global_context_map_ = Map::cast(obj);
1013
1014 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1015 if (obj->IsFailure()) return false;
1016 boilerplate_function_map_ = Map::cast(obj);
1017
1018 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1019 if (obj->IsFailure()) return false;
1020 shared_function_info_map_ = Map::cast(obj);
1021
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001022 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001023 return true;
1024}
1025
1026
1027Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1028 // Statically ensure that it is safe to allocate heap numbers in paged
1029 // spaces.
1030 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001031 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001032 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001033 if (result->IsFailure()) return result;
1034
1035 HeapObject::cast(result)->set_map(heap_number_map());
1036 HeapNumber::cast(result)->set_value(value);
1037 return result;
1038}
1039
1040
1041Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001042 // Use general version, if we're forced to always allocate.
1043 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001044 // This version of AllocateHeapNumber is optimized for
1045 // allocation in new space.
1046 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1047 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001048 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001049 if (result->IsFailure()) return result;
1050 HeapObject::cast(result)->set_map(heap_number_map());
1051 HeapNumber::cast(result)->set_value(value);
1052 return result;
1053}
1054
1055
1056Object* Heap::CreateOddball(Map* map,
1057 const char* to_string,
1058 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001059 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060 if (result->IsFailure()) return result;
1061 return Oddball::cast(result)->Initialize(to_string, to_number);
1062}
1063
1064
1065bool Heap::CreateApiObjects() {
1066 Object* obj;
1067
1068 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1069 if (obj->IsFailure()) return false;
1070 neander_map_ = Map::cast(obj);
1071
1072 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1073 if (obj->IsFailure()) return false;
1074 Object* elements = AllocateFixedArray(2);
1075 if (elements->IsFailure()) return false;
1076 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1077 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1078 message_listeners_ = JSObject::cast(obj);
1079
1080 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1081 if (obj->IsFailure()) return false;
1082 elements = AllocateFixedArray(2);
1083 if (elements->IsFailure()) return false;
1084 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1085 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1086 debug_event_listeners_ = JSObject::cast(obj);
1087
1088 return true;
1089}
1090
1091void Heap::CreateFixedStubs() {
1092 // Here we create roots for fixed stubs. They are needed at GC
1093 // for cooking and uncooking (check out frames.cc).
1094 // The eliminates the need for doing dictionary lookup in the
1095 // stub cache for these stubs.
1096 HandleScope scope;
1097 {
1098 CEntryStub stub;
1099 c_entry_code_ = *stub.GetCode();
1100 }
1101 {
1102 CEntryDebugBreakStub stub;
1103 c_entry_debug_break_code_ = *stub.GetCode();
1104 }
1105 {
1106 JSEntryStub stub;
1107 js_entry_code_ = *stub.GetCode();
1108 }
1109 {
1110 JSConstructEntryStub stub;
1111 js_construct_entry_code_ = *stub.GetCode();
1112 }
1113}
1114
1115
1116bool Heap::CreateInitialObjects() {
1117 Object* obj;
1118
1119 // The -0 value must be set before NumberFromDouble works.
1120 obj = AllocateHeapNumber(-0.0, TENURED);
1121 if (obj->IsFailure()) return false;
1122 minus_zero_value_ = obj;
1123 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1124
1125 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1126 if (obj->IsFailure()) return false;
1127 nan_value_ = obj;
1128
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001129 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001130 if (obj->IsFailure()) return false;
1131 undefined_value_ = obj;
1132 ASSERT(!InNewSpace(undefined_value()));
1133
1134 // Allocate initial symbol table.
1135 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1136 if (obj->IsFailure()) return false;
1137 symbol_table_ = obj;
1138
1139 // Assign the print strings for oddballs after creating symboltable.
1140 Object* symbol = LookupAsciiSymbol("undefined");
1141 if (symbol->IsFailure()) return false;
1142 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1143 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1144
1145 // Assign the print strings for oddballs after creating symboltable.
1146 symbol = LookupAsciiSymbol("null");
1147 if (symbol->IsFailure()) return false;
1148 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1149 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1150
1151 // Allocate the null_value
1152 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1153 if (obj->IsFailure()) return false;
1154
1155 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1156 if (obj->IsFailure()) return false;
1157 true_value_ = obj;
1158
1159 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1160 if (obj->IsFailure()) return false;
1161 false_value_ = obj;
1162
1163 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1164 if (obj->IsFailure()) return false;
1165 the_hole_value_ = obj;
1166
1167 // Allocate the empty string.
1168 obj = AllocateRawAsciiString(0, TENURED);
1169 if (obj->IsFailure()) return false;
1170 empty_string_ = String::cast(obj);
1171
1172#define SYMBOL_INITIALIZE(name, string) \
1173 obj = LookupAsciiSymbol(string); \
1174 if (obj->IsFailure()) return false; \
1175 (name##_) = String::cast(obj);
1176 SYMBOL_LIST(SYMBOL_INITIALIZE)
1177#undef SYMBOL_INITIALIZE
1178
1179 // Allocate the proxy for __proto__.
1180 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1181 if (obj->IsFailure()) return false;
1182 prototype_accessors_ = Proxy::cast(obj);
1183
1184 // Allocate the code_stubs dictionary.
1185 obj = Dictionary::Allocate(4);
1186 if (obj->IsFailure()) return false;
1187 code_stubs_ = Dictionary::cast(obj);
1188
1189 // Allocate the non_monomorphic_cache used in stub-cache.cc
1190 obj = Dictionary::Allocate(4);
1191 if (obj->IsFailure()) return false;
1192 non_monomorphic_cache_ = Dictionary::cast(obj);
1193
1194 CreateFixedStubs();
1195
1196 // Allocate the number->string conversion cache
1197 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1198 if (obj->IsFailure()) return false;
1199 number_string_cache_ = FixedArray::cast(obj);
1200
1201 // Allocate cache for single character strings.
1202 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1203 if (obj->IsFailure()) return false;
1204 single_character_string_cache_ = FixedArray::cast(obj);
1205
1206 // Allocate cache for external strings pointing to native source code.
1207 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1208 if (obj->IsFailure()) return false;
1209 natives_source_cache_ = FixedArray::cast(obj);
1210
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001211 // Initialize keyed lookup cache.
1212 ClearKeyedLookupCache();
1213
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001214 // Initialize compilation cache.
1215 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001216
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001217 return true;
1218}
1219
1220
1221static inline int double_get_hash(double d) {
1222 DoubleRepresentation rep(d);
1223 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1224 (Heap::kNumberStringCacheSize - 1));
1225}
1226
1227
1228static inline int smi_get_hash(Smi* smi) {
1229 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1230}
1231
1232
1233
1234Object* Heap::GetNumberStringCache(Object* number) {
1235 int hash;
1236 if (number->IsSmi()) {
1237 hash = smi_get_hash(Smi::cast(number));
1238 } else {
1239 hash = double_get_hash(number->Number());
1240 }
1241 Object* key = number_string_cache_->get(hash * 2);
1242 if (key == number) {
1243 return String::cast(number_string_cache_->get(hash * 2 + 1));
1244 } else if (key->IsHeapNumber() &&
1245 number->IsHeapNumber() &&
1246 key->Number() == number->Number()) {
1247 return String::cast(number_string_cache_->get(hash * 2 + 1));
1248 }
1249 return undefined_value();
1250}
1251
1252
1253void Heap::SetNumberStringCache(Object* number, String* string) {
1254 int hash;
1255 if (number->IsSmi()) {
1256 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001257 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001258 } else {
1259 hash = double_get_hash(number->Number());
1260 number_string_cache_->set(hash * 2, number);
1261 }
1262 number_string_cache_->set(hash * 2 + 1, string);
1263}
1264
1265
1266Object* Heap::SmiOrNumberFromDouble(double value,
1267 bool new_object,
1268 PretenureFlag pretenure) {
1269 // We need to distinguish the minus zero value and this cannot be
1270 // done after conversion to int. Doing this by comparing bit
1271 // patterns is faster than using fpclassify() et al.
1272 static const DoubleRepresentation plus_zero(0.0);
1273 static const DoubleRepresentation minus_zero(-0.0);
1274 static const DoubleRepresentation nan(OS::nan_value());
1275 ASSERT(minus_zero_value_ != NULL);
1276 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1277
1278 DoubleRepresentation rep(value);
1279 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1280 if (rep.bits == minus_zero.bits) {
1281 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1282 : minus_zero_value_;
1283 }
1284 if (rep.bits == nan.bits) {
1285 return new_object
1286 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1287 : nan_value_;
1288 }
1289
1290 // Try to represent the value as a tagged small integer.
1291 int int_value = FastD2I(value);
1292 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1293 return Smi::FromInt(int_value);
1294 }
1295
1296 // Materialize the value in the heap.
1297 return AllocateHeapNumber(value, pretenure);
1298}
1299
1300
1301Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1302 return SmiOrNumberFromDouble(value,
1303 true /* number object must be new */,
1304 pretenure);
1305}
1306
1307
1308Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1309 return SmiOrNumberFromDouble(value,
1310 false /* use preallocated NaN, -0.0 */,
1311 pretenure);
1312}
1313
1314
1315Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1316 // Statically ensure that it is safe to allocate proxies in paged spaces.
1317 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001318 AllocationSpace space =
1319 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001320 Object* result = Allocate(proxy_map(), space);
1321 if (result->IsFailure()) return result;
1322
1323 Proxy::cast(result)->set_proxy(proxy);
1324 return result;
1325}
1326
1327
1328Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1329 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1330 if (result->IsFailure()) return result;
1331
1332 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1333 share->set_name(name);
1334 Code* illegal = Builtins::builtin(Builtins::Illegal);
1335 share->set_code(illegal);
1336 share->set_expected_nof_properties(0);
1337 share->set_length(0);
1338 share->set_formal_parameter_count(0);
1339 share->set_instance_class_name(Object_symbol());
1340 share->set_function_data(undefined_value());
1341 share->set_lazy_load_data(undefined_value());
1342 share->set_script(undefined_value());
1343 share->set_start_position_and_type(0);
1344 share->set_debug_info(undefined_value());
1345 return result;
1346}
1347
1348
ager@chromium.org870a0b62008-11-04 11:43:05 +00001349Object* Heap::AllocateConsString(String* first,
1350 StringShape first_shape,
1351 String* second,
1352 StringShape second_shape) {
1353 int first_length = first->length(first_shape);
1354 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001355 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001356 bool is_ascii = first_shape.IsAsciiRepresentation()
1357 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001358
1359 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001360 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001361 ASSERT(first->IsFlat(first_shape));
1362 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001363 if (is_ascii) {
1364 Object* result = AllocateRawAsciiString(length);
1365 if (result->IsFailure()) return result;
1366 // Copy the characters into the new object.
1367 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001368 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1369 String::WriteToFlat(second,
1370 second_shape,
1371 dest + first_length,
1372 0,
1373 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001374 return result;
1375 } else {
1376 Object* result = AllocateRawTwoByteString(length);
1377 if (result->IsFailure()) return result;
1378 // Copy the characters into the new object.
1379 uc16* dest = SeqTwoByteString::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;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001387 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001388 }
1389
1390 Map* map;
1391 if (length <= String::kMaxShortStringSize) {
1392 map = is_ascii ? short_cons_ascii_string_map()
1393 : short_cons_string_map();
1394 } else if (length <= String::kMaxMediumStringSize) {
1395 map = is_ascii ? medium_cons_ascii_string_map()
1396 : medium_cons_string_map();
1397 } else {
1398 map = is_ascii ? long_cons_ascii_string_map()
1399 : long_cons_string_map();
1400 }
1401
1402 Object* result = Allocate(map, NEW_SPACE);
1403 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001404 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001406 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1407 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001408 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409 return result;
1410}
1411
1412
ager@chromium.org870a0b62008-11-04 11:43:05 +00001413Object* Heap::AllocateSlicedString(String* buffer,
1414 StringShape buffer_shape,
1415 int start,
1416 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 int length = end - start;
1418
1419 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001420 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001421 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001422 }
1423
1424 Map* map;
1425 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001426 map = buffer_shape.IsAsciiRepresentation() ?
1427 short_sliced_ascii_string_map() :
1428 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001429 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001430 map = buffer_shape.IsAsciiRepresentation() ?
1431 medium_sliced_ascii_string_map() :
1432 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001433 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001434 map = buffer_shape.IsAsciiRepresentation() ?
1435 long_sliced_ascii_string_map() :
1436 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001437 }
1438
1439 Object* result = Allocate(map, NEW_SPACE);
1440 if (result->IsFailure()) return result;
1441
1442 SlicedString* sliced_string = SlicedString::cast(result);
1443 sliced_string->set_buffer(buffer);
1444 sliced_string->set_start(start);
1445 sliced_string->set_length(length);
1446
1447 return result;
1448}
1449
1450
ager@chromium.org870a0b62008-11-04 11:43:05 +00001451Object* Heap::AllocateSubString(String* buffer,
1452 StringShape buffer_shape,
1453 int start,
1454 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001455 int length = end - start;
1456
ager@chromium.org7c537e22008-10-16 08:43:32 +00001457 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001458 return Heap::LookupSingleCharacterStringFromCode(
1459 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001460 }
1461
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001462 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001463 if (!buffer->IsFlat(buffer_shape)) {
1464 buffer->TryFlatten(buffer_shape);
1465 buffer_shape = StringShape(buffer);
1466 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467
ager@chromium.org870a0b62008-11-04 11:43:05 +00001468 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001469 ? AllocateRawAsciiString(length)
1470 : AllocateRawTwoByteString(length);
1471 if (result->IsFailure()) return result;
1472
1473 // Copy the characters into the new object.
1474 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001475 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001476 StringHasher hasher(length);
1477 int i = 0;
1478 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001479 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001480 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001481 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001482 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001483 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001484 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001485 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001486 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001487 }
1488 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001489 return result;
1490}
1491
1492
1493Object* Heap::AllocateExternalStringFromAscii(
1494 ExternalAsciiString::Resource* resource) {
1495 Map* map;
1496 int length = resource->length();
1497 if (length <= String::kMaxShortStringSize) {
1498 map = short_external_ascii_string_map();
1499 } else if (length <= String::kMaxMediumStringSize) {
1500 map = medium_external_ascii_string_map();
1501 } else {
1502 map = long_external_ascii_string_map();
1503 }
1504
1505 Object* result = Allocate(map, NEW_SPACE);
1506 if (result->IsFailure()) return result;
1507
1508 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1509 external_string->set_length(length);
1510 external_string->set_resource(resource);
1511
1512 return result;
1513}
1514
1515
1516Object* Heap::AllocateExternalStringFromTwoByte(
1517 ExternalTwoByteString::Resource* resource) {
1518 Map* map;
1519 int length = resource->length();
1520 if (length <= String::kMaxShortStringSize) {
1521 map = short_external_string_map();
1522 } else if (length <= String::kMaxMediumStringSize) {
1523 map = medium_external_string_map();
1524 } else {
1525 map = long_external_string_map();
1526 }
1527
1528 Object* result = Allocate(map, NEW_SPACE);
1529 if (result->IsFailure()) return result;
1530
1531 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1532 external_string->set_length(length);
1533 external_string->set_resource(resource);
1534
1535 return result;
1536}
1537
1538
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001539Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001540 if (code <= String::kMaxAsciiCharCode) {
1541 Object* value = Heap::single_character_string_cache()->get(code);
1542 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001543
1544 char buffer[1];
1545 buffer[0] = static_cast<char>(code);
1546 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1547
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001548 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549 Heap::single_character_string_cache()->set(code, result);
1550 return result;
1551 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001552
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553 Object* result = Heap::AllocateRawTwoByteString(1);
1554 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001555 String* answer = String::cast(result);
1556 answer->Set(StringShape(answer), 0, code);
1557 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001558}
1559
1560
1561Object* Heap::AllocateByteArray(int length) {
1562 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001563 AllocationSpace space =
1564 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001565
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001566 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001567
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001568 if (result->IsFailure()) return result;
1569
1570 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1571 reinterpret_cast<Array*>(result)->set_length(length);
1572 return result;
1573}
1574
1575
1576Object* Heap::CreateCode(const CodeDesc& desc,
1577 ScopeInfo<>* sinfo,
1578 Code::Flags flags) {
1579 // Compute size
1580 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1581 int sinfo_size = 0;
1582 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1583 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001584 Object* result;
1585 if (obj_size > MaxHeapObjectSize()) {
1586 result = lo_space_->AllocateRawCode(obj_size);
1587 } else {
1588 result = code_space_->AllocateRaw(obj_size);
1589 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001590
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001591 if (result->IsFailure()) return result;
1592
1593 // Initialize the object
1594 HeapObject::cast(result)->set_map(code_map());
1595 Code* code = Code::cast(result);
1596 code->set_instruction_size(desc.instr_size);
1597 code->set_relocation_size(desc.reloc_size);
1598 code->set_sinfo_size(sinfo_size);
1599 code->set_flags(flags);
1600 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
1601 code->CopyFrom(desc); // migrate generated code
1602 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1603
1604#ifdef DEBUG
1605 code->Verify();
1606#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001607 return code;
1608}
1609
1610
1611Object* Heap::CopyCode(Code* code) {
1612 // Allocate an object the same size as the code object.
1613 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001614 Object* result;
1615 if (obj_size > MaxHeapObjectSize()) {
1616 result = lo_space_->AllocateRawCode(obj_size);
1617 } else {
1618 result = code_space_->AllocateRaw(obj_size);
1619 }
1620
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621 if (result->IsFailure()) return result;
1622
1623 // Copy code object.
1624 Address old_addr = code->address();
1625 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001626 CopyBlock(reinterpret_cast<Object**>(new_addr),
1627 reinterpret_cast<Object**>(old_addr),
1628 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629 // Relocate the copy.
1630 Code* new_code = Code::cast(result);
1631 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001632 return new_code;
1633}
1634
1635
1636Object* Heap::Allocate(Map* map, AllocationSpace space) {
1637 ASSERT(gc_state_ == NOT_IN_GC);
1638 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001639 Object* result = AllocateRaw(map->instance_size(),
1640 space,
1641 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001642 if (result->IsFailure()) return result;
1643 HeapObject::cast(result)->set_map(map);
1644 return result;
1645}
1646
1647
1648Object* Heap::InitializeFunction(JSFunction* function,
1649 SharedFunctionInfo* shared,
1650 Object* prototype) {
1651 ASSERT(!prototype->IsMap());
1652 function->initialize_properties();
1653 function->initialize_elements();
1654 function->set_shared(shared);
1655 function->set_prototype_or_initial_map(prototype);
1656 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001657 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001658 return function;
1659}
1660
1661
1662Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1663 // Allocate the prototype.
1664 Object* prototype =
1665 AllocateJSObject(Top::context()->global_context()->object_function());
1666 if (prototype->IsFailure()) return prototype;
1667 // When creating the prototype for the function we must set its
1668 // constructor to the function.
1669 Object* result =
1670 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1671 function,
1672 DONT_ENUM);
1673 if (result->IsFailure()) return result;
1674 return prototype;
1675}
1676
1677
1678Object* Heap::AllocateFunction(Map* function_map,
1679 SharedFunctionInfo* shared,
1680 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001681 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682 if (result->IsFailure()) return result;
1683 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1684}
1685
1686
1687Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001688 // To get fast allocation and map sharing for arguments objects we
1689 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001690
1691 // This calls Copy directly rather than using Heap::AllocateRaw so we
1692 // duplicate the check here.
1693 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1694
1695 JSObject* boilerplate =
1696 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001697
1698 // Make the clone.
1699 Map* map = boilerplate->map();
1700 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001701 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001702 if (result->IsFailure()) return result;
1703
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001704 // Copy the content. The arguments boilerplate doesn't have any
1705 // fields that point to new space so it's safe to skip the write
1706 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001707 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1708 reinterpret_cast<Object**>(boilerplate->address()),
1709 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001711 // Set the two properties.
1712 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001713 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001714 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1715 Smi::FromInt(length),
1716 SKIP_WRITE_BARRIER);
1717
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001718 // Check the state of the object
1719 ASSERT(JSObject::cast(result)->HasFastProperties());
1720 ASSERT(JSObject::cast(result)->HasFastElements());
1721
1722 return result;
1723}
1724
1725
1726Object* Heap::AllocateInitialMap(JSFunction* fun) {
1727 ASSERT(!fun->has_initial_map());
1728
ager@chromium.org7c537e22008-10-16 08:43:32 +00001729 // First create a new map with the expected number of properties being
1730 // allocated in-object.
1731 int expected_nof_properties = fun->shared()->expected_nof_properties();
1732 int instance_size = JSObject::kHeaderSize +
1733 expected_nof_properties * kPointerSize;
1734 if (instance_size > JSObject::kMaxInstanceSize) {
1735 instance_size = JSObject::kMaxInstanceSize;
1736 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1737 kPointerSize;
1738 }
1739 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001740 if (map_obj->IsFailure()) return map_obj;
1741
1742 // Fetch or allocate prototype.
1743 Object* prototype;
1744 if (fun->has_instance_prototype()) {
1745 prototype = fun->instance_prototype();
1746 } else {
1747 prototype = AllocateFunctionPrototype(fun);
1748 if (prototype->IsFailure()) return prototype;
1749 }
1750 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001751 map->set_inobject_properties(expected_nof_properties);
1752 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001753 map->set_prototype(prototype);
1754 return map;
1755}
1756
1757
1758void Heap::InitializeJSObjectFromMap(JSObject* obj,
1759 FixedArray* properties,
1760 Map* map) {
1761 obj->set_properties(properties);
1762 obj->initialize_elements();
1763 // TODO(1240798): Initialize the object's body using valid initial values
1764 // according to the object's initial map. For example, if the map's
1765 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1766 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1767 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1768 // verification code has to cope with (temporarily) invalid objects. See
1769 // for example, JSArray::JSArrayVerify).
1770 obj->InitializeBody(map->instance_size());
1771}
1772
1773
1774Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1775 // JSFunctions should be allocated using AllocateFunction to be
1776 // properly initialized.
1777 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1778
1779 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001780 int prop_size = map->unused_property_fields() - map->inobject_properties();
1781 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782 if (properties->IsFailure()) return properties;
1783
1784 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001785 AllocationSpace space =
1786 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001787 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1788 Object* obj = Allocate(map, space);
1789 if (obj->IsFailure()) return obj;
1790
1791 // Initialize the JSObject.
1792 InitializeJSObjectFromMap(JSObject::cast(obj),
1793 FixedArray::cast(properties),
1794 map);
1795 return obj;
1796}
1797
1798
1799Object* Heap::AllocateJSObject(JSFunction* constructor,
1800 PretenureFlag pretenure) {
1801 // Allocate the initial map if absent.
1802 if (!constructor->has_initial_map()) {
1803 Object* initial_map = AllocateInitialMap(constructor);
1804 if (initial_map->IsFailure()) return initial_map;
1805 constructor->set_initial_map(Map::cast(initial_map));
1806 Map::cast(initial_map)->set_constructor(constructor);
1807 }
1808 // Allocate the object based on the constructors initial map.
1809 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1810}
1811
1812
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001813Object* Heap::CopyJSObject(JSObject* source) {
1814 // Never used to copy functions. If functions need to be copied we
1815 // have to be careful to clear the literals array.
1816 ASSERT(!source->IsJSFunction());
1817
1818 // Make the clone.
1819 Map* map = source->map();
1820 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001821 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001822
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001823 // If we're forced to always allocate, we use the general allocation
1824 // functions which may leave us with an object in old space.
1825 if (always_allocate()) {
1826 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1827 if (clone->IsFailure()) return clone;
1828 Address clone_address = HeapObject::cast(clone)->address();
1829 CopyBlock(reinterpret_cast<Object**>(clone_address),
1830 reinterpret_cast<Object**>(source->address()),
1831 object_size);
1832 // Update write barrier for all fields that lie beyond the header.
1833 for (int offset = JSObject::kHeaderSize;
1834 offset < object_size;
1835 offset += kPointerSize) {
1836 RecordWrite(clone_address, offset);
1837 }
1838 } else {
1839 clone = new_space_.AllocateRaw(object_size);
1840 if (clone->IsFailure()) return clone;
1841 ASSERT(Heap::InNewSpace(clone));
1842 // Since we know the clone is allocated in new space, we can copy
1843 // the contents without worring about updating the write barrier.
1844 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1845 reinterpret_cast<Object**>(source->address()),
1846 object_size);
1847 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001848
1849 FixedArray* elements = FixedArray::cast(source->elements());
1850 FixedArray* properties = FixedArray::cast(source->properties());
1851 // Update elements if necessary.
1852 if (elements->length()> 0) {
1853 Object* elem = CopyFixedArray(elements);
1854 if (elem->IsFailure()) return elem;
1855 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1856 }
1857 // Update properties if necessary.
1858 if (properties->length() > 0) {
1859 Object* prop = CopyFixedArray(properties);
1860 if (prop->IsFailure()) return prop;
1861 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1862 }
1863 // Return the new clone.
1864 return clone;
1865}
1866
1867
1868Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1869 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001870 // Allocate initial map if absent.
1871 if (!constructor->has_initial_map()) {
1872 Object* initial_map = AllocateInitialMap(constructor);
1873 if (initial_map->IsFailure()) return initial_map;
1874 constructor->set_initial_map(Map::cast(initial_map));
1875 Map::cast(initial_map)->set_constructor(constructor);
1876 }
1877
1878 Map* map = constructor->initial_map();
1879
1880 // Check that the already allocated object has the same size as
1881 // objects allocated using the constructor.
1882 ASSERT(map->instance_size() == object->map()->instance_size());
1883
1884 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001885 int prop_size = map->unused_property_fields() - map->inobject_properties();
1886 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001887 if (properties->IsFailure()) return properties;
1888
1889 // Reset the map for the object.
1890 object->set_map(constructor->initial_map());
1891
1892 // Reinitialize the object from the constructor map.
1893 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1894 return object;
1895}
1896
1897
1898Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1899 PretenureFlag pretenure) {
1900 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1901 if (result->IsFailure()) return result;
1902
1903 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001904 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001905 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001906 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001907 }
1908 return result;
1909}
1910
1911
1912Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1913 PretenureFlag pretenure) {
1914 // Count the number of characters in the UTF-8 string and check if
1915 // it is an ASCII string.
1916 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1917 decoder->Reset(string.start(), string.length());
1918 int chars = 0;
1919 bool is_ascii = true;
1920 while (decoder->has_more()) {
1921 uc32 r = decoder->GetNext();
1922 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1923 chars++;
1924 }
1925
1926 // If the string is ascii, we do not need to convert the characters
1927 // since UTF8 is backwards compatible with ascii.
1928 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1929
1930 Object* result = AllocateRawTwoByteString(chars, pretenure);
1931 if (result->IsFailure()) return result;
1932
1933 // Convert and copy the characters into the new object.
1934 String* string_result = String::cast(result);
1935 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00001936 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001937 for (int i = 0; i < chars; i++) {
1938 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001939 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001940 }
1941 return result;
1942}
1943
1944
1945Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1946 PretenureFlag pretenure) {
1947 // Check if the string is an ASCII string.
1948 int i = 0;
1949 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1950
1951 Object* result;
1952 if (i == string.length()) { // It's an ASCII string.
1953 result = AllocateRawAsciiString(string.length(), pretenure);
1954 } else { // It's not an ASCII string.
1955 result = AllocateRawTwoByteString(string.length(), pretenure);
1956 }
1957 if (result->IsFailure()) return result;
1958
1959 // Copy the characters into the new object, which may be either ASCII or
1960 // UTF-16.
1961 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001962 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001963 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001964 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001965 }
1966 return result;
1967}
1968
1969
1970Map* Heap::SymbolMapForString(String* string) {
1971 // If the string is in new space it cannot be used as a symbol.
1972 if (InNewSpace(string)) return NULL;
1973
1974 // Find the corresponding symbol map for strings.
1975 Map* map = string->map();
1976
1977 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
1978 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
1979 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
1980
1981 if (map == short_string_map()) return short_symbol_map();
1982 if (map == medium_string_map()) return medium_symbol_map();
1983 if (map == long_string_map()) return long_symbol_map();
1984
1985 if (map == short_cons_string_map()) return short_cons_symbol_map();
1986 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
1987 if (map == long_cons_string_map()) return long_cons_symbol_map();
1988
1989 if (map == short_cons_ascii_string_map()) {
1990 return short_cons_ascii_symbol_map();
1991 }
1992 if (map == medium_cons_ascii_string_map()) {
1993 return medium_cons_ascii_symbol_map();
1994 }
1995 if (map == long_cons_ascii_string_map()) {
1996 return long_cons_ascii_symbol_map();
1997 }
1998
1999 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002000 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2001 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002002
2003 if (map == short_sliced_ascii_string_map()) {
2004 return short_sliced_ascii_symbol_map();
2005 }
2006 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002007 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002008 }
2009 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002010 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002011 }
2012
2013 if (map == short_external_string_map()) return short_external_string_map();
2014 if (map == medium_external_string_map()) return medium_external_string_map();
2015 if (map == long_external_string_map()) return long_external_string_map();
2016
2017 if (map == short_external_ascii_string_map()) {
2018 return short_external_ascii_string_map();
2019 }
2020 if (map == medium_external_ascii_string_map()) {
2021 return medium_external_ascii_string_map();
2022 }
2023 if (map == long_external_ascii_string_map()) {
2024 return long_external_ascii_string_map();
2025 }
2026
2027 // No match found.
2028 return NULL;
2029}
2030
2031
2032Object* Heap::AllocateSymbol(unibrow::CharacterStream* buffer,
2033 int chars,
ager@chromium.org7c537e22008-10-16 08:43:32 +00002034 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002035 // Ensure the chars matches the number of characters in the buffer.
2036 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2037 // Determine whether the string is ascii.
2038 bool is_ascii = true;
2039 while (buffer->has_more()) {
2040 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2041 }
2042 buffer->Rewind();
2043
2044 // Compute map and object size.
2045 int size;
2046 Map* map;
2047
2048 if (is_ascii) {
2049 if (chars <= String::kMaxShortStringSize) {
2050 map = short_ascii_symbol_map();
2051 } else if (chars <= String::kMaxMediumStringSize) {
2052 map = medium_ascii_symbol_map();
2053 } else {
2054 map = long_ascii_symbol_map();
2055 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002056 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002057 } else {
2058 if (chars <= String::kMaxShortStringSize) {
2059 map = short_symbol_map();
2060 } else if (chars <= String::kMaxMediumStringSize) {
2061 map = medium_symbol_map();
2062 } else {
2063 map = long_symbol_map();
2064 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002065 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002066 }
2067
2068 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002069 AllocationSpace space =
2070 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002071 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002072 if (result->IsFailure()) return result;
2073
2074 reinterpret_cast<HeapObject*>(result)->set_map(map);
2075 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002076 String* answer = String::cast(result);
2077 StringShape answer_shape(answer);
2078 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002079
ager@chromium.org870a0b62008-11-04 11:43:05 +00002080 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002081
2082 // Fill in the characters.
2083 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002084 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002085 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002086 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002087}
2088
2089
2090Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002091 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002092 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002093 if (size > MaxHeapObjectSize()) {
2094 space = LO_SPACE;
2095 }
2096
2097 // Use AllocateRaw rather than Allocate because the object's size cannot be
2098 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002099 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002100 if (result->IsFailure()) return result;
2101
2102 // Determine the map based on the string's length.
2103 Map* map;
2104 if (length <= String::kMaxShortStringSize) {
2105 map = short_ascii_string_map();
2106 } else if (length <= String::kMaxMediumStringSize) {
2107 map = medium_ascii_string_map();
2108 } else {
2109 map = long_ascii_string_map();
2110 }
2111
2112 // Partially initialize the object.
2113 HeapObject::cast(result)->set_map(map);
2114 String::cast(result)->set_length(length);
2115 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2116 return result;
2117}
2118
2119
2120Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002121 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002122 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002123 if (size > MaxHeapObjectSize()) {
2124 space = LO_SPACE;
2125 }
2126
2127 // Use AllocateRaw rather than Allocate because the object's size cannot be
2128 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002129 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002130 if (result->IsFailure()) return result;
2131
2132 // Determine the map based on the string's length.
2133 Map* map;
2134 if (length <= String::kMaxShortStringSize) {
2135 map = short_string_map();
2136 } else if (length <= String::kMaxMediumStringSize) {
2137 map = medium_string_map();
2138 } else {
2139 map = long_string_map();
2140 }
2141
2142 // Partially initialize the object.
2143 HeapObject::cast(result)->set_map(map);
2144 String::cast(result)->set_length(length);
2145 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2146 return result;
2147}
2148
2149
2150Object* Heap::AllocateEmptyFixedArray() {
2151 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002152 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002153 if (result->IsFailure()) return result;
2154 // Initialize the object.
2155 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2156 reinterpret_cast<Array*>(result)->set_length(0);
2157 return result;
2158}
2159
2160
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002161Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002162 // Use the general function if we're forced to always allocate.
2163 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002164 // Allocate the raw data for a fixed array.
2165 int size = FixedArray::SizeFor(length);
2166 return (size > MaxHeapObjectSize())
2167 ? lo_space_->AllocateRawFixedArray(size)
2168 : new_space_.AllocateRaw(size);
2169}
2170
2171
2172Object* Heap::CopyFixedArray(FixedArray* src) {
2173 int len = src->length();
2174 Object* obj = AllocateRawFixedArray(len);
2175 if (obj->IsFailure()) return obj;
2176 if (Heap::InNewSpace(obj)) {
2177 HeapObject* dst = HeapObject::cast(obj);
2178 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2179 reinterpret_cast<Object**>(src->address()),
2180 FixedArray::SizeFor(len));
2181 return obj;
2182 }
2183 HeapObject::cast(obj)->set_map(src->map());
2184 FixedArray* result = FixedArray::cast(obj);
2185 result->set_length(len);
2186 // Copy the content
2187 WriteBarrierMode mode = result->GetWriteBarrierMode();
2188 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2189 return result;
2190}
2191
2192
2193Object* Heap::AllocateFixedArray(int length) {
2194 Object* result = AllocateRawFixedArray(length);
2195 if (!result->IsFailure()) {
2196 // Initialize header.
2197 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2198 FixedArray* array = FixedArray::cast(result);
2199 array->set_length(length);
2200 Object* value = undefined_value();
2201 // Initialize body.
2202 for (int index = 0; index < length; index++) {
2203 array->set(index, value, SKIP_WRITE_BARRIER);
2204 }
2205 }
2206 return result;
2207}
2208
2209
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002210Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2211 ASSERT(empty_fixed_array()->IsFixedArray());
2212 if (length == 0) return empty_fixed_array();
2213
2214 int size = FixedArray::SizeFor(length);
2215 Object* result;
2216 if (size > MaxHeapObjectSize()) {
2217 result = lo_space_->AllocateRawFixedArray(size);
2218 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002219 AllocationSpace space =
2220 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002221 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002222 }
2223 if (result->IsFailure()) return result;
2224
2225 // Initialize the object.
2226 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2227 FixedArray* array = FixedArray::cast(result);
2228 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002229 Object* value = undefined_value();
2230 for (int index = 0; index < length; index++) {
2231 array->set(index, value, SKIP_WRITE_BARRIER);
2232 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002233 return array;
2234}
2235
2236
2237Object* Heap::AllocateFixedArrayWithHoles(int length) {
2238 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002239 Object* result = AllocateRawFixedArray(length);
2240 if (!result->IsFailure()) {
2241 // Initialize header.
2242 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2243 FixedArray* array = FixedArray::cast(result);
2244 array->set_length(length);
2245 // Initialize body.
2246 Object* value = the_hole_value();
2247 for (int index = 0; index < length; index++) {
2248 array->set(index, value, SKIP_WRITE_BARRIER);
2249 }
2250 }
2251 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002252}
2253
2254
2255Object* Heap::AllocateHashTable(int length) {
2256 Object* result = Heap::AllocateFixedArray(length);
2257 if (result->IsFailure()) return result;
2258 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2259 ASSERT(result->IsDictionary());
2260 return result;
2261}
2262
2263
2264Object* Heap::AllocateGlobalContext() {
2265 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2266 if (result->IsFailure()) return result;
2267 Context* context = reinterpret_cast<Context*>(result);
2268 context->set_map(global_context_map());
2269 ASSERT(context->IsGlobalContext());
2270 ASSERT(result->IsContext());
2271 return result;
2272}
2273
2274
2275Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2276 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2277 Object* result = Heap::AllocateFixedArray(length);
2278 if (result->IsFailure()) return result;
2279 Context* context = reinterpret_cast<Context*>(result);
2280 context->set_map(context_map());
2281 context->set_closure(function);
2282 context->set_fcontext(context);
2283 context->set_previous(NULL);
2284 context->set_extension(NULL);
2285 context->set_global(function->context()->global());
2286 ASSERT(!context->IsGlobalContext());
2287 ASSERT(context->is_function_context());
2288 ASSERT(result->IsContext());
2289 return result;
2290}
2291
2292
2293Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2294 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2295 if (result->IsFailure()) return result;
2296 Context* context = reinterpret_cast<Context*>(result);
2297 context->set_map(context_map());
2298 context->set_closure(previous->closure());
2299 context->set_fcontext(previous->fcontext());
2300 context->set_previous(previous);
2301 context->set_extension(extension);
2302 context->set_global(previous->global());
2303 ASSERT(!context->IsGlobalContext());
2304 ASSERT(!context->is_function_context());
2305 ASSERT(result->IsContext());
2306 return result;
2307}
2308
2309
2310Object* Heap::AllocateStruct(InstanceType type) {
2311 Map* map;
2312 switch (type) {
2313#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2314STRUCT_LIST(MAKE_CASE)
2315#undef MAKE_CASE
2316 default:
2317 UNREACHABLE();
2318 return Failure::InternalError();
2319 }
2320 int size = map->instance_size();
2321 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002322 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002323 Object* result = Heap::Allocate(map, space);
2324 if (result->IsFailure()) return result;
2325 Struct::cast(result)->InitializeBody(size);
2326 return result;
2327}
2328
2329
2330#ifdef DEBUG
2331
2332void Heap::Print() {
2333 if (!HasBeenSetup()) return;
2334 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002335 AllSpaces spaces;
2336 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002337}
2338
2339
2340void Heap::ReportCodeStatistics(const char* title) {
2341 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2342 PagedSpace::ResetCodeStatistics();
2343 // We do not look for code in new space, map space, or old space. If code
2344 // somehow ends up in those spaces, we would miss it here.
2345 code_space_->CollectCodeStatistics();
2346 lo_space_->CollectCodeStatistics();
2347 PagedSpace::ReportCodeStatistics();
2348}
2349
2350
2351// This function expects that NewSpace's allocated objects histogram is
2352// populated (via a call to CollectStatistics or else as a side effect of a
2353// just-completed scavenge collection).
2354void Heap::ReportHeapStatistics(const char* title) {
2355 USE(title);
2356 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2357 title, gc_count_);
2358 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002359 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2360 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002361
2362 PrintF("\n");
2363 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2364 GlobalHandles::PrintStats();
2365 PrintF("\n");
2366
2367 PrintF("Heap statistics : ");
2368 MemoryAllocator::ReportStatistics();
2369 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002370 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002371 PrintF("Old pointer space : ");
2372 old_pointer_space_->ReportStatistics();
2373 PrintF("Old data space : ");
2374 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002375 PrintF("Code space : ");
2376 code_space_->ReportStatistics();
2377 PrintF("Map space : ");
2378 map_space_->ReportStatistics();
2379 PrintF("Large object space : ");
2380 lo_space_->ReportStatistics();
2381 PrintF(">>>>>> ========================================= >>>>>>\n");
2382}
2383
2384#endif // DEBUG
2385
2386bool Heap::Contains(HeapObject* value) {
2387 return Contains(value->address());
2388}
2389
2390
2391bool Heap::Contains(Address addr) {
2392 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2393 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002394 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002395 old_pointer_space_->Contains(addr) ||
2396 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002397 code_space_->Contains(addr) ||
2398 map_space_->Contains(addr) ||
2399 lo_space_->SlowContains(addr));
2400}
2401
2402
2403bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2404 return InSpace(value->address(), space);
2405}
2406
2407
2408bool Heap::InSpace(Address addr, AllocationSpace space) {
2409 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2410 if (!HasBeenSetup()) return false;
2411
2412 switch (space) {
2413 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002414 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002415 case OLD_POINTER_SPACE:
2416 return old_pointer_space_->Contains(addr);
2417 case OLD_DATA_SPACE:
2418 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002419 case CODE_SPACE:
2420 return code_space_->Contains(addr);
2421 case MAP_SPACE:
2422 return map_space_->Contains(addr);
2423 case LO_SPACE:
2424 return lo_space_->SlowContains(addr);
2425 }
2426
2427 return false;
2428}
2429
2430
2431#ifdef DEBUG
2432void Heap::Verify() {
2433 ASSERT(HasBeenSetup());
2434
2435 VerifyPointersVisitor visitor;
2436 Heap::IterateRoots(&visitor);
2437
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002438 AllSpaces spaces;
2439 while (Space* space = spaces.next()) {
2440 space->Verify();
2441 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002442}
2443#endif // DEBUG
2444
2445
2446Object* Heap::LookupSymbol(Vector<const char> string) {
2447 Object* symbol = NULL;
2448 Object* new_table =
2449 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2450 if (new_table->IsFailure()) return new_table;
2451 symbol_table_ = new_table;
2452 ASSERT(symbol != NULL);
2453 return symbol;
2454}
2455
2456
2457Object* Heap::LookupSymbol(String* string) {
2458 if (string->IsSymbol()) return string;
2459 Object* symbol = NULL;
2460 Object* new_table =
2461 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2462 if (new_table->IsFailure()) return new_table;
2463 symbol_table_ = new_table;
2464 ASSERT(symbol != NULL);
2465 return symbol;
2466}
2467
2468
ager@chromium.org7c537e22008-10-16 08:43:32 +00002469bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2470 if (string->IsSymbol()) {
2471 *symbol = string;
2472 return true;
2473 }
2474 SymbolTable* table = SymbolTable::cast(symbol_table_);
2475 return table->LookupSymbolIfExists(string, symbol);
2476}
2477
2478
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002479#ifdef DEBUG
2480void Heap::ZapFromSpace() {
2481 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002482 for (Address a = new_space_.FromSpaceLow();
2483 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002484 a += kPointerSize) {
2485 Memory::Address_at(a) = kFromSpaceZapValue;
2486 }
2487}
2488#endif // DEBUG
2489
2490
2491void Heap::IterateRSetRange(Address object_start,
2492 Address object_end,
2493 Address rset_start,
2494 ObjectSlotCallback copy_object_func) {
2495 Address object_address = object_start;
2496 Address rset_address = rset_start;
2497
2498 // Loop over all the pointers in [object_start, object_end).
2499 while (object_address < object_end) {
2500 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002501 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002502 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002503 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002504 // Do not dereference pointers at or past object_end.
2505 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2506 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002507 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002508 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2509 }
2510 // If this pointer does not need to be remembered anymore, clear
2511 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002512 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002513 }
2514 object_address += kPointerSize;
2515 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002516 // Update the remembered set if it has changed.
2517 if (result_rset != rset_word) {
2518 Memory::uint32_at(rset_address) = result_rset;
2519 }
2520 } else {
2521 // No bits in the word were set. This is the common case.
2522 object_address += kPointerSize * kBitsPerInt;
2523 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002524 rset_address += kIntSize;
2525 }
2526}
2527
2528
2529void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2530 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002531 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002532
2533 PageIterator it(space, PageIterator::PAGES_IN_USE);
2534 while (it.has_next()) {
2535 Page* page = it.next();
2536 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2537 page->RSetStart(), copy_object_func);
2538 }
2539}
2540
2541
2542#ifdef DEBUG
2543#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2544#else
2545#define SYNCHRONIZE_TAG(tag)
2546#endif
2547
2548void Heap::IterateRoots(ObjectVisitor* v) {
2549 IterateStrongRoots(v);
2550 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2551 SYNCHRONIZE_TAG("symbol_table");
2552}
2553
2554
2555void Heap::IterateStrongRoots(ObjectVisitor* v) {
2556#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002557 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002558 STRONG_ROOT_LIST(ROOT_ITERATE);
2559#undef ROOT_ITERATE
2560 SYNCHRONIZE_TAG("strong_root_list");
2561
2562#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002563 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002564 STRUCT_LIST(STRUCT_MAP_ITERATE);
2565#undef STRUCT_MAP_ITERATE
2566 SYNCHRONIZE_TAG("struct_map");
2567
2568#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002569 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002570 SYMBOL_LIST(SYMBOL_ITERATE)
2571#undef SYMBOL_ITERATE
2572 SYNCHRONIZE_TAG("symbol");
2573
2574 Bootstrapper::Iterate(v);
2575 SYNCHRONIZE_TAG("bootstrapper");
2576 Top::Iterate(v);
2577 SYNCHRONIZE_TAG("top");
2578 Debug::Iterate(v);
2579 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002580 CompilationCache::Iterate(v);
2581 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002582
2583 // Iterate over local handles in handle scopes.
2584 HandleScopeImplementer::Iterate(v);
2585 SYNCHRONIZE_TAG("handlescope");
2586
2587 // Iterate over the builtin code objects and code stubs in the heap. Note
2588 // that it is not strictly necessary to iterate over code objects on
2589 // scavenge collections. We still do it here because this same function
2590 // is used by the mark-sweep collector and the deserializer.
2591 Builtins::IterateBuiltins(v);
2592 SYNCHRONIZE_TAG("builtins");
2593
2594 // Iterate over global handles.
2595 GlobalHandles::IterateRoots(v);
2596 SYNCHRONIZE_TAG("globalhandles");
2597
2598 // Iterate over pointers being held by inactive threads.
2599 ThreadManager::Iterate(v);
2600 SYNCHRONIZE_TAG("threadmanager");
2601}
2602#undef SYNCHRONIZE_TAG
2603
2604
2605// Flag is set when the heap has been configured. The heap can be repeatedly
2606// configured through the API until it is setup.
2607static bool heap_configured = false;
2608
2609// TODO(1236194): Since the heap size is configurable on the command line
2610// and through the API, we should gracefully handle the case that the heap
2611// size is not big enough to fit all the initial objects.
2612bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2613 if (HasBeenSetup()) return false;
2614
2615 if (semispace_size > 0) semispace_size_ = semispace_size;
2616 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2617
2618 // The new space size must be a power of two to support single-bit testing
2619 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002620 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002621 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2622 young_generation_size_ = 2 * semispace_size_;
2623
2624 // The old generation is paged.
2625 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2626
2627 heap_configured = true;
2628 return true;
2629}
2630
2631
kasper.lund7276f142008-07-30 08:49:36 +00002632bool Heap::ConfigureHeapDefault() {
2633 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2634}
2635
2636
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002637int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002638 return old_pointer_space_->Size()
2639 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002640 + code_space_->Size()
2641 + map_space_->Size()
2642 + lo_space_->Size();
2643}
2644
2645
kasper.lund7276f142008-07-30 08:49:36 +00002646int Heap::PromotedExternalMemorySize() {
2647 if (amount_of_external_allocated_memory_
2648 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2649 return amount_of_external_allocated_memory_
2650 - amount_of_external_allocated_memory_at_last_global_gc_;
2651}
2652
2653
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002654bool Heap::Setup(bool create_heap_objects) {
2655 // Initialize heap spaces and initial maps and objects. Whenever something
2656 // goes wrong, just return false. The caller should check the results and
2657 // call Heap::TearDown() to release allocated memory.
2658 //
2659 // If the heap is not yet configured (eg, through the API), configure it.
2660 // Configuration is based on the flags new-space-size (really the semispace
2661 // size) and old-space-size if set or the initial values of semispace_size_
2662 // and old_generation_size_ otherwise.
2663 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002664 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002665 }
2666
2667 // Setup memory allocator and allocate an initial chunk of memory. The
2668 // initial chunk is double the size of the new space to ensure that we can
2669 // find a pair of semispaces that are contiguous and aligned to their size.
2670 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2671 void* chunk
2672 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2673 if (chunk == NULL) return false;
2674
2675 // Put the initial chunk of the old space at the start of the initial
2676 // chunk, then the two new space semispaces, then the initial chunk of
2677 // code space. Align the pair of semispaces to their size, which must be
2678 // a power of 2.
2679 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002680 Address code_space_start = reinterpret_cast<Address>(chunk);
2681 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2682 Address old_space_start = new_space_start + young_generation_size_;
2683 int code_space_size = new_space_start - code_space_start;
2684 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002685
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002686 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002687 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002688
2689 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002690 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002691 old_pointer_space_ =
2692 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2693 if (old_pointer_space_ == NULL) return false;
2694 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2695 return false;
2696 }
2697 old_data_space_ =
2698 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2699 if (old_data_space_ == NULL) return false;
2700 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2701 old_space_size >> 1)) {
2702 return false;
2703 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002704
2705 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002706 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002707 code_space_ =
2708 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002709 if (code_space_ == NULL) return false;
2710 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2711
2712 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002713 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002714 if (map_space_ == NULL) return false;
2715 // Setting up a paged space without giving it a virtual memory range big
2716 // enough to hold at least a page will cause it to allocate.
2717 if (!map_space_->Setup(NULL, 0)) return false;
2718
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002719 // The large object code space may contain code or data. We set the memory
2720 // to be non-executable here for safety, but this means we need to enable it
2721 // explicitly when allocating large code objects.
2722 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002723 if (lo_space_ == NULL) return false;
2724 if (!lo_space_->Setup()) return false;
2725
2726 if (create_heap_objects) {
2727 // Create initial maps.
2728 if (!CreateInitialMaps()) return false;
2729 if (!CreateApiObjects()) return false;
2730
2731 // Create initial objects
2732 if (!CreateInitialObjects()) return false;
2733 }
2734
2735 LOG(IntEvent("heap-capacity", Capacity()));
2736 LOG(IntEvent("heap-available", Available()));
2737
2738 return true;
2739}
2740
2741
2742void Heap::TearDown() {
2743 GlobalHandles::TearDown();
2744
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002745 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002746
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002747 if (old_pointer_space_ != NULL) {
2748 old_pointer_space_->TearDown();
2749 delete old_pointer_space_;
2750 old_pointer_space_ = NULL;
2751 }
2752
2753 if (old_data_space_ != NULL) {
2754 old_data_space_->TearDown();
2755 delete old_data_space_;
2756 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002757 }
2758
2759 if (code_space_ != NULL) {
2760 code_space_->TearDown();
2761 delete code_space_;
2762 code_space_ = NULL;
2763 }
2764
2765 if (map_space_ != NULL) {
2766 map_space_->TearDown();
2767 delete map_space_;
2768 map_space_ = NULL;
2769 }
2770
2771 if (lo_space_ != NULL) {
2772 lo_space_->TearDown();
2773 delete lo_space_;
2774 lo_space_ = NULL;
2775 }
2776
2777 MemoryAllocator::TearDown();
2778}
2779
2780
2781void Heap::Shrink() {
2782 // Try to shrink map, old, and code spaces.
2783 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002784 old_pointer_space_->Shrink();
2785 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002786 code_space_->Shrink();
2787}
2788
2789
2790#ifdef DEBUG
2791
2792class PrintHandleVisitor: public ObjectVisitor {
2793 public:
2794 void VisitPointers(Object** start, Object** end) {
2795 for (Object** p = start; p < end; p++)
2796 PrintF(" handle %p to %p\n", p, *p);
2797 }
2798};
2799
2800void Heap::PrintHandles() {
2801 PrintF("Handles:\n");
2802 PrintHandleVisitor v;
2803 HandleScopeImplementer::Iterate(&v);
2804}
2805
2806#endif
2807
2808
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002809Space* AllSpaces::next() {
2810 switch (counter_++) {
2811 case NEW_SPACE:
2812 return Heap::new_space();
2813 case OLD_POINTER_SPACE:
2814 return Heap::old_pointer_space();
2815 case OLD_DATA_SPACE:
2816 return Heap::old_data_space();
2817 case CODE_SPACE:
2818 return Heap::code_space();
2819 case MAP_SPACE:
2820 return Heap::map_space();
2821 case LO_SPACE:
2822 return Heap::lo_space();
2823 default:
2824 return NULL;
2825 }
2826}
2827
2828
2829PagedSpace* PagedSpaces::next() {
2830 switch (counter_++) {
2831 case OLD_POINTER_SPACE:
2832 return Heap::old_pointer_space();
2833 case OLD_DATA_SPACE:
2834 return Heap::old_data_space();
2835 case CODE_SPACE:
2836 return Heap::code_space();
2837 case MAP_SPACE:
2838 return Heap::map_space();
2839 default:
2840 return NULL;
2841 }
2842}
2843
2844
2845
2846OldSpace* OldSpaces::next() {
2847 switch (counter_++) {
2848 case OLD_POINTER_SPACE:
2849 return Heap::old_pointer_space();
2850 case OLD_DATA_SPACE:
2851 return Heap::old_data_space();
2852 case CODE_SPACE:
2853 return Heap::code_space();
2854 default:
2855 return NULL;
2856 }
2857}
2858
2859
kasper.lund7276f142008-07-30 08:49:36 +00002860SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2861}
2862
2863
2864SpaceIterator::~SpaceIterator() {
2865 // Delete active iterator if any.
2866 delete iterator_;
2867}
2868
2869
2870bool SpaceIterator::has_next() {
2871 // Iterate until no more spaces.
2872 return current_space_ != LAST_SPACE;
2873}
2874
2875
2876ObjectIterator* SpaceIterator::next() {
2877 if (iterator_ != NULL) {
2878 delete iterator_;
2879 iterator_ = NULL;
2880 // Move to the next space
2881 current_space_++;
2882 if (current_space_ > LAST_SPACE) {
2883 return NULL;
2884 }
2885 }
2886
2887 // Return iterator for the new current space.
2888 return CreateIterator();
2889}
2890
2891
2892// Create an iterator for the space to iterate.
2893ObjectIterator* SpaceIterator::CreateIterator() {
2894 ASSERT(iterator_ == NULL);
2895
2896 switch (current_space_) {
2897 case NEW_SPACE:
2898 iterator_ = new SemiSpaceIterator(Heap::new_space());
2899 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002900 case OLD_POINTER_SPACE:
2901 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2902 break;
2903 case OLD_DATA_SPACE:
2904 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002905 break;
2906 case CODE_SPACE:
2907 iterator_ = new HeapObjectIterator(Heap::code_space());
2908 break;
2909 case MAP_SPACE:
2910 iterator_ = new HeapObjectIterator(Heap::map_space());
2911 break;
2912 case LO_SPACE:
2913 iterator_ = new LargeObjectIterator(Heap::lo_space());
2914 break;
2915 }
2916
2917 // Return the newly allocated iterator;
2918 ASSERT(iterator_ != NULL);
2919 return iterator_;
2920}
2921
2922
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002923HeapIterator::HeapIterator() {
2924 Init();
2925}
2926
2927
2928HeapIterator::~HeapIterator() {
2929 Shutdown();
2930}
2931
2932
2933void HeapIterator::Init() {
2934 // Start the iteration.
2935 space_iterator_ = new SpaceIterator();
2936 object_iterator_ = space_iterator_->next();
2937}
2938
2939
2940void HeapIterator::Shutdown() {
2941 // Make sure the last iterator is deallocated.
2942 delete space_iterator_;
2943 space_iterator_ = NULL;
2944 object_iterator_ = NULL;
2945}
2946
2947
2948bool HeapIterator::has_next() {
2949 // No iterator means we are done.
2950 if (object_iterator_ == NULL) return false;
2951
2952 if (object_iterator_->has_next_object()) {
2953 // If the current iterator has more objects we are fine.
2954 return true;
2955 } else {
2956 // Go though the spaces looking for one that has objects.
2957 while (space_iterator_->has_next()) {
2958 object_iterator_ = space_iterator_->next();
2959 if (object_iterator_->has_next_object()) {
2960 return true;
2961 }
2962 }
2963 }
2964 // Done with the last space.
2965 object_iterator_ = NULL;
2966 return false;
2967}
2968
2969
2970HeapObject* HeapIterator::next() {
2971 if (has_next()) {
2972 return object_iterator_->next_object();
2973 } else {
2974 return NULL;
2975 }
2976}
2977
2978
2979void HeapIterator::reset() {
2980 // Restart the iterator.
2981 Shutdown();
2982 Init();
2983}
2984
2985
2986//
2987// HeapProfiler class implementation.
2988//
2989#ifdef ENABLE_LOGGING_AND_PROFILING
2990void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
2991 InstanceType type = obj->map()->instance_type();
2992 ASSERT(0 <= type && type <= LAST_TYPE);
2993 info[type].increment_number(1);
2994 info[type].increment_bytes(obj->Size());
2995}
2996#endif
2997
2998
2999#ifdef ENABLE_LOGGING_AND_PROFILING
3000void HeapProfiler::WriteSample() {
3001 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3002
3003 HistogramInfo info[LAST_TYPE+1];
3004#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3005 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3006#undef DEF_TYPE_NAME
3007
3008 HeapIterator iterator;
3009 while (iterator.has_next()) {
3010 CollectStats(iterator.next(), info);
3011 }
3012
3013 // Lump all the string types together.
3014 int string_number = 0;
3015 int string_bytes = 0;
3016#define INCREMENT_SIZE(type, size, name) \
3017 string_number += info[type].number(); \
3018 string_bytes += info[type].bytes();
3019 STRING_TYPE_LIST(INCREMENT_SIZE)
3020#undef INCREMENT_SIZE
3021 if (string_bytes > 0) {
3022 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3023 }
3024
3025 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3026 if (info[i].bytes() > 0) {
3027 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3028 info[i].bytes()));
3029 }
3030 }
3031
3032 LOG(HeapSampleEndEvent("Heap", "allocated"));
3033}
3034
3035
3036#endif
3037
3038
3039
3040#ifdef DEBUG
3041
3042static bool search_for_any_global;
3043static Object* search_target;
3044static bool found_target;
3045static List<Object*> object_stack(20);
3046
3047
3048// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3049static const int kMarkTag = 2;
3050
3051static void MarkObjectRecursively(Object** p);
3052class MarkObjectVisitor : public ObjectVisitor {
3053 public:
3054 void VisitPointers(Object** start, Object** end) {
3055 // Copy all HeapObject pointers in [start, end)
3056 for (Object** p = start; p < end; p++) {
3057 if ((*p)->IsHeapObject())
3058 MarkObjectRecursively(p);
3059 }
3060 }
3061};
3062
3063static MarkObjectVisitor mark_visitor;
3064
3065static void MarkObjectRecursively(Object** p) {
3066 if (!(*p)->IsHeapObject()) return;
3067
3068 HeapObject* obj = HeapObject::cast(*p);
3069
3070 Object* map = obj->map();
3071
3072 if (!map->IsHeapObject()) return; // visited before
3073
3074 if (found_target) return; // stop if target found
3075 object_stack.Add(obj);
3076 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3077 (!search_for_any_global && (obj == search_target))) {
3078 found_target = true;
3079 return;
3080 }
3081
3082 if (obj->IsCode()) {
3083 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3084 }
3085
3086 // not visited yet
3087 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3088
3089 Address map_addr = map_p->address();
3090
3091 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3092
3093 MarkObjectRecursively(&map);
3094
3095 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3096 &mark_visitor);
3097
3098 if (!found_target) // don't pop if found the target
3099 object_stack.RemoveLast();
3100}
3101
3102
3103static void UnmarkObjectRecursively(Object** p);
3104class UnmarkObjectVisitor : public ObjectVisitor {
3105 public:
3106 void VisitPointers(Object** start, Object** end) {
3107 // Copy all HeapObject pointers in [start, end)
3108 for (Object** p = start; p < end; p++) {
3109 if ((*p)->IsHeapObject())
3110 UnmarkObjectRecursively(p);
3111 }
3112 }
3113};
3114
3115static UnmarkObjectVisitor unmark_visitor;
3116
3117static void UnmarkObjectRecursively(Object** p) {
3118 if (!(*p)->IsHeapObject()) return;
3119
3120 HeapObject* obj = HeapObject::cast(*p);
3121
3122 Object* map = obj->map();
3123
3124 if (map->IsHeapObject()) return; // unmarked already
3125
3126 Address map_addr = reinterpret_cast<Address>(map);
3127
3128 map_addr -= kMarkTag;
3129
3130 ASSERT_TAG_ALIGNED(map_addr);
3131
3132 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3133
3134 obj->set_map(reinterpret_cast<Map*>(map_p));
3135
3136 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3137
3138 obj->IterateBody(Map::cast(map_p)->instance_type(),
3139 obj->SizeFromMap(Map::cast(map_p)),
3140 &unmark_visitor);
3141
3142 if (obj->IsCode()) {
3143 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3144 }
3145}
3146
3147
3148static void MarkRootObjectRecursively(Object** root) {
3149 if (search_for_any_global) {
3150 ASSERT(search_target == NULL);
3151 } else {
3152 ASSERT(search_target->IsHeapObject());
3153 }
3154 found_target = false;
3155 object_stack.Clear();
3156
3157 MarkObjectRecursively(root);
3158 UnmarkObjectRecursively(root);
3159
3160 if (found_target) {
3161 PrintF("=====================================\n");
3162 PrintF("==== Path to object ====\n");
3163 PrintF("=====================================\n\n");
3164
3165 ASSERT(!object_stack.is_empty());
3166 for (int i = 0; i < object_stack.length(); i++) {
3167 if (i > 0) PrintF("\n |\n |\n V\n\n");
3168 Object* obj = object_stack[i];
3169 obj->Print();
3170 }
3171 PrintF("=====================================\n");
3172 }
3173}
3174
3175
3176// Helper class for visiting HeapObjects recursively.
3177class MarkRootVisitor: public ObjectVisitor {
3178 public:
3179 void VisitPointers(Object** start, Object** end) {
3180 // Visit all HeapObject pointers in [start, end)
3181 for (Object** p = start; p < end; p++) {
3182 if ((*p)->IsHeapObject())
3183 MarkRootObjectRecursively(p);
3184 }
3185 }
3186};
3187
3188
3189// Triggers a depth-first traversal of reachable objects from roots
3190// and finds a path to a specific heap object and prints it.
3191void Heap::TracePathToObject() {
3192 search_target = NULL;
3193 search_for_any_global = false;
3194
3195 MarkRootVisitor root_visitor;
3196 IterateRoots(&root_visitor);
3197}
3198
3199
3200// Triggers a depth-first traversal of reachable objects from roots
3201// and finds a path to any global object and prints it. Useful for
3202// determining the source for leaks of global objects.
3203void Heap::TracePathToGlobal() {
3204 search_target = NULL;
3205 search_for_any_global = true;
3206
3207 MarkRootVisitor root_visitor;
3208 IterateRoots(&root_visitor);
3209}
3210#endif
3211
3212
kasper.lund7276f142008-07-30 08:49:36 +00003213GCTracer::GCTracer()
3214 : start_time_(0.0),
3215 start_size_(0.0),
3216 gc_count_(0),
3217 full_gc_count_(0),
3218 is_compacting_(false),
3219 marked_count_(0) {
3220 // These two fields reflect the state of the previous full collection.
3221 // Set them before they are changed by the collector.
3222 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3223 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3224 if (!FLAG_trace_gc) return;
3225 start_time_ = OS::TimeCurrentMillis();
3226 start_size_ = SizeOfHeapObjects();
3227}
3228
3229
3230GCTracer::~GCTracer() {
3231 if (!FLAG_trace_gc) return;
3232 // Printf ONE line iff flag is set.
3233 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3234 CollectorString(),
3235 start_size_, SizeOfHeapObjects(),
3236 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3237}
3238
3239
3240const char* GCTracer::CollectorString() {
3241 switch (collector_) {
3242 case SCAVENGER:
3243 return "Scavenge";
3244 case MARK_COMPACTOR:
3245 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3246 : "Mark-sweep";
3247 }
3248 return "Unknown GC";
3249}
3250
3251
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003252#ifdef DEBUG
3253bool Heap::GarbageCollectionGreedyCheck() {
3254 ASSERT(FLAG_gc_greedy);
3255 if (Bootstrapper::IsActive()) return true;
3256 if (disallow_allocation_failure()) return true;
3257 return CollectGarbage(0, NEW_SPACE);
3258}
3259#endif
3260
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003261} } // namespace v8::internal