blob: 8159311122fa1356f4f38280a4624b2feed12b6c [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;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000100bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000101
kasper.lund7276f142008-07-30 08:49:36 +0000102#ifdef DEBUG
103bool Heap::allocation_allowed_ = true;
104
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000105int Heap::allocation_timeout_ = 0;
106bool Heap::disallow_allocation_failure_ = false;
107#endif // DEBUG
108
109
110int Heap::Capacity() {
111 if (!HasBeenSetup()) return 0;
112
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000113 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000114 old_pointer_space_->Capacity() +
115 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000116 code_space_->Capacity() +
117 map_space_->Capacity();
118}
119
120
121int Heap::Available() {
122 if (!HasBeenSetup()) return 0;
123
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000124 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000125 old_pointer_space_->Available() +
126 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000127 code_space_->Available() +
128 map_space_->Available();
129}
130
131
132bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000133 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000134 old_data_space_ != NULL &&
135 code_space_ != NULL &&
136 map_space_ != NULL &&
137 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000138}
139
140
141GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
142 // Is global GC requested?
143 if (space != NEW_SPACE || FLAG_gc_global) {
144 Counters::gc_compactor_caused_by_request.Increment();
145 return MARK_COMPACTOR;
146 }
147
148 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000149 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000150 Counters::gc_compactor_caused_by_promoted_data.Increment();
151 return MARK_COMPACTOR;
152 }
153
154 // Have allocation in OLD and LO failed?
155 if (old_gen_exhausted_) {
156 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
157 return MARK_COMPACTOR;
158 }
159
160 // Is there enough space left in OLD to guarantee that a scavenge can
161 // succeed?
162 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000163 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000164 // for object promotion. It counts only the bytes that the memory
165 // allocator has not yet allocated from the OS and assigned to any space,
166 // and does not count available bytes already in the old space or code
167 // space. Undercounting is safe---we may get an unrequested full GC when
168 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000169 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000170 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
171 return MARK_COMPACTOR;
172 }
173
174 // Default
175 return SCAVENGER;
176}
177
178
179// TODO(1238405): Combine the infrastructure for --heap-stats and
180// --log-gc to avoid the complicated preprocessor and flag testing.
181#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
182void Heap::ReportStatisticsBeforeGC() {
183 // Heap::ReportHeapStatistics will also log NewSpace statistics when
184 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
185 // following logic is used to avoid double logging.
186#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000187 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000188 if (FLAG_heap_stats) {
189 ReportHeapStatistics("Before GC");
190 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000191 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000192 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000193 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000194#elif defined(DEBUG)
195 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000196 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000197 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000198 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199 }
200#elif defined(ENABLE_LOGGING_AND_PROFILING)
201 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000202 new_space_.CollectStatistics();
203 new_space_.ReportStatistics();
204 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000205 }
206#endif
207}
208
209
210// TODO(1238405): Combine the infrastructure for --heap-stats and
211// --log-gc to avoid the complicated preprocessor and flag testing.
212void Heap::ReportStatisticsAfterGC() {
213 // Similar to the before GC, we use some complicated logic to ensure that
214 // NewSpace statistics are logged exactly once when --log-gc is turned on.
215#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
216 if (FLAG_heap_stats) {
217 ReportHeapStatistics("After GC");
218 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000219 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000220 }
221#elif defined(DEBUG)
222 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
223#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000224 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225#endif
226}
227#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
228
229
230void Heap::GarbageCollectionPrologue() {
231 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000232 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233#ifdef DEBUG
234 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
235 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237 if (FLAG_verify_heap) {
238 Verify();
239 }
240
241 if (FLAG_gc_verbose) Print();
242
243 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000244 // Not all spaces have remembered set bits that we care about.
245 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 map_space_->PrintRSet();
247 lo_space_->PrintRSet();
248 }
249#endif
250
251#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
252 ReportStatisticsBeforeGC();
253#endif
254}
255
256int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000257 int total = 0;
258 AllSpaces spaces;
259 while (Space* space = spaces.next()) total += space->Size();
260 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261}
262
263void Heap::GarbageCollectionEpilogue() {
264#ifdef DEBUG
265 allow_allocation(true);
266 ZapFromSpace();
267
268 if (FLAG_verify_heap) {
269 Verify();
270 }
271
272 if (FLAG_print_global_handles) GlobalHandles::Print();
273 if (FLAG_print_handles) PrintHandles();
274 if (FLAG_gc_verbose) Print();
275 if (FLAG_code_stats) ReportCodeStatistics("After GC");
276#endif
277
278 Counters::alive_after_last_gc.Set(SizeOfObjects());
279
280 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
281 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
282 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
283#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
284 ReportStatisticsAfterGC();
285#endif
286}
287
288
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000289void Heap::CollectAllGarbage() {
290 // Since we are ignoring the return value, the exact choice of space does
291 // not matter, so long as we do not specify NEW_SPACE, which would not
292 // cause a full GC.
293 CollectGarbage(0, OLD_POINTER_SPACE);
294}
295
296
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000297void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000298 // If the garbage collector interface is exposed through the global
299 // gc() function, we avoid being clever about forcing GCs when
300 // contexts are disposed and leave it to the embedder to make
301 // informed decisions about when to force a collection.
302 if (!FLAG_expose_gc && context_disposed_pending_) {
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000303 StatsRateScope scope(&Counters::gc_context);
304 CollectAllGarbage();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000305 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000306 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000307}
308
309
310void Heap::NotifyContextDisposed() {
311 context_disposed_pending_ = true;
312}
313
314
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000315bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
316 // The VM is in the GC state until exiting this function.
317 VMState state(GC);
318
319#ifdef DEBUG
320 // Reset the allocation timeout to the GC interval, but make sure to
321 // allow at least a few allocations after a collection. The reason
322 // for this is that we have a lot of allocation sequences and we
323 // assume that a garbage collection will allow the subsequent
324 // allocation attempts to go through.
325 allocation_timeout_ = Max(6, FLAG_gc_interval);
326#endif
327
328 { GCTracer tracer;
329 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000330 // The GC count was incremented in the prologue. Tell the tracer about
331 // it.
332 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333
334 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000335 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 tracer.set_collector(collector);
337
338 StatsRate* rate = (collector == SCAVENGER)
339 ? &Counters::gc_scavenger
340 : &Counters::gc_compactor;
341 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000342 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 rate->Stop();
344
345 GarbageCollectionEpilogue();
346 }
347
348
349#ifdef ENABLE_LOGGING_AND_PROFILING
350 if (FLAG_log_gc) HeapProfiler::WriteSample();
351#endif
352
353 switch (space) {
354 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000355 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000356 case OLD_POINTER_SPACE:
357 return old_pointer_space_->Available() >= requested_size;
358 case OLD_DATA_SPACE:
359 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 case CODE_SPACE:
361 return code_space_->Available() >= requested_size;
362 case MAP_SPACE:
363 return map_space_->Available() >= requested_size;
364 case LO_SPACE:
365 return lo_space_->Available() >= requested_size;
366 }
367 return false;
368}
369
370
kasper.lund7276f142008-07-30 08:49:36 +0000371void Heap::PerformScavenge() {
372 GCTracer tracer;
373 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
374}
375
376
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000377void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000378 GarbageCollector collector,
379 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000380 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
381 ASSERT(!allocation_allowed_);
382 global_gc_prologue_callback_();
383 }
384
385 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000386 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000387
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000388 int old_gen_size = PromotedSpaceSize();
389 old_gen_promotion_limit_ =
390 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
391 old_gen_allocation_limit_ =
392 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393 old_gen_exhausted_ = false;
394
395 // If we have used the mark-compact collector to collect the new
396 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000397 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000398 // case where (1) a new space collection was requested, (2) the
399 // collector selection policy selected the mark-compact collector,
400 // and (3) the mark-compact collector policy selected not to
401 // compact the new space. In that case, there is no more (usable)
402 // free space in the new space after the collection compared to
403 // before.
404 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
405 Scavenge();
406 }
407 } else {
408 Scavenge();
409 }
410 Counters::objs_since_last_young.Set(0);
411
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000412 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413
kasper.lund7276f142008-07-30 08:49:36 +0000414 if (collector == MARK_COMPACTOR) {
415 // Register the amount of external allocated memory.
416 amount_of_external_allocated_memory_at_last_global_gc_ =
417 amount_of_external_allocated_memory_;
418 }
419
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
421 ASSERT(!allocation_allowed_);
422 global_gc_epilogue_callback_();
423 }
424}
425
426
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000427void Heap::PostGarbageCollectionProcessing() {
428 // Process weak handles post gc.
429 GlobalHandles::PostGarbageCollectionProcessing();
430 // Update flat string readers.
431 FlatStringReader::PostGarbageCollectionProcessing();
432}
433
434
kasper.lund7276f142008-07-30 08:49:36 +0000435void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000436 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000437 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000438 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000439 LOG(ResourceEvent("markcompact", "begin"));
440
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000441 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000442
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000443 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000445 MarkCompactPrologue(is_compacting);
446
447 MarkCompactCollector::CollectGarbage();
448
449 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450
451 LOG(ResourceEvent("markcompact", "end"));
452
453 gc_state_ = NOT_IN_GC;
454
455 Shrink();
456
457 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000458 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000459}
460
461
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000462void Heap::MarkCompactPrologue(bool is_compacting) {
463 // At any old GC clear the keyed lookup cache to enable collection of unused
464 // maps.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000465 ClearKeyedLookupCache();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000466
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000467 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468 RegExpImpl::OldSpaceCollectionPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000469
470 Top::MarkCompactPrologue(is_compacting);
471 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472}
473
474
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000475void Heap::MarkCompactEpilogue(bool is_compacting) {
476 Top::MarkCompactEpilogue(is_compacting);
477 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000478}
479
480
481Object* Heap::FindCodeObject(Address a) {
482 Object* obj = code_space_->FindObject(a);
483 if (obj->IsFailure()) {
484 obj = lo_space_->FindObject(a);
485 }
kasper.lund7276f142008-07-30 08:49:36 +0000486 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487 return obj;
488}
489
490
491// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000492class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000493 public:
494
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000495 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000496
497 void VisitPointers(Object** start, Object** end) {
498 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000499 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500 }
501
502 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000503 void ScavengePointer(Object** p) {
504 Object* object = *p;
505 if (!Heap::InNewSpace(object)) return;
506 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
507 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508 }
509};
510
511
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000512// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513static Address promoted_top = NULL;
514
515
516#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000517// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000518// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000519class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 public:
521 void VisitPointers(Object** start, Object**end) {
522 for (Object** current = start; current < end; current++) {
523 if ((*current)->IsHeapObject()) {
524 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
525 }
526 }
527 }
528};
529#endif
530
531void Heap::Scavenge() {
532#ifdef DEBUG
533 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000534 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000535 HeapObjectIterator it(code_space_);
536 while (it.has_next()) {
537 HeapObject* object = it.next();
538 if (object->IsCode()) {
539 Code::cast(object)->ConvertICTargetsFromAddressToObject();
540 }
541 object->Iterate(&v);
542 if (object->IsCode()) {
543 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
544 }
545 }
546 }
547#endif
548
549 gc_state_ = SCAVENGE;
550
551 // Implements Cheney's copying algorithm
552 LOG(ResourceEvent("scavenge", "begin"));
553
554 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000555 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000556 scavenge_count_ > new_space_growth_limit_) {
557 // Double the size of the new space, and double the limit. The next
558 // doubling attempt will occur after the current new_space_growth_limit_
559 // more collections.
560 // TODO(1240712): NewSpace::Double has a return value which is
561 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000562 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563 new_space_growth_limit_ *= 2;
564 }
565
566 // Flip the semispaces. After flipping, to space is empty, from space has
567 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000568 new_space_.Flip();
569 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570
571 // We need to sweep newly copied objects which can be in either the to space
572 // or the old space. For to space objects, we use a mark. Newly copied
573 // objects lie between the mark and the allocation top. For objects
574 // promoted to old space, we write their addresses downward from the top of
575 // the new space. Sweeping newly promoted objects requires an allocation
576 // pointer and a mark. Note that the allocation pointer 'top' actually
577 // moves downward from the high address in the to space.
578 //
579 // There is guaranteed to be enough room at the top of the to space for the
580 // addresses of promoted objects: every object promoted frees up its size in
581 // bytes from the top of the new space, and objects are at least one pointer
582 // in size. Using the new space to record promoted addresses makes the
583 // scavenge collector agnostic to the allocation strategy (eg, linear or
584 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000585 Address new_mark = new_space_.ToSpaceLow();
586 Address promoted_mark = new_space_.ToSpaceHigh();
587 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000588
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000589 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000590 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000591 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000592
593 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000594 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000595 IterateRSet(old_pointer_space_, &ScavengePointer);
596 IterateRSet(map_space_, &ScavengePointer);
597 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598
599 bool has_processed_weak_pointers = false;
600
601 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000602 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000603 ASSERT(promoted_mark >= promoted_top);
604
605 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000606 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607 // Sweep newly copied objects in the to space. The allocation pointer
608 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000609 Address previous_top = new_space_.top();
610 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000612 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000613 }
614 new_mark = previous_top;
615
616 // Sweep newly copied objects in the old space. The promotion 'top'
617 // pointer could change during sweeping.
618 previous_top = promoted_top;
619 for (Address current = promoted_mark - kPointerSize;
620 current >= previous_top;
621 current -= kPointerSize) {
622 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000623 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000624 UpdateRSet(object);
625 }
626 promoted_mark = previous_top;
627 }
628
629 if (has_processed_weak_pointers) break; // We are done.
630 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000631 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000632 has_processed_weak_pointers = true;
633 }
634
635 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000636 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000637
638 LOG(ResourceEvent("scavenge", "end"));
639
640 gc_state_ = NOT_IN_GC;
641}
642
643
644void Heap::ClearRSetRange(Address start, int size_in_bytes) {
645 uint32_t start_bit;
646 Address start_word_address =
647 Page::ComputeRSetBitPosition(start, 0, &start_bit);
648 uint32_t end_bit;
649 Address end_word_address =
650 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
651 0,
652 &end_bit);
653
654 // We want to clear the bits in the starting word starting with the
655 // first bit, and in the ending word up to and including the last
656 // bit. Build a pair of bitmasks to do that.
657 uint32_t start_bitmask = start_bit - 1;
658 uint32_t end_bitmask = ~((end_bit << 1) - 1);
659
660 // If the start address and end address are the same, we mask that
661 // word once, otherwise mask the starting and ending word
662 // separately and all the ones in between.
663 if (start_word_address == end_word_address) {
664 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
665 } else {
666 Memory::uint32_at(start_word_address) &= start_bitmask;
667 Memory::uint32_at(end_word_address) &= end_bitmask;
668 start_word_address += kIntSize;
669 memset(start_word_address, 0, end_word_address - start_word_address);
670 }
671}
672
673
674class UpdateRSetVisitor: public ObjectVisitor {
675 public:
676
677 void VisitPointer(Object** p) {
678 UpdateRSet(p);
679 }
680
681 void VisitPointers(Object** start, Object** end) {
682 // Update a store into slots [start, end), used (a) to update remembered
683 // set when promoting a young object to old space or (b) to rebuild
684 // remembered sets after a mark-compact collection.
685 for (Object** p = start; p < end; p++) UpdateRSet(p);
686 }
687 private:
688
689 void UpdateRSet(Object** p) {
690 // The remembered set should not be set. It should be clear for objects
691 // newly copied to old space, and it is cleared before rebuilding in the
692 // mark-compact collector.
693 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
694 if (Heap::InNewSpace(*p)) {
695 Page::SetRSet(reinterpret_cast<Address>(p), 0);
696 }
697 }
698};
699
700
701int Heap::UpdateRSet(HeapObject* obj) {
702 ASSERT(!InNewSpace(obj));
703 // Special handling of fixed arrays to iterate the body based on the start
704 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
705 // will not work because Page::SetRSet needs to have the start of the
706 // object.
707 if (obj->IsFixedArray()) {
708 FixedArray* array = FixedArray::cast(obj);
709 int length = array->length();
710 for (int i = 0; i < length; i++) {
711 int offset = FixedArray::kHeaderSize + i * kPointerSize;
712 ASSERT(!Page::IsRSetSet(obj->address(), offset));
713 if (Heap::InNewSpace(array->get(i))) {
714 Page::SetRSet(obj->address(), offset);
715 }
716 }
717 } else if (!obj->IsCode()) {
718 // Skip code object, we know it does not contain inter-generational
719 // pointers.
720 UpdateRSetVisitor v;
721 obj->Iterate(&v);
722 }
723 return obj->Size();
724}
725
726
727void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000728 // By definition, we do not care about remembered set bits in code or data
729 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000730 map_space_->ClearRSet();
731 RebuildRSets(map_space_);
732
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000733 old_pointer_space_->ClearRSet();
734 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000735
736 Heap::lo_space_->ClearRSet();
737 RebuildRSets(lo_space_);
738}
739
740
741void Heap::RebuildRSets(PagedSpace* space) {
742 HeapObjectIterator it(space);
743 while (it.has_next()) Heap::UpdateRSet(it.next());
744}
745
746
747void Heap::RebuildRSets(LargeObjectSpace* space) {
748 LargeObjectIterator it(space);
749 while (it.has_next()) Heap::UpdateRSet(it.next());
750}
751
752
753#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
754void Heap::RecordCopiedObject(HeapObject* obj) {
755 bool should_record = false;
756#ifdef DEBUG
757 should_record = FLAG_heap_stats;
758#endif
759#ifdef ENABLE_LOGGING_AND_PROFILING
760 should_record = should_record || FLAG_log_gc;
761#endif
762 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000763 if (new_space_.Contains(obj)) {
764 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000765 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000766 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000767 }
768 }
769}
770#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
771
772
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000773
774HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775 HeapObject* target,
776 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000777 // Copy the content of source to target.
778 CopyBlock(reinterpret_cast<Object**>(target->address()),
779 reinterpret_cast<Object**>(source->address()),
780 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000781
kasper.lund7276f142008-07-30 08:49:36 +0000782 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000783 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000784
785 // Update NewSpace stats if necessary.
786#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
787 RecordCopiedObject(target);
788#endif
789
790 return target;
791}
792
793
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000794// Inlined function.
795void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
796 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797
kasper.lund7276f142008-07-30 08:49:36 +0000798 // We use the first word (where the map pointer usually is) of a heap
799 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000800 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000802 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000803
kasper.lund7276f142008-07-30 08:49:36 +0000804 // If the first word is a forwarding address, the object has already been
805 // copied.
806 if (first_word.IsForwardingAddress()) {
807 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808 return;
809 }
810
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000811 // Call the slow part of scavenge object.
812 return ScavengeObjectSlow(p, object);
813}
814
ager@chromium.org870a0b62008-11-04 11:43:05 +0000815
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000816static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000817 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000818 // is a candidate for being shortcut by the scavenger.
819 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000820 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
ager@chromium.orgc3e50d82008-11-05 11:53:10 +0000821 return (StringShape(map).representation_tag() == kConsStringTag) &&
ager@chromium.org870a0b62008-11-04 11:43:05 +0000822 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000823}
824
825
826void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
827 ASSERT(InFromSpace(object));
828 MapWord first_word = object->map_word();
829 ASSERT(!first_word.IsForwardingAddress());
830
831 // Optimization: Bypass flattened ConsString objects.
832 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000833 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834 *p = object;
835 // After patching *p we have to repeat the checks that object is in the
836 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000837 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000838 first_word = object->map_word();
839 if (first_word.IsForwardingAddress()) {
840 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000841 return;
842 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000843 }
844
kasper.lund7276f142008-07-30 08:49:36 +0000845 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000846 // If the object should be promoted, we try to copy it to old space.
847 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000848 OldSpace* target_space = Heap::TargetSpace(object);
849 ASSERT(target_space == Heap::old_pointer_space_ ||
850 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000851 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000852 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000853 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000854 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000855 // Record the object's address at the top of the to space, to allow
856 // it to be swept by the scavenger.
857 promoted_top -= kPointerSize;
858 Memory::Object_at(promoted_top) = *p;
859 } else {
860#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000861 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000862 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000863 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000864 (*p)->Iterate(&v);
865#endif
866 }
867 return;
868 }
869 }
870
871 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000872 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873 // Failed allocation at this point is utterly unexpected.
874 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000875 *p = MigrateObject(object, HeapObject::cast(result), object_size);
876}
877
878
879void Heap::ScavengePointer(HeapObject** p) {
880 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000881}
882
883
884Object* Heap::AllocatePartialMap(InstanceType instance_type,
885 int instance_size) {
886 Object* result = AllocateRawMap(Map::kSize);
887 if (result->IsFailure()) return result;
888
889 // Map::cast cannot be used due to uninitialized map field.
890 reinterpret_cast<Map*>(result)->set_map(meta_map());
891 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
892 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000893 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000894 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
895 return result;
896}
897
898
899Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
900 Object* result = AllocateRawMap(Map::kSize);
901 if (result->IsFailure()) return result;
902
903 Map* map = reinterpret_cast<Map*>(result);
904 map->set_map(meta_map());
905 map->set_instance_type(instance_type);
906 map->set_prototype(null_value());
907 map->set_constructor(null_value());
908 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000909 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000910 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000911 map->set_code_cache(empty_fixed_array());
912 map->set_unused_property_fields(0);
913 map->set_bit_field(0);
914 return map;
915}
916
917
918bool Heap::CreateInitialMaps() {
919 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
920 if (obj->IsFailure()) return false;
921
922 // Map::cast cannot be used due to uninitialized map field.
923 meta_map_ = reinterpret_cast<Map*>(obj);
924 meta_map()->set_map(meta_map());
925
926 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
927 if (obj->IsFailure()) return false;
928 fixed_array_map_ = Map::cast(obj);
929
930 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
931 if (obj->IsFailure()) return false;
932 oddball_map_ = Map::cast(obj);
933
934 // Allocate the empty array
935 obj = AllocateEmptyFixedArray();
936 if (obj->IsFailure()) return false;
937 empty_fixed_array_ = FixedArray::cast(obj);
938
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000939 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000940 if (obj->IsFailure()) return false;
941 null_value_ = obj;
942
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000943 // Allocate the empty descriptor array. AllocateMap can now be used.
944 obj = AllocateEmptyFixedArray();
945 if (obj->IsFailure()) return false;
946 // There is a check against empty_descriptor_array() in cast().
947 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000948
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000949 // Fix the instance_descriptors for the existing maps.
950 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000951 meta_map()->set_code_cache(empty_fixed_array());
952
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000953 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954 fixed_array_map()->set_code_cache(empty_fixed_array());
955
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000956 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000957 oddball_map()->set_code_cache(empty_fixed_array());
958
959 // Fix prototype object for existing maps.
960 meta_map()->set_prototype(null_value());
961 meta_map()->set_constructor(null_value());
962
963 fixed_array_map()->set_prototype(null_value());
964 fixed_array_map()->set_constructor(null_value());
965 oddball_map()->set_prototype(null_value());
966 oddball_map()->set_constructor(null_value());
967
968 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
969 if (obj->IsFailure()) return false;
970 heap_number_map_ = Map::cast(obj);
971
972 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
973 if (obj->IsFailure()) return false;
974 proxy_map_ = Map::cast(obj);
975
976#define ALLOCATE_STRING_MAP(type, size, name) \
977 obj = AllocateMap(type, size); \
978 if (obj->IsFailure()) return false; \
979 name##_map_ = Map::cast(obj);
980 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
981#undef ALLOCATE_STRING_MAP
982
ager@chromium.org7c537e22008-10-16 08:43:32 +0000983 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000984 if (obj->IsFailure()) return false;
985 undetectable_short_string_map_ = Map::cast(obj);
986 undetectable_short_string_map_->set_is_undetectable();
987
ager@chromium.org7c537e22008-10-16 08:43:32 +0000988 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000989 if (obj->IsFailure()) return false;
990 undetectable_medium_string_map_ = Map::cast(obj);
991 undetectable_medium_string_map_->set_is_undetectable();
992
ager@chromium.org7c537e22008-10-16 08:43:32 +0000993 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000994 if (obj->IsFailure()) return false;
995 undetectable_long_string_map_ = Map::cast(obj);
996 undetectable_long_string_map_->set_is_undetectable();
997
ager@chromium.org7c537e22008-10-16 08:43:32 +0000998 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000999 if (obj->IsFailure()) return false;
1000 undetectable_short_ascii_string_map_ = Map::cast(obj);
1001 undetectable_short_ascii_string_map_->set_is_undetectable();
1002
ager@chromium.org7c537e22008-10-16 08:43:32 +00001003 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001004 if (obj->IsFailure()) return false;
1005 undetectable_medium_ascii_string_map_ = Map::cast(obj);
1006 undetectable_medium_ascii_string_map_->set_is_undetectable();
1007
ager@chromium.org7c537e22008-10-16 08:43:32 +00001008 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001009 if (obj->IsFailure()) return false;
1010 undetectable_long_ascii_string_map_ = Map::cast(obj);
1011 undetectable_long_ascii_string_map_->set_is_undetectable();
1012
1013 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
1014 if (obj->IsFailure()) return false;
1015 byte_array_map_ = Map::cast(obj);
1016
1017 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1018 if (obj->IsFailure()) return false;
1019 code_map_ = Map::cast(obj);
1020
1021 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1022 if (obj->IsFailure()) return false;
1023 one_word_filler_map_ = Map::cast(obj);
1024
1025 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1026 if (obj->IsFailure()) return false;
1027 two_word_filler_map_ = Map::cast(obj);
1028
1029#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1030 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1031 if (obj->IsFailure()) return false; \
1032 name##_map_ = Map::cast(obj);
1033 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1034#undef ALLOCATE_STRUCT_MAP
1035
ager@chromium.org236ad962008-09-25 09:45:57 +00001036 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001037 if (obj->IsFailure()) return false;
1038 hash_table_map_ = Map::cast(obj);
1039
ager@chromium.org236ad962008-09-25 09:45:57 +00001040 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001041 if (obj->IsFailure()) return false;
1042 context_map_ = Map::cast(obj);
1043
ager@chromium.org236ad962008-09-25 09:45:57 +00001044 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001045 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001046 catch_context_map_ = Map::cast(obj);
1047
1048 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1049 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001050 global_context_map_ = Map::cast(obj);
1051
1052 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1053 if (obj->IsFailure()) return false;
1054 boilerplate_function_map_ = Map::cast(obj);
1055
1056 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1057 if (obj->IsFailure()) return false;
1058 shared_function_info_map_ = Map::cast(obj);
1059
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001060 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061 return true;
1062}
1063
1064
1065Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1066 // Statically ensure that it is safe to allocate heap numbers in paged
1067 // spaces.
1068 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001069 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001070 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001071 if (result->IsFailure()) return result;
1072
1073 HeapObject::cast(result)->set_map(heap_number_map());
1074 HeapNumber::cast(result)->set_value(value);
1075 return result;
1076}
1077
1078
1079Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001080 // Use general version, if we're forced to always allocate.
1081 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001082 // This version of AllocateHeapNumber is optimized for
1083 // allocation in new space.
1084 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1085 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001086 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001087 if (result->IsFailure()) return result;
1088 HeapObject::cast(result)->set_map(heap_number_map());
1089 HeapNumber::cast(result)->set_value(value);
1090 return result;
1091}
1092
1093
1094Object* Heap::CreateOddball(Map* map,
1095 const char* to_string,
1096 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001097 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001098 if (result->IsFailure()) return result;
1099 return Oddball::cast(result)->Initialize(to_string, to_number);
1100}
1101
1102
1103bool Heap::CreateApiObjects() {
1104 Object* obj;
1105
1106 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1107 if (obj->IsFailure()) return false;
1108 neander_map_ = Map::cast(obj);
1109
1110 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1111 if (obj->IsFailure()) return false;
1112 Object* elements = AllocateFixedArray(2);
1113 if (elements->IsFailure()) return false;
1114 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1115 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1116 message_listeners_ = JSObject::cast(obj);
1117
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001118 return true;
1119}
1120
1121void Heap::CreateFixedStubs() {
1122 // Here we create roots for fixed stubs. They are needed at GC
1123 // for cooking and uncooking (check out frames.cc).
1124 // The eliminates the need for doing dictionary lookup in the
1125 // stub cache for these stubs.
1126 HandleScope scope;
1127 {
1128 CEntryStub stub;
1129 c_entry_code_ = *stub.GetCode();
1130 }
1131 {
1132 CEntryDebugBreakStub stub;
1133 c_entry_debug_break_code_ = *stub.GetCode();
1134 }
1135 {
1136 JSEntryStub stub;
1137 js_entry_code_ = *stub.GetCode();
1138 }
1139 {
1140 JSConstructEntryStub stub;
1141 js_construct_entry_code_ = *stub.GetCode();
1142 }
1143}
1144
1145
1146bool Heap::CreateInitialObjects() {
1147 Object* obj;
1148
1149 // The -0 value must be set before NumberFromDouble works.
1150 obj = AllocateHeapNumber(-0.0, TENURED);
1151 if (obj->IsFailure()) return false;
1152 minus_zero_value_ = obj;
1153 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1154
1155 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1156 if (obj->IsFailure()) return false;
1157 nan_value_ = obj;
1158
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001159 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160 if (obj->IsFailure()) return false;
1161 undefined_value_ = obj;
1162 ASSERT(!InNewSpace(undefined_value()));
1163
1164 // Allocate initial symbol table.
1165 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1166 if (obj->IsFailure()) return false;
1167 symbol_table_ = obj;
1168
1169 // Assign the print strings for oddballs after creating symboltable.
1170 Object* symbol = LookupAsciiSymbol("undefined");
1171 if (symbol->IsFailure()) return false;
1172 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1173 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1174
1175 // Assign the print strings for oddballs after creating symboltable.
1176 symbol = LookupAsciiSymbol("null");
1177 if (symbol->IsFailure()) return false;
1178 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1179 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1180
1181 // Allocate the null_value
1182 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1183 if (obj->IsFailure()) return false;
1184
1185 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1186 if (obj->IsFailure()) return false;
1187 true_value_ = obj;
1188
1189 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1190 if (obj->IsFailure()) return false;
1191 false_value_ = obj;
1192
1193 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1194 if (obj->IsFailure()) return false;
1195 the_hole_value_ = obj;
1196
1197 // Allocate the empty string.
1198 obj = AllocateRawAsciiString(0, TENURED);
1199 if (obj->IsFailure()) return false;
1200 empty_string_ = String::cast(obj);
1201
1202#define SYMBOL_INITIALIZE(name, string) \
1203 obj = LookupAsciiSymbol(string); \
1204 if (obj->IsFailure()) return false; \
1205 (name##_) = String::cast(obj);
1206 SYMBOL_LIST(SYMBOL_INITIALIZE)
1207#undef SYMBOL_INITIALIZE
1208
1209 // Allocate the proxy for __proto__.
1210 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1211 if (obj->IsFailure()) return false;
1212 prototype_accessors_ = Proxy::cast(obj);
1213
1214 // Allocate the code_stubs dictionary.
1215 obj = Dictionary::Allocate(4);
1216 if (obj->IsFailure()) return false;
1217 code_stubs_ = Dictionary::cast(obj);
1218
1219 // Allocate the non_monomorphic_cache used in stub-cache.cc
1220 obj = Dictionary::Allocate(4);
1221 if (obj->IsFailure()) return false;
1222 non_monomorphic_cache_ = Dictionary::cast(obj);
1223
1224 CreateFixedStubs();
1225
1226 // Allocate the number->string conversion cache
1227 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1228 if (obj->IsFailure()) return false;
1229 number_string_cache_ = FixedArray::cast(obj);
1230
1231 // Allocate cache for single character strings.
1232 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1233 if (obj->IsFailure()) return false;
1234 single_character_string_cache_ = FixedArray::cast(obj);
1235
1236 // Allocate cache for external strings pointing to native source code.
1237 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1238 if (obj->IsFailure()) return false;
1239 natives_source_cache_ = FixedArray::cast(obj);
1240
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001241 // Handling of script id generation is in Factory::NewScript.
1242 last_script_id_ = undefined_value();
1243
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001244 // Initialize keyed lookup cache.
1245 ClearKeyedLookupCache();
1246
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001247 // Initialize compilation cache.
1248 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001249
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001250 return true;
1251}
1252
1253
1254static inline int double_get_hash(double d) {
1255 DoubleRepresentation rep(d);
1256 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1257 (Heap::kNumberStringCacheSize - 1));
1258}
1259
1260
1261static inline int smi_get_hash(Smi* smi) {
1262 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1263}
1264
1265
1266
1267Object* Heap::GetNumberStringCache(Object* number) {
1268 int hash;
1269 if (number->IsSmi()) {
1270 hash = smi_get_hash(Smi::cast(number));
1271 } else {
1272 hash = double_get_hash(number->Number());
1273 }
1274 Object* key = number_string_cache_->get(hash * 2);
1275 if (key == number) {
1276 return String::cast(number_string_cache_->get(hash * 2 + 1));
1277 } else if (key->IsHeapNumber() &&
1278 number->IsHeapNumber() &&
1279 key->Number() == number->Number()) {
1280 return String::cast(number_string_cache_->get(hash * 2 + 1));
1281 }
1282 return undefined_value();
1283}
1284
1285
1286void Heap::SetNumberStringCache(Object* number, String* string) {
1287 int hash;
1288 if (number->IsSmi()) {
1289 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001290 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001291 } else {
1292 hash = double_get_hash(number->Number());
1293 number_string_cache_->set(hash * 2, number);
1294 }
1295 number_string_cache_->set(hash * 2 + 1, string);
1296}
1297
1298
1299Object* Heap::SmiOrNumberFromDouble(double value,
1300 bool new_object,
1301 PretenureFlag pretenure) {
1302 // We need to distinguish the minus zero value and this cannot be
1303 // done after conversion to int. Doing this by comparing bit
1304 // patterns is faster than using fpclassify() et al.
1305 static const DoubleRepresentation plus_zero(0.0);
1306 static const DoubleRepresentation minus_zero(-0.0);
1307 static const DoubleRepresentation nan(OS::nan_value());
1308 ASSERT(minus_zero_value_ != NULL);
1309 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1310
1311 DoubleRepresentation rep(value);
1312 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1313 if (rep.bits == minus_zero.bits) {
1314 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1315 : minus_zero_value_;
1316 }
1317 if (rep.bits == nan.bits) {
1318 return new_object
1319 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1320 : nan_value_;
1321 }
1322
1323 // Try to represent the value as a tagged small integer.
1324 int int_value = FastD2I(value);
1325 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1326 return Smi::FromInt(int_value);
1327 }
1328
1329 // Materialize the value in the heap.
1330 return AllocateHeapNumber(value, pretenure);
1331}
1332
1333
1334Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1335 return SmiOrNumberFromDouble(value,
1336 true /* number object must be new */,
1337 pretenure);
1338}
1339
1340
1341Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1342 return SmiOrNumberFromDouble(value,
1343 false /* use preallocated NaN, -0.0 */,
1344 pretenure);
1345}
1346
1347
1348Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1349 // Statically ensure that it is safe to allocate proxies in paged spaces.
1350 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001351 AllocationSpace space =
1352 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001353 Object* result = Allocate(proxy_map(), space);
1354 if (result->IsFailure()) return result;
1355
1356 Proxy::cast(result)->set_proxy(proxy);
1357 return result;
1358}
1359
1360
1361Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1362 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1363 if (result->IsFailure()) return result;
1364
1365 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1366 share->set_name(name);
1367 Code* illegal = Builtins::builtin(Builtins::Illegal);
1368 share->set_code(illegal);
1369 share->set_expected_nof_properties(0);
1370 share->set_length(0);
1371 share->set_formal_parameter_count(0);
1372 share->set_instance_class_name(Object_symbol());
1373 share->set_function_data(undefined_value());
1374 share->set_lazy_load_data(undefined_value());
1375 share->set_script(undefined_value());
1376 share->set_start_position_and_type(0);
1377 share->set_debug_info(undefined_value());
1378 return result;
1379}
1380
1381
ager@chromium.org870a0b62008-11-04 11:43:05 +00001382Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001383 String* second) {
1384 StringShape first_shape(first);
1385 StringShape second_shape(second);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001386 int first_length = first->length(first_shape);
1387 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001388 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001389 bool is_ascii = first_shape.IsAsciiRepresentation()
1390 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001391
1392 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001393 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001394 ASSERT(first->IsFlat(first_shape));
1395 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001396 if (is_ascii) {
1397 Object* result = AllocateRawAsciiString(length);
1398 if (result->IsFailure()) return result;
1399 // Copy the characters into the new object.
1400 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001401 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1402 String::WriteToFlat(second,
1403 second_shape,
1404 dest + first_length,
1405 0,
1406 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001407 return result;
1408 } else {
1409 Object* result = AllocateRawTwoByteString(length);
1410 if (result->IsFailure()) return result;
1411 // Copy the characters into the new object.
1412 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001413 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1414 String::WriteToFlat(second,
1415 second_shape,
1416 dest + first_length,
1417 0,
1418 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001419 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 }
1422
1423 Map* map;
1424 if (length <= String::kMaxShortStringSize) {
1425 map = is_ascii ? short_cons_ascii_string_map()
1426 : short_cons_string_map();
1427 } else if (length <= String::kMaxMediumStringSize) {
1428 map = is_ascii ? medium_cons_ascii_string_map()
1429 : medium_cons_string_map();
1430 } else {
1431 map = is_ascii ? long_cons_ascii_string_map()
1432 : long_cons_string_map();
1433 }
1434
1435 Object* result = Allocate(map, NEW_SPACE);
1436 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001437 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001439 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1440 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001442 return result;
1443}
1444
1445
ager@chromium.org870a0b62008-11-04 11:43:05 +00001446Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001447 int start,
1448 int end) {
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001449 StringShape buffer_shape(buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001450 int length = end - start;
1451
1452 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001453 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001454 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001455 }
1456
1457 Map* map;
1458 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001459 map = buffer_shape.IsAsciiRepresentation() ?
1460 short_sliced_ascii_string_map() :
1461 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001462 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001463 map = buffer_shape.IsAsciiRepresentation() ?
1464 medium_sliced_ascii_string_map() :
1465 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001466 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001467 map = buffer_shape.IsAsciiRepresentation() ?
1468 long_sliced_ascii_string_map() :
1469 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001470 }
1471
1472 Object* result = Allocate(map, NEW_SPACE);
1473 if (result->IsFailure()) return result;
1474
1475 SlicedString* sliced_string = SlicedString::cast(result);
1476 sliced_string->set_buffer(buffer);
1477 sliced_string->set_start(start);
1478 sliced_string->set_length(length);
1479
1480 return result;
1481}
1482
1483
ager@chromium.org870a0b62008-11-04 11:43:05 +00001484Object* Heap::AllocateSubString(String* buffer,
1485 StringShape buffer_shape,
1486 int start,
1487 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001488 int length = end - start;
1489
ager@chromium.org7c537e22008-10-16 08:43:32 +00001490 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001491 return Heap::LookupSingleCharacterStringFromCode(
1492 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001493 }
1494
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001495 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001496 if (!buffer->IsFlat(buffer_shape)) {
1497 buffer->TryFlatten(buffer_shape);
1498 buffer_shape = StringShape(buffer);
1499 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001500
ager@chromium.org870a0b62008-11-04 11:43:05 +00001501 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001502 ? AllocateRawAsciiString(length)
1503 : AllocateRawTwoByteString(length);
1504 if (result->IsFailure()) return result;
1505
1506 // Copy the characters into the new object.
1507 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001508 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001509 StringHasher hasher(length);
1510 int i = 0;
1511 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001512 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001513 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001514 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001515 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001516 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001517 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001518 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001519 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001520 }
1521 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522 return result;
1523}
1524
1525
1526Object* Heap::AllocateExternalStringFromAscii(
1527 ExternalAsciiString::Resource* resource) {
1528 Map* map;
1529 int length = resource->length();
1530 if (length <= String::kMaxShortStringSize) {
1531 map = short_external_ascii_string_map();
1532 } else if (length <= String::kMaxMediumStringSize) {
1533 map = medium_external_ascii_string_map();
1534 } else {
1535 map = long_external_ascii_string_map();
1536 }
1537
1538 Object* result = Allocate(map, NEW_SPACE);
1539 if (result->IsFailure()) return result;
1540
1541 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1542 external_string->set_length(length);
1543 external_string->set_resource(resource);
1544
1545 return result;
1546}
1547
1548
1549Object* Heap::AllocateExternalStringFromTwoByte(
1550 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001551 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001552
ager@chromium.org6f10e412009-02-13 10:11:16 +00001553 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554 Object* result = Allocate(map, NEW_SPACE);
1555 if (result->IsFailure()) return result;
1556
1557 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1558 external_string->set_length(length);
1559 external_string->set_resource(resource);
1560
1561 return result;
1562}
1563
1564
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001565Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566 if (code <= String::kMaxAsciiCharCode) {
1567 Object* value = Heap::single_character_string_cache()->get(code);
1568 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001569
1570 char buffer[1];
1571 buffer[0] = static_cast<char>(code);
1572 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575 Heap::single_character_string_cache()->set(code, result);
1576 return result;
1577 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001578
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579 Object* result = Heap::AllocateRawTwoByteString(1);
1580 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001581 String* answer = String::cast(result);
1582 answer->Set(StringShape(answer), 0, code);
1583 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584}
1585
1586
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001587Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1588 if (pretenure == NOT_TENURED) {
1589 return AllocateByteArray(length);
1590 }
1591 int size = ByteArray::SizeFor(length);
1592 AllocationSpace space =
1593 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1594
1595 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1596
1597 if (result->IsFailure()) return result;
1598
1599 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1600 reinterpret_cast<Array*>(result)->set_length(length);
1601 return result;
1602}
1603
1604
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605Object* Heap::AllocateByteArray(int length) {
1606 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001607 AllocationSpace space =
1608 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001610 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001611
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612 if (result->IsFailure()) return result;
1613
1614 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1615 reinterpret_cast<Array*>(result)->set_length(length);
1616 return result;
1617}
1618
1619
ager@chromium.org6f10e412009-02-13 10:11:16 +00001620void Heap::CreateFillerObjectAt(Address addr, int size) {
1621 if (size == 0) return;
1622 HeapObject* filler = HeapObject::FromAddress(addr);
1623 if (size == kPointerSize) {
1624 filler->set_map(Heap::one_word_filler_map());
1625 } else {
1626 filler->set_map(Heap::byte_array_map());
1627 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1628 }
1629}
1630
1631
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001632Object* Heap::CreateCode(const CodeDesc& desc,
1633 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001634 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001635 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001636 // Compute size
1637 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1638 int sinfo_size = 0;
1639 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1640 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001641 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001642 Object* result;
1643 if (obj_size > MaxHeapObjectSize()) {
1644 result = lo_space_->AllocateRawCode(obj_size);
1645 } else {
1646 result = code_space_->AllocateRaw(obj_size);
1647 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001648
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001649 if (result->IsFailure()) return result;
1650
1651 // Initialize the object
1652 HeapObject::cast(result)->set_map(code_map());
1653 Code* code = Code::cast(result);
1654 code->set_instruction_size(desc.instr_size);
1655 code->set_relocation_size(desc.reloc_size);
1656 code->set_sinfo_size(sinfo_size);
1657 code->set_flags(flags);
1658 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001659 // Allow self references to created code object by patching the handle to
1660 // point to the newly allocated Code object.
1661 if (!self_reference.is_null()) {
1662 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001663 }
1664 // Migrate generated code.
1665 // The generated code can contain Object** values (typically from handles)
1666 // that are dereferenced during the copy to point directly to the actual heap
1667 // objects. These pointers can include references to the code object itself,
1668 // through the self_reference parameter.
1669 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001670 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001671 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001672
1673#ifdef DEBUG
1674 code->Verify();
1675#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001676 return code;
1677}
1678
1679
1680Object* Heap::CopyCode(Code* code) {
1681 // Allocate an object the same size as the code object.
1682 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001683 Object* result;
1684 if (obj_size > MaxHeapObjectSize()) {
1685 result = lo_space_->AllocateRawCode(obj_size);
1686 } else {
1687 result = code_space_->AllocateRaw(obj_size);
1688 }
1689
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001690 if (result->IsFailure()) return result;
1691
1692 // Copy code object.
1693 Address old_addr = code->address();
1694 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001695 CopyBlock(reinterpret_cast<Object**>(new_addr),
1696 reinterpret_cast<Object**>(old_addr),
1697 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001698 // Relocate the copy.
1699 Code* new_code = Code::cast(result);
1700 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001701 return new_code;
1702}
1703
1704
1705Object* Heap::Allocate(Map* map, AllocationSpace space) {
1706 ASSERT(gc_state_ == NOT_IN_GC);
1707 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001708 Object* result = AllocateRaw(map->instance_size(),
1709 space,
1710 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001711 if (result->IsFailure()) return result;
1712 HeapObject::cast(result)->set_map(map);
1713 return result;
1714}
1715
1716
1717Object* Heap::InitializeFunction(JSFunction* function,
1718 SharedFunctionInfo* shared,
1719 Object* prototype) {
1720 ASSERT(!prototype->IsMap());
1721 function->initialize_properties();
1722 function->initialize_elements();
1723 function->set_shared(shared);
1724 function->set_prototype_or_initial_map(prototype);
1725 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001726 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001727 return function;
1728}
1729
1730
1731Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001732 // Allocate the prototype. Make sure to use the object function
1733 // from the function's context, since the function can be from a
1734 // different context.
1735 JSFunction* object_function =
1736 function->context()->global_context()->object_function();
1737 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001738 if (prototype->IsFailure()) return prototype;
1739 // When creating the prototype for the function we must set its
1740 // constructor to the function.
1741 Object* result =
1742 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1743 function,
1744 DONT_ENUM);
1745 if (result->IsFailure()) return result;
1746 return prototype;
1747}
1748
1749
1750Object* Heap::AllocateFunction(Map* function_map,
1751 SharedFunctionInfo* shared,
1752 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001753 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754 if (result->IsFailure()) return result;
1755 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1756}
1757
1758
1759Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001760 // To get fast allocation and map sharing for arguments objects we
1761 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001762
1763 // This calls Copy directly rather than using Heap::AllocateRaw so we
1764 // duplicate the check here.
1765 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1766
1767 JSObject* boilerplate =
1768 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001769
1770 // Make the clone.
1771 Map* map = boilerplate->map();
1772 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001773 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001774 if (result->IsFailure()) return result;
1775
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001776 // Copy the content. The arguments boilerplate doesn't have any
1777 // fields that point to new space so it's safe to skip the write
1778 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001779 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1780 reinterpret_cast<Object**>(boilerplate->address()),
1781 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001783 // Set the two properties.
1784 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001785 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001786 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1787 Smi::FromInt(length),
1788 SKIP_WRITE_BARRIER);
1789
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001790 // Check the state of the object
1791 ASSERT(JSObject::cast(result)->HasFastProperties());
1792 ASSERT(JSObject::cast(result)->HasFastElements());
1793
1794 return result;
1795}
1796
1797
1798Object* Heap::AllocateInitialMap(JSFunction* fun) {
1799 ASSERT(!fun->has_initial_map());
1800
ager@chromium.org7c537e22008-10-16 08:43:32 +00001801 // First create a new map with the expected number of properties being
1802 // allocated in-object.
1803 int expected_nof_properties = fun->shared()->expected_nof_properties();
1804 int instance_size = JSObject::kHeaderSize +
1805 expected_nof_properties * kPointerSize;
1806 if (instance_size > JSObject::kMaxInstanceSize) {
1807 instance_size = JSObject::kMaxInstanceSize;
1808 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1809 kPointerSize;
1810 }
1811 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001812 if (map_obj->IsFailure()) return map_obj;
1813
1814 // Fetch or allocate prototype.
1815 Object* prototype;
1816 if (fun->has_instance_prototype()) {
1817 prototype = fun->instance_prototype();
1818 } else {
1819 prototype = AllocateFunctionPrototype(fun);
1820 if (prototype->IsFailure()) return prototype;
1821 }
1822 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001823 map->set_inobject_properties(expected_nof_properties);
1824 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001825 map->set_prototype(prototype);
1826 return map;
1827}
1828
1829
1830void Heap::InitializeJSObjectFromMap(JSObject* obj,
1831 FixedArray* properties,
1832 Map* map) {
1833 obj->set_properties(properties);
1834 obj->initialize_elements();
1835 // TODO(1240798): Initialize the object's body using valid initial values
1836 // according to the object's initial map. For example, if the map's
1837 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1838 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1839 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1840 // verification code has to cope with (temporarily) invalid objects. See
1841 // for example, JSArray::JSArrayVerify).
1842 obj->InitializeBody(map->instance_size());
1843}
1844
1845
1846Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1847 // JSFunctions should be allocated using AllocateFunction to be
1848 // properly initialized.
1849 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1850
1851 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001852 int prop_size = map->unused_property_fields() - map->inobject_properties();
1853 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854 if (properties->IsFailure()) return properties;
1855
1856 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001857 AllocationSpace space =
1858 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1860 Object* obj = Allocate(map, space);
1861 if (obj->IsFailure()) return obj;
1862
1863 // Initialize the JSObject.
1864 InitializeJSObjectFromMap(JSObject::cast(obj),
1865 FixedArray::cast(properties),
1866 map);
1867 return obj;
1868}
1869
1870
1871Object* Heap::AllocateJSObject(JSFunction* constructor,
1872 PretenureFlag pretenure) {
1873 // Allocate the initial map if absent.
1874 if (!constructor->has_initial_map()) {
1875 Object* initial_map = AllocateInitialMap(constructor);
1876 if (initial_map->IsFailure()) return initial_map;
1877 constructor->set_initial_map(Map::cast(initial_map));
1878 Map::cast(initial_map)->set_constructor(constructor);
1879 }
1880 // Allocate the object based on the constructors initial map.
1881 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1882}
1883
1884
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001885Object* Heap::CopyJSObject(JSObject* source) {
1886 // Never used to copy functions. If functions need to be copied we
1887 // have to be careful to clear the literals array.
1888 ASSERT(!source->IsJSFunction());
1889
1890 // Make the clone.
1891 Map* map = source->map();
1892 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001893 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001894
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001895 // If we're forced to always allocate, we use the general allocation
1896 // functions which may leave us with an object in old space.
1897 if (always_allocate()) {
1898 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1899 if (clone->IsFailure()) return clone;
1900 Address clone_address = HeapObject::cast(clone)->address();
1901 CopyBlock(reinterpret_cast<Object**>(clone_address),
1902 reinterpret_cast<Object**>(source->address()),
1903 object_size);
1904 // Update write barrier for all fields that lie beyond the header.
1905 for (int offset = JSObject::kHeaderSize;
1906 offset < object_size;
1907 offset += kPointerSize) {
1908 RecordWrite(clone_address, offset);
1909 }
1910 } else {
1911 clone = new_space_.AllocateRaw(object_size);
1912 if (clone->IsFailure()) return clone;
1913 ASSERT(Heap::InNewSpace(clone));
1914 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00001915 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001916 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1917 reinterpret_cast<Object**>(source->address()),
1918 object_size);
1919 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001920
1921 FixedArray* elements = FixedArray::cast(source->elements());
1922 FixedArray* properties = FixedArray::cast(source->properties());
1923 // Update elements if necessary.
1924 if (elements->length()> 0) {
1925 Object* elem = CopyFixedArray(elements);
1926 if (elem->IsFailure()) return elem;
1927 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1928 }
1929 // Update properties if necessary.
1930 if (properties->length() > 0) {
1931 Object* prop = CopyFixedArray(properties);
1932 if (prop->IsFailure()) return prop;
1933 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1934 }
1935 // Return the new clone.
1936 return clone;
1937}
1938
1939
1940Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1941 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001942 // Allocate initial map if absent.
1943 if (!constructor->has_initial_map()) {
1944 Object* initial_map = AllocateInitialMap(constructor);
1945 if (initial_map->IsFailure()) return initial_map;
1946 constructor->set_initial_map(Map::cast(initial_map));
1947 Map::cast(initial_map)->set_constructor(constructor);
1948 }
1949
1950 Map* map = constructor->initial_map();
1951
1952 // Check that the already allocated object has the same size as
1953 // objects allocated using the constructor.
1954 ASSERT(map->instance_size() == object->map()->instance_size());
1955
1956 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001957 int prop_size = map->unused_property_fields() - map->inobject_properties();
1958 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001959 if (properties->IsFailure()) return properties;
1960
1961 // Reset the map for the object.
1962 object->set_map(constructor->initial_map());
1963
1964 // Reinitialize the object from the constructor map.
1965 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1966 return object;
1967}
1968
1969
1970Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1971 PretenureFlag pretenure) {
1972 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1973 if (result->IsFailure()) return result;
1974
1975 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001976 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001977 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001978 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001979 }
1980 return result;
1981}
1982
1983
1984Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1985 PretenureFlag pretenure) {
1986 // Count the number of characters in the UTF-8 string and check if
1987 // it is an ASCII string.
1988 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1989 decoder->Reset(string.start(), string.length());
1990 int chars = 0;
1991 bool is_ascii = true;
1992 while (decoder->has_more()) {
1993 uc32 r = decoder->GetNext();
1994 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1995 chars++;
1996 }
1997
1998 // If the string is ascii, we do not need to convert the characters
1999 // since UTF8 is backwards compatible with ascii.
2000 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2001
2002 Object* result = AllocateRawTwoByteString(chars, pretenure);
2003 if (result->IsFailure()) return result;
2004
2005 // Convert and copy the characters into the new object.
2006 String* string_result = String::cast(result);
2007 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00002008 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002009 for (int i = 0; i < chars; i++) {
2010 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00002011 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002012 }
2013 return result;
2014}
2015
2016
2017Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2018 PretenureFlag pretenure) {
2019 // Check if the string is an ASCII string.
2020 int i = 0;
2021 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2022
2023 Object* result;
2024 if (i == string.length()) { // It's an ASCII string.
2025 result = AllocateRawAsciiString(string.length(), pretenure);
2026 } else { // It's not an ASCII string.
2027 result = AllocateRawTwoByteString(string.length(), pretenure);
2028 }
2029 if (result->IsFailure()) return result;
2030
2031 // Copy the characters into the new object, which may be either ASCII or
2032 // UTF-16.
2033 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002034 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002035 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002036 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002037 }
2038 return result;
2039}
2040
2041
2042Map* Heap::SymbolMapForString(String* string) {
2043 // If the string is in new space it cannot be used as a symbol.
2044 if (InNewSpace(string)) return NULL;
2045
2046 // Find the corresponding symbol map for strings.
2047 Map* map = string->map();
2048
2049 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2050 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2051 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2052
2053 if (map == short_string_map()) return short_symbol_map();
2054 if (map == medium_string_map()) return medium_symbol_map();
2055 if (map == long_string_map()) return long_symbol_map();
2056
2057 if (map == short_cons_string_map()) return short_cons_symbol_map();
2058 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2059 if (map == long_cons_string_map()) return long_cons_symbol_map();
2060
2061 if (map == short_cons_ascii_string_map()) {
2062 return short_cons_ascii_symbol_map();
2063 }
2064 if (map == medium_cons_ascii_string_map()) {
2065 return medium_cons_ascii_symbol_map();
2066 }
2067 if (map == long_cons_ascii_string_map()) {
2068 return long_cons_ascii_symbol_map();
2069 }
2070
2071 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002072 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2073 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002074
2075 if (map == short_sliced_ascii_string_map()) {
2076 return short_sliced_ascii_symbol_map();
2077 }
2078 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002079 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080 }
2081 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002082 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002083 }
2084
ager@chromium.org6f10e412009-02-13 10:11:16 +00002085 if (map == short_external_string_map()) {
2086 return short_external_symbol_map();
2087 }
2088 if (map == medium_external_string_map()) {
2089 return medium_external_symbol_map();
2090 }
2091 if (map == long_external_string_map()) {
2092 return long_external_symbol_map();
2093 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002094
2095 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002096 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002097 }
2098 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002099 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002100 }
2101 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002102 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002103 }
2104
2105 // No match found.
2106 return NULL;
2107}
2108
2109
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002110Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2111 int chars,
2112 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002113 // Ensure the chars matches the number of characters in the buffer.
2114 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2115 // Determine whether the string is ascii.
2116 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002117 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002118 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2119 }
2120 buffer->Rewind();
2121
2122 // Compute map and object size.
2123 int size;
2124 Map* map;
2125
2126 if (is_ascii) {
2127 if (chars <= String::kMaxShortStringSize) {
2128 map = short_ascii_symbol_map();
2129 } else if (chars <= String::kMaxMediumStringSize) {
2130 map = medium_ascii_symbol_map();
2131 } else {
2132 map = long_ascii_symbol_map();
2133 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002134 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002135 } else {
2136 if (chars <= String::kMaxShortStringSize) {
2137 map = short_symbol_map();
2138 } else if (chars <= String::kMaxMediumStringSize) {
2139 map = medium_symbol_map();
2140 } else {
2141 map = long_symbol_map();
2142 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002143 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002144 }
2145
2146 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002147 AllocationSpace space =
2148 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002149 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002150 if (result->IsFailure()) return result;
2151
2152 reinterpret_cast<HeapObject*>(result)->set_map(map);
2153 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002154 String* answer = String::cast(result);
2155 StringShape answer_shape(answer);
2156 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002157
ager@chromium.org870a0b62008-11-04 11:43:05 +00002158 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002159
2160 // Fill in the characters.
2161 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002162 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002163 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002164 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002165}
2166
2167
2168Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002169 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002170 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002171 if (size > MaxHeapObjectSize()) {
2172 space = LO_SPACE;
2173 }
2174
2175 // Use AllocateRaw rather than Allocate because the object's size cannot be
2176 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002177 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002178 if (result->IsFailure()) return result;
2179
2180 // Determine the map based on the string's length.
2181 Map* map;
2182 if (length <= String::kMaxShortStringSize) {
2183 map = short_ascii_string_map();
2184 } else if (length <= String::kMaxMediumStringSize) {
2185 map = medium_ascii_string_map();
2186 } else {
2187 map = long_ascii_string_map();
2188 }
2189
2190 // Partially initialize the object.
2191 HeapObject::cast(result)->set_map(map);
2192 String::cast(result)->set_length(length);
2193 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2194 return result;
2195}
2196
2197
2198Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002199 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002200 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002201 if (size > MaxHeapObjectSize()) {
2202 space = LO_SPACE;
2203 }
2204
2205 // Use AllocateRaw rather than Allocate because the object's size cannot be
2206 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002207 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002208 if (result->IsFailure()) return result;
2209
2210 // Determine the map based on the string's length.
2211 Map* map;
2212 if (length <= String::kMaxShortStringSize) {
2213 map = short_string_map();
2214 } else if (length <= String::kMaxMediumStringSize) {
2215 map = medium_string_map();
2216 } else {
2217 map = long_string_map();
2218 }
2219
2220 // Partially initialize the object.
2221 HeapObject::cast(result)->set_map(map);
2222 String::cast(result)->set_length(length);
2223 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2224 return result;
2225}
2226
2227
2228Object* Heap::AllocateEmptyFixedArray() {
2229 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002230 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002231 if (result->IsFailure()) return result;
2232 // Initialize the object.
2233 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2234 reinterpret_cast<Array*>(result)->set_length(0);
2235 return result;
2236}
2237
2238
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002239Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002240 // Use the general function if we're forced to always allocate.
2241 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002242 // Allocate the raw data for a fixed array.
2243 int size = FixedArray::SizeFor(length);
2244 return (size > MaxHeapObjectSize())
2245 ? lo_space_->AllocateRawFixedArray(size)
2246 : new_space_.AllocateRaw(size);
2247}
2248
2249
2250Object* Heap::CopyFixedArray(FixedArray* src) {
2251 int len = src->length();
2252 Object* obj = AllocateRawFixedArray(len);
2253 if (obj->IsFailure()) return obj;
2254 if (Heap::InNewSpace(obj)) {
2255 HeapObject* dst = HeapObject::cast(obj);
2256 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2257 reinterpret_cast<Object**>(src->address()),
2258 FixedArray::SizeFor(len));
2259 return obj;
2260 }
2261 HeapObject::cast(obj)->set_map(src->map());
2262 FixedArray* result = FixedArray::cast(obj);
2263 result->set_length(len);
2264 // Copy the content
2265 WriteBarrierMode mode = result->GetWriteBarrierMode();
2266 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2267 return result;
2268}
2269
2270
2271Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002272 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002273 Object* result = AllocateRawFixedArray(length);
2274 if (!result->IsFailure()) {
2275 // Initialize header.
2276 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2277 FixedArray* array = FixedArray::cast(result);
2278 array->set_length(length);
2279 Object* value = undefined_value();
2280 // Initialize body.
2281 for (int index = 0; index < length; index++) {
2282 array->set(index, value, SKIP_WRITE_BARRIER);
2283 }
2284 }
2285 return result;
2286}
2287
2288
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002289Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2290 ASSERT(empty_fixed_array()->IsFixedArray());
2291 if (length == 0) return empty_fixed_array();
2292
2293 int size = FixedArray::SizeFor(length);
2294 Object* result;
2295 if (size > MaxHeapObjectSize()) {
2296 result = lo_space_->AllocateRawFixedArray(size);
2297 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002298 AllocationSpace space =
2299 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002300 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002301 }
2302 if (result->IsFailure()) return result;
2303
2304 // Initialize the object.
2305 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2306 FixedArray* array = FixedArray::cast(result);
2307 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002308 Object* value = undefined_value();
2309 for (int index = 0; index < length; index++) {
2310 array->set(index, value, SKIP_WRITE_BARRIER);
2311 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002312 return array;
2313}
2314
2315
2316Object* Heap::AllocateFixedArrayWithHoles(int length) {
2317 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002318 Object* result = AllocateRawFixedArray(length);
2319 if (!result->IsFailure()) {
2320 // Initialize header.
2321 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2322 FixedArray* array = FixedArray::cast(result);
2323 array->set_length(length);
2324 // Initialize body.
2325 Object* value = the_hole_value();
2326 for (int index = 0; index < length; index++) {
2327 array->set(index, value, SKIP_WRITE_BARRIER);
2328 }
2329 }
2330 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002331}
2332
2333
2334Object* Heap::AllocateHashTable(int length) {
2335 Object* result = Heap::AllocateFixedArray(length);
2336 if (result->IsFailure()) return result;
2337 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2338 ASSERT(result->IsDictionary());
2339 return result;
2340}
2341
2342
2343Object* Heap::AllocateGlobalContext() {
2344 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2345 if (result->IsFailure()) return result;
2346 Context* context = reinterpret_cast<Context*>(result);
2347 context->set_map(global_context_map());
2348 ASSERT(context->IsGlobalContext());
2349 ASSERT(result->IsContext());
2350 return result;
2351}
2352
2353
2354Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2355 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2356 Object* result = Heap::AllocateFixedArray(length);
2357 if (result->IsFailure()) return result;
2358 Context* context = reinterpret_cast<Context*>(result);
2359 context->set_map(context_map());
2360 context->set_closure(function);
2361 context->set_fcontext(context);
2362 context->set_previous(NULL);
2363 context->set_extension(NULL);
2364 context->set_global(function->context()->global());
2365 ASSERT(!context->IsGlobalContext());
2366 ASSERT(context->is_function_context());
2367 ASSERT(result->IsContext());
2368 return result;
2369}
2370
2371
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002372Object* Heap::AllocateWithContext(Context* previous,
2373 JSObject* extension,
2374 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002375 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2376 if (result->IsFailure()) return result;
2377 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002378 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002379 context->set_closure(previous->closure());
2380 context->set_fcontext(previous->fcontext());
2381 context->set_previous(previous);
2382 context->set_extension(extension);
2383 context->set_global(previous->global());
2384 ASSERT(!context->IsGlobalContext());
2385 ASSERT(!context->is_function_context());
2386 ASSERT(result->IsContext());
2387 return result;
2388}
2389
2390
2391Object* Heap::AllocateStruct(InstanceType type) {
2392 Map* map;
2393 switch (type) {
2394#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2395STRUCT_LIST(MAKE_CASE)
2396#undef MAKE_CASE
2397 default:
2398 UNREACHABLE();
2399 return Failure::InternalError();
2400 }
2401 int size = map->instance_size();
2402 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002403 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002404 Object* result = Heap::Allocate(map, space);
2405 if (result->IsFailure()) return result;
2406 Struct::cast(result)->InitializeBody(size);
2407 return result;
2408}
2409
2410
2411#ifdef DEBUG
2412
2413void Heap::Print() {
2414 if (!HasBeenSetup()) return;
2415 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002416 AllSpaces spaces;
2417 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002418}
2419
2420
2421void Heap::ReportCodeStatistics(const char* title) {
2422 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2423 PagedSpace::ResetCodeStatistics();
2424 // We do not look for code in new space, map space, or old space. If code
2425 // somehow ends up in those spaces, we would miss it here.
2426 code_space_->CollectCodeStatistics();
2427 lo_space_->CollectCodeStatistics();
2428 PagedSpace::ReportCodeStatistics();
2429}
2430
2431
2432// This function expects that NewSpace's allocated objects histogram is
2433// populated (via a call to CollectStatistics or else as a side effect of a
2434// just-completed scavenge collection).
2435void Heap::ReportHeapStatistics(const char* title) {
2436 USE(title);
2437 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2438 title, gc_count_);
2439 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002440 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2441 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002442
2443 PrintF("\n");
2444 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2445 GlobalHandles::PrintStats();
2446 PrintF("\n");
2447
2448 PrintF("Heap statistics : ");
2449 MemoryAllocator::ReportStatistics();
2450 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002451 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002452 PrintF("Old pointer space : ");
2453 old_pointer_space_->ReportStatistics();
2454 PrintF("Old data space : ");
2455 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002456 PrintF("Code space : ");
2457 code_space_->ReportStatistics();
2458 PrintF("Map space : ");
2459 map_space_->ReportStatistics();
2460 PrintF("Large object space : ");
2461 lo_space_->ReportStatistics();
2462 PrintF(">>>>>> ========================================= >>>>>>\n");
2463}
2464
2465#endif // DEBUG
2466
2467bool Heap::Contains(HeapObject* value) {
2468 return Contains(value->address());
2469}
2470
2471
2472bool Heap::Contains(Address addr) {
2473 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2474 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002475 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002476 old_pointer_space_->Contains(addr) ||
2477 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002478 code_space_->Contains(addr) ||
2479 map_space_->Contains(addr) ||
2480 lo_space_->SlowContains(addr));
2481}
2482
2483
2484bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2485 return InSpace(value->address(), space);
2486}
2487
2488
2489bool Heap::InSpace(Address addr, AllocationSpace space) {
2490 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2491 if (!HasBeenSetup()) return false;
2492
2493 switch (space) {
2494 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002495 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002496 case OLD_POINTER_SPACE:
2497 return old_pointer_space_->Contains(addr);
2498 case OLD_DATA_SPACE:
2499 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002500 case CODE_SPACE:
2501 return code_space_->Contains(addr);
2502 case MAP_SPACE:
2503 return map_space_->Contains(addr);
2504 case LO_SPACE:
2505 return lo_space_->SlowContains(addr);
2506 }
2507
2508 return false;
2509}
2510
2511
2512#ifdef DEBUG
2513void Heap::Verify() {
2514 ASSERT(HasBeenSetup());
2515
2516 VerifyPointersVisitor visitor;
2517 Heap::IterateRoots(&visitor);
2518
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002519 AllSpaces spaces;
2520 while (Space* space = spaces.next()) {
2521 space->Verify();
2522 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002523}
2524#endif // DEBUG
2525
2526
2527Object* Heap::LookupSymbol(Vector<const char> string) {
2528 Object* symbol = NULL;
2529 Object* new_table =
2530 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2531 if (new_table->IsFailure()) return new_table;
2532 symbol_table_ = new_table;
2533 ASSERT(symbol != NULL);
2534 return symbol;
2535}
2536
2537
2538Object* Heap::LookupSymbol(String* string) {
2539 if (string->IsSymbol()) return string;
2540 Object* symbol = NULL;
2541 Object* new_table =
2542 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2543 if (new_table->IsFailure()) return new_table;
2544 symbol_table_ = new_table;
2545 ASSERT(symbol != NULL);
2546 return symbol;
2547}
2548
2549
ager@chromium.org7c537e22008-10-16 08:43:32 +00002550bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2551 if (string->IsSymbol()) {
2552 *symbol = string;
2553 return true;
2554 }
2555 SymbolTable* table = SymbolTable::cast(symbol_table_);
2556 return table->LookupSymbolIfExists(string, symbol);
2557}
2558
2559
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002560#ifdef DEBUG
2561void Heap::ZapFromSpace() {
2562 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002563 for (Address a = new_space_.FromSpaceLow();
2564 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002565 a += kPointerSize) {
2566 Memory::Address_at(a) = kFromSpaceZapValue;
2567 }
2568}
2569#endif // DEBUG
2570
2571
2572void Heap::IterateRSetRange(Address object_start,
2573 Address object_end,
2574 Address rset_start,
2575 ObjectSlotCallback copy_object_func) {
2576 Address object_address = object_start;
2577 Address rset_address = rset_start;
2578
2579 // Loop over all the pointers in [object_start, object_end).
2580 while (object_address < object_end) {
2581 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002582 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002583 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002584 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002585 // Do not dereference pointers at or past object_end.
2586 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2587 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002588 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002589 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2590 }
2591 // If this pointer does not need to be remembered anymore, clear
2592 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002593 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002594 }
2595 object_address += kPointerSize;
2596 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002597 // Update the remembered set if it has changed.
2598 if (result_rset != rset_word) {
2599 Memory::uint32_at(rset_address) = result_rset;
2600 }
2601 } else {
2602 // No bits in the word were set. This is the common case.
2603 object_address += kPointerSize * kBitsPerInt;
2604 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002605 rset_address += kIntSize;
2606 }
2607}
2608
2609
2610void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2611 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002612 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002613
2614 PageIterator it(space, PageIterator::PAGES_IN_USE);
2615 while (it.has_next()) {
2616 Page* page = it.next();
2617 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2618 page->RSetStart(), copy_object_func);
2619 }
2620}
2621
2622
2623#ifdef DEBUG
2624#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2625#else
2626#define SYNCHRONIZE_TAG(tag)
2627#endif
2628
2629void Heap::IterateRoots(ObjectVisitor* v) {
2630 IterateStrongRoots(v);
2631 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2632 SYNCHRONIZE_TAG("symbol_table");
2633}
2634
2635
2636void Heap::IterateStrongRoots(ObjectVisitor* v) {
2637#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002638 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002639 STRONG_ROOT_LIST(ROOT_ITERATE);
2640#undef ROOT_ITERATE
2641 SYNCHRONIZE_TAG("strong_root_list");
2642
2643#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002644 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002645 STRUCT_LIST(STRUCT_MAP_ITERATE);
2646#undef STRUCT_MAP_ITERATE
2647 SYNCHRONIZE_TAG("struct_map");
2648
2649#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002650 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002651 SYMBOL_LIST(SYMBOL_ITERATE)
2652#undef SYMBOL_ITERATE
2653 SYNCHRONIZE_TAG("symbol");
2654
2655 Bootstrapper::Iterate(v);
2656 SYNCHRONIZE_TAG("bootstrapper");
2657 Top::Iterate(v);
2658 SYNCHRONIZE_TAG("top");
2659 Debug::Iterate(v);
2660 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002661 CompilationCache::Iterate(v);
2662 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002663
2664 // Iterate over local handles in handle scopes.
2665 HandleScopeImplementer::Iterate(v);
2666 SYNCHRONIZE_TAG("handlescope");
2667
2668 // Iterate over the builtin code objects and code stubs in the heap. Note
2669 // that it is not strictly necessary to iterate over code objects on
2670 // scavenge collections. We still do it here because this same function
2671 // is used by the mark-sweep collector and the deserializer.
2672 Builtins::IterateBuiltins(v);
2673 SYNCHRONIZE_TAG("builtins");
2674
2675 // Iterate over global handles.
2676 GlobalHandles::IterateRoots(v);
2677 SYNCHRONIZE_TAG("globalhandles");
2678
2679 // Iterate over pointers being held by inactive threads.
2680 ThreadManager::Iterate(v);
2681 SYNCHRONIZE_TAG("threadmanager");
2682}
2683#undef SYNCHRONIZE_TAG
2684
2685
2686// Flag is set when the heap has been configured. The heap can be repeatedly
2687// configured through the API until it is setup.
2688static bool heap_configured = false;
2689
2690// TODO(1236194): Since the heap size is configurable on the command line
2691// and through the API, we should gracefully handle the case that the heap
2692// size is not big enough to fit all the initial objects.
2693bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2694 if (HasBeenSetup()) return false;
2695
2696 if (semispace_size > 0) semispace_size_ = semispace_size;
2697 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2698
2699 // The new space size must be a power of two to support single-bit testing
2700 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002701 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002702 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2703 young_generation_size_ = 2 * semispace_size_;
2704
2705 // The old generation is paged.
2706 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2707
2708 heap_configured = true;
2709 return true;
2710}
2711
2712
kasper.lund7276f142008-07-30 08:49:36 +00002713bool Heap::ConfigureHeapDefault() {
2714 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2715}
2716
2717
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002718int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002719 return old_pointer_space_->Size()
2720 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002721 + code_space_->Size()
2722 + map_space_->Size()
2723 + lo_space_->Size();
2724}
2725
2726
kasper.lund7276f142008-07-30 08:49:36 +00002727int Heap::PromotedExternalMemorySize() {
2728 if (amount_of_external_allocated_memory_
2729 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2730 return amount_of_external_allocated_memory_
2731 - amount_of_external_allocated_memory_at_last_global_gc_;
2732}
2733
2734
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002735bool Heap::Setup(bool create_heap_objects) {
2736 // Initialize heap spaces and initial maps and objects. Whenever something
2737 // goes wrong, just return false. The caller should check the results and
2738 // call Heap::TearDown() to release allocated memory.
2739 //
2740 // If the heap is not yet configured (eg, through the API), configure it.
2741 // Configuration is based on the flags new-space-size (really the semispace
2742 // size) and old-space-size if set or the initial values of semispace_size_
2743 // and old_generation_size_ otherwise.
2744 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002745 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002746 }
2747
2748 // Setup memory allocator and allocate an initial chunk of memory. The
2749 // initial chunk is double the size of the new space to ensure that we can
2750 // find a pair of semispaces that are contiguous and aligned to their size.
2751 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2752 void* chunk
2753 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2754 if (chunk == NULL) return false;
2755
2756 // Put the initial chunk of the old space at the start of the initial
2757 // chunk, then the two new space semispaces, then the initial chunk of
2758 // code space. Align the pair of semispaces to their size, which must be
2759 // a power of 2.
2760 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002761 Address code_space_start = reinterpret_cast<Address>(chunk);
2762 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2763 Address old_space_start = new_space_start + young_generation_size_;
2764 int code_space_size = new_space_start - code_space_start;
2765 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002766
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002767 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002768 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002769
2770 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002771 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002772 old_pointer_space_ =
2773 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2774 if (old_pointer_space_ == NULL) return false;
2775 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2776 return false;
2777 }
2778 old_data_space_ =
2779 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2780 if (old_data_space_ == NULL) return false;
2781 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2782 old_space_size >> 1)) {
2783 return false;
2784 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002785
2786 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002787 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002788 code_space_ =
2789 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002790 if (code_space_ == NULL) return false;
2791 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2792
2793 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002794 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002795 if (map_space_ == NULL) return false;
2796 // Setting up a paged space without giving it a virtual memory range big
2797 // enough to hold at least a page will cause it to allocate.
2798 if (!map_space_->Setup(NULL, 0)) return false;
2799
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002800 // The large object code space may contain code or data. We set the memory
2801 // to be non-executable here for safety, but this means we need to enable it
2802 // explicitly when allocating large code objects.
2803 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002804 if (lo_space_ == NULL) return false;
2805 if (!lo_space_->Setup()) return false;
2806
2807 if (create_heap_objects) {
2808 // Create initial maps.
2809 if (!CreateInitialMaps()) return false;
2810 if (!CreateApiObjects()) return false;
2811
2812 // Create initial objects
2813 if (!CreateInitialObjects()) return false;
2814 }
2815
2816 LOG(IntEvent("heap-capacity", Capacity()));
2817 LOG(IntEvent("heap-available", Available()));
2818
2819 return true;
2820}
2821
2822
2823void Heap::TearDown() {
2824 GlobalHandles::TearDown();
2825
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002826 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002827
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002828 if (old_pointer_space_ != NULL) {
2829 old_pointer_space_->TearDown();
2830 delete old_pointer_space_;
2831 old_pointer_space_ = NULL;
2832 }
2833
2834 if (old_data_space_ != NULL) {
2835 old_data_space_->TearDown();
2836 delete old_data_space_;
2837 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002838 }
2839
2840 if (code_space_ != NULL) {
2841 code_space_->TearDown();
2842 delete code_space_;
2843 code_space_ = NULL;
2844 }
2845
2846 if (map_space_ != NULL) {
2847 map_space_->TearDown();
2848 delete map_space_;
2849 map_space_ = NULL;
2850 }
2851
2852 if (lo_space_ != NULL) {
2853 lo_space_->TearDown();
2854 delete lo_space_;
2855 lo_space_ = NULL;
2856 }
2857
2858 MemoryAllocator::TearDown();
2859}
2860
2861
2862void Heap::Shrink() {
2863 // Try to shrink map, old, and code spaces.
2864 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002865 old_pointer_space_->Shrink();
2866 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002867 code_space_->Shrink();
2868}
2869
2870
2871#ifdef DEBUG
2872
2873class PrintHandleVisitor: public ObjectVisitor {
2874 public:
2875 void VisitPointers(Object** start, Object** end) {
2876 for (Object** p = start; p < end; p++)
2877 PrintF(" handle %p to %p\n", p, *p);
2878 }
2879};
2880
2881void Heap::PrintHandles() {
2882 PrintF("Handles:\n");
2883 PrintHandleVisitor v;
2884 HandleScopeImplementer::Iterate(&v);
2885}
2886
2887#endif
2888
2889
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002890Space* AllSpaces::next() {
2891 switch (counter_++) {
2892 case NEW_SPACE:
2893 return Heap::new_space();
2894 case OLD_POINTER_SPACE:
2895 return Heap::old_pointer_space();
2896 case OLD_DATA_SPACE:
2897 return Heap::old_data_space();
2898 case CODE_SPACE:
2899 return Heap::code_space();
2900 case MAP_SPACE:
2901 return Heap::map_space();
2902 case LO_SPACE:
2903 return Heap::lo_space();
2904 default:
2905 return NULL;
2906 }
2907}
2908
2909
2910PagedSpace* PagedSpaces::next() {
2911 switch (counter_++) {
2912 case OLD_POINTER_SPACE:
2913 return Heap::old_pointer_space();
2914 case OLD_DATA_SPACE:
2915 return Heap::old_data_space();
2916 case CODE_SPACE:
2917 return Heap::code_space();
2918 case MAP_SPACE:
2919 return Heap::map_space();
2920 default:
2921 return NULL;
2922 }
2923}
2924
2925
2926
2927OldSpace* OldSpaces::next() {
2928 switch (counter_++) {
2929 case OLD_POINTER_SPACE:
2930 return Heap::old_pointer_space();
2931 case OLD_DATA_SPACE:
2932 return Heap::old_data_space();
2933 case CODE_SPACE:
2934 return Heap::code_space();
2935 default:
2936 return NULL;
2937 }
2938}
2939
2940
kasper.lund7276f142008-07-30 08:49:36 +00002941SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2942}
2943
2944
2945SpaceIterator::~SpaceIterator() {
2946 // Delete active iterator if any.
2947 delete iterator_;
2948}
2949
2950
2951bool SpaceIterator::has_next() {
2952 // Iterate until no more spaces.
2953 return current_space_ != LAST_SPACE;
2954}
2955
2956
2957ObjectIterator* SpaceIterator::next() {
2958 if (iterator_ != NULL) {
2959 delete iterator_;
2960 iterator_ = NULL;
2961 // Move to the next space
2962 current_space_++;
2963 if (current_space_ > LAST_SPACE) {
2964 return NULL;
2965 }
2966 }
2967
2968 // Return iterator for the new current space.
2969 return CreateIterator();
2970}
2971
2972
2973// Create an iterator for the space to iterate.
2974ObjectIterator* SpaceIterator::CreateIterator() {
2975 ASSERT(iterator_ == NULL);
2976
2977 switch (current_space_) {
2978 case NEW_SPACE:
2979 iterator_ = new SemiSpaceIterator(Heap::new_space());
2980 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002981 case OLD_POINTER_SPACE:
2982 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2983 break;
2984 case OLD_DATA_SPACE:
2985 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002986 break;
2987 case CODE_SPACE:
2988 iterator_ = new HeapObjectIterator(Heap::code_space());
2989 break;
2990 case MAP_SPACE:
2991 iterator_ = new HeapObjectIterator(Heap::map_space());
2992 break;
2993 case LO_SPACE:
2994 iterator_ = new LargeObjectIterator(Heap::lo_space());
2995 break;
2996 }
2997
2998 // Return the newly allocated iterator;
2999 ASSERT(iterator_ != NULL);
3000 return iterator_;
3001}
3002
3003
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003004HeapIterator::HeapIterator() {
3005 Init();
3006}
3007
3008
3009HeapIterator::~HeapIterator() {
3010 Shutdown();
3011}
3012
3013
3014void HeapIterator::Init() {
3015 // Start the iteration.
3016 space_iterator_ = new SpaceIterator();
3017 object_iterator_ = space_iterator_->next();
3018}
3019
3020
3021void HeapIterator::Shutdown() {
3022 // Make sure the last iterator is deallocated.
3023 delete space_iterator_;
3024 space_iterator_ = NULL;
3025 object_iterator_ = NULL;
3026}
3027
3028
3029bool HeapIterator::has_next() {
3030 // No iterator means we are done.
3031 if (object_iterator_ == NULL) return false;
3032
3033 if (object_iterator_->has_next_object()) {
3034 // If the current iterator has more objects we are fine.
3035 return true;
3036 } else {
3037 // Go though the spaces looking for one that has objects.
3038 while (space_iterator_->has_next()) {
3039 object_iterator_ = space_iterator_->next();
3040 if (object_iterator_->has_next_object()) {
3041 return true;
3042 }
3043 }
3044 }
3045 // Done with the last space.
3046 object_iterator_ = NULL;
3047 return false;
3048}
3049
3050
3051HeapObject* HeapIterator::next() {
3052 if (has_next()) {
3053 return object_iterator_->next_object();
3054 } else {
3055 return NULL;
3056 }
3057}
3058
3059
3060void HeapIterator::reset() {
3061 // Restart the iterator.
3062 Shutdown();
3063 Init();
3064}
3065
3066
3067//
3068// HeapProfiler class implementation.
3069//
3070#ifdef ENABLE_LOGGING_AND_PROFILING
3071void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3072 InstanceType type = obj->map()->instance_type();
3073 ASSERT(0 <= type && type <= LAST_TYPE);
3074 info[type].increment_number(1);
3075 info[type].increment_bytes(obj->Size());
3076}
3077#endif
3078
3079
3080#ifdef ENABLE_LOGGING_AND_PROFILING
3081void HeapProfiler::WriteSample() {
3082 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3083
3084 HistogramInfo info[LAST_TYPE+1];
3085#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3086 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3087#undef DEF_TYPE_NAME
3088
3089 HeapIterator iterator;
3090 while (iterator.has_next()) {
3091 CollectStats(iterator.next(), info);
3092 }
3093
3094 // Lump all the string types together.
3095 int string_number = 0;
3096 int string_bytes = 0;
3097#define INCREMENT_SIZE(type, size, name) \
3098 string_number += info[type].number(); \
3099 string_bytes += info[type].bytes();
3100 STRING_TYPE_LIST(INCREMENT_SIZE)
3101#undef INCREMENT_SIZE
3102 if (string_bytes > 0) {
3103 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3104 }
3105
3106 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3107 if (info[i].bytes() > 0) {
3108 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3109 info[i].bytes()));
3110 }
3111 }
3112
3113 LOG(HeapSampleEndEvent("Heap", "allocated"));
3114}
3115
3116
3117#endif
3118
3119
3120
3121#ifdef DEBUG
3122
3123static bool search_for_any_global;
3124static Object* search_target;
3125static bool found_target;
3126static List<Object*> object_stack(20);
3127
3128
3129// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3130static const int kMarkTag = 2;
3131
3132static void MarkObjectRecursively(Object** p);
3133class MarkObjectVisitor : public ObjectVisitor {
3134 public:
3135 void VisitPointers(Object** start, Object** end) {
3136 // Copy all HeapObject pointers in [start, end)
3137 for (Object** p = start; p < end; p++) {
3138 if ((*p)->IsHeapObject())
3139 MarkObjectRecursively(p);
3140 }
3141 }
3142};
3143
3144static MarkObjectVisitor mark_visitor;
3145
3146static void MarkObjectRecursively(Object** p) {
3147 if (!(*p)->IsHeapObject()) return;
3148
3149 HeapObject* obj = HeapObject::cast(*p);
3150
3151 Object* map = obj->map();
3152
3153 if (!map->IsHeapObject()) return; // visited before
3154
3155 if (found_target) return; // stop if target found
3156 object_stack.Add(obj);
3157 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3158 (!search_for_any_global && (obj == search_target))) {
3159 found_target = true;
3160 return;
3161 }
3162
3163 if (obj->IsCode()) {
3164 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3165 }
3166
3167 // not visited yet
3168 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3169
3170 Address map_addr = map_p->address();
3171
3172 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3173
3174 MarkObjectRecursively(&map);
3175
3176 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3177 &mark_visitor);
3178
3179 if (!found_target) // don't pop if found the target
3180 object_stack.RemoveLast();
3181}
3182
3183
3184static void UnmarkObjectRecursively(Object** p);
3185class UnmarkObjectVisitor : public ObjectVisitor {
3186 public:
3187 void VisitPointers(Object** start, Object** end) {
3188 // Copy all HeapObject pointers in [start, end)
3189 for (Object** p = start; p < end; p++) {
3190 if ((*p)->IsHeapObject())
3191 UnmarkObjectRecursively(p);
3192 }
3193 }
3194};
3195
3196static UnmarkObjectVisitor unmark_visitor;
3197
3198static void UnmarkObjectRecursively(Object** p) {
3199 if (!(*p)->IsHeapObject()) return;
3200
3201 HeapObject* obj = HeapObject::cast(*p);
3202
3203 Object* map = obj->map();
3204
3205 if (map->IsHeapObject()) return; // unmarked already
3206
3207 Address map_addr = reinterpret_cast<Address>(map);
3208
3209 map_addr -= kMarkTag;
3210
3211 ASSERT_TAG_ALIGNED(map_addr);
3212
3213 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3214
3215 obj->set_map(reinterpret_cast<Map*>(map_p));
3216
3217 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3218
3219 obj->IterateBody(Map::cast(map_p)->instance_type(),
3220 obj->SizeFromMap(Map::cast(map_p)),
3221 &unmark_visitor);
3222
3223 if (obj->IsCode()) {
3224 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3225 }
3226}
3227
3228
3229static void MarkRootObjectRecursively(Object** root) {
3230 if (search_for_any_global) {
3231 ASSERT(search_target == NULL);
3232 } else {
3233 ASSERT(search_target->IsHeapObject());
3234 }
3235 found_target = false;
3236 object_stack.Clear();
3237
3238 MarkObjectRecursively(root);
3239 UnmarkObjectRecursively(root);
3240
3241 if (found_target) {
3242 PrintF("=====================================\n");
3243 PrintF("==== Path to object ====\n");
3244 PrintF("=====================================\n\n");
3245
3246 ASSERT(!object_stack.is_empty());
3247 for (int i = 0; i < object_stack.length(); i++) {
3248 if (i > 0) PrintF("\n |\n |\n V\n\n");
3249 Object* obj = object_stack[i];
3250 obj->Print();
3251 }
3252 PrintF("=====================================\n");
3253 }
3254}
3255
3256
3257// Helper class for visiting HeapObjects recursively.
3258class MarkRootVisitor: public ObjectVisitor {
3259 public:
3260 void VisitPointers(Object** start, Object** end) {
3261 // Visit all HeapObject pointers in [start, end)
3262 for (Object** p = start; p < end; p++) {
3263 if ((*p)->IsHeapObject())
3264 MarkRootObjectRecursively(p);
3265 }
3266 }
3267};
3268
3269
3270// Triggers a depth-first traversal of reachable objects from roots
3271// and finds a path to a specific heap object and prints it.
3272void Heap::TracePathToObject() {
3273 search_target = NULL;
3274 search_for_any_global = false;
3275
3276 MarkRootVisitor root_visitor;
3277 IterateRoots(&root_visitor);
3278}
3279
3280
3281// Triggers a depth-first traversal of reachable objects from roots
3282// and finds a path to any global object and prints it. Useful for
3283// determining the source for leaks of global objects.
3284void Heap::TracePathToGlobal() {
3285 search_target = NULL;
3286 search_for_any_global = true;
3287
3288 MarkRootVisitor root_visitor;
3289 IterateRoots(&root_visitor);
3290}
3291#endif
3292
3293
kasper.lund7276f142008-07-30 08:49:36 +00003294GCTracer::GCTracer()
3295 : start_time_(0.0),
3296 start_size_(0.0),
3297 gc_count_(0),
3298 full_gc_count_(0),
3299 is_compacting_(false),
3300 marked_count_(0) {
3301 // These two fields reflect the state of the previous full collection.
3302 // Set them before they are changed by the collector.
3303 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3304 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3305 if (!FLAG_trace_gc) return;
3306 start_time_ = OS::TimeCurrentMillis();
3307 start_size_ = SizeOfHeapObjects();
3308}
3309
3310
3311GCTracer::~GCTracer() {
3312 if (!FLAG_trace_gc) return;
3313 // Printf ONE line iff flag is set.
3314 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3315 CollectorString(),
3316 start_size_, SizeOfHeapObjects(),
3317 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3318}
3319
3320
3321const char* GCTracer::CollectorString() {
3322 switch (collector_) {
3323 case SCAVENGER:
3324 return "Scavenge";
3325 case MARK_COMPACTOR:
3326 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3327 : "Mark-sweep";
3328 }
3329 return "Unknown GC";
3330}
3331
3332
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003333#ifdef DEBUG
3334bool Heap::GarbageCollectionGreedyCheck() {
3335 ASSERT(FLAG_gc_greedy);
3336 if (Bootstrapper::IsActive()) return true;
3337 if (disallow_allocation_failure()) return true;
3338 return CollectGarbage(0, NEW_SPACE);
3339}
3340#endif
3341
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003342} } // namespace v8::internal