blob: a5b7b30658de00b0601d0041875c3014f7fa33dd [file] [log] [blame]
ager@chromium.org71daaf62009-04-01 07:22:49 +00001// Copyright 2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
33#include "codegen-inl.h"
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "debug.h"
36#include "global-handles.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "mark-compact.h"
38#include "natives.h"
39#include "scanner.h"
40#include "scopeinfo.h"
41#include "v8threads.h"
42
43namespace v8 { namespace internal {
44
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
46 ROOT_LIST(ROOT_ALLOCATION)
47#undef ROOT_ALLOCATION
48
49
50#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
51 STRUCT_LIST(STRUCT_ALLOCATION)
52#undef STRUCT_ALLOCATION
53
54
55#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
56 SYMBOL_LIST(SYMBOL_ALLOCATION)
57#undef SYMBOL_ALLOCATION
58
ager@chromium.org3b45ab52009-03-19 22:21:34 +000059String* Heap::hidden_symbol_;
60
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000061NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000062OldSpace* Heap::old_pointer_space_ = NULL;
63OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000064OldSpace* Heap::code_space_ = NULL;
65MapSpace* Heap::map_space_ = NULL;
66LargeObjectSpace* Heap::lo_space_ = NULL;
67
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000068static const int kMinimumPromotionLimit = 2*MB;
69static const int kMinimumAllocationLimit = 8*MB;
70
71int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
72int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
73
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074int Heap::old_gen_exhausted_ = false;
75
kasper.lund7276f142008-07-30 08:49:36 +000076int Heap::amount_of_external_allocated_memory_ = 0;
77int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
78
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000079// semispace_size_ should be a power of 2 and old_generation_size_ should be
80// a multiple of Page::kPageSize.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000081int Heap::semispace_size_ = 2*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082int Heap::old_generation_size_ = 512*MB;
83int Heap::initial_semispace_size_ = 256*KB;
84
85GCCallback Heap::global_gc_prologue_callback_ = NULL;
86GCCallback Heap::global_gc_epilogue_callback_ = NULL;
87
88// Variables set based on semispace_size_ and old_generation_size_ in
89// ConfigureHeap.
90int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
91
92// Double the new space after this many scavenge collections.
93int Heap::new_space_growth_limit_ = 8;
94int Heap::scavenge_count_ = 0;
95Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097int Heap::mc_count_ = 0;
98int Heap::gc_count_ = 0;
99
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000100int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000101bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000102
kasper.lund7276f142008-07-30 08:49:36 +0000103#ifdef DEBUG
104bool Heap::allocation_allowed_ = true;
105
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000106int Heap::allocation_timeout_ = 0;
107bool Heap::disallow_allocation_failure_ = false;
108#endif // DEBUG
109
110
111int Heap::Capacity() {
112 if (!HasBeenSetup()) return 0;
113
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000114 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000115 old_pointer_space_->Capacity() +
116 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 code_space_->Capacity() +
118 map_space_->Capacity();
119}
120
121
122int Heap::Available() {
123 if (!HasBeenSetup()) return 0;
124
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000125 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000126 old_pointer_space_->Available() +
127 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 code_space_->Available() +
129 map_space_->Available();
130}
131
132
133bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000134 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000135 old_data_space_ != NULL &&
136 code_space_ != NULL &&
137 map_space_ != NULL &&
138 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139}
140
141
142GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
143 // Is global GC requested?
144 if (space != NEW_SPACE || FLAG_gc_global) {
145 Counters::gc_compactor_caused_by_request.Increment();
146 return MARK_COMPACTOR;
147 }
148
149 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000150 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000151 Counters::gc_compactor_caused_by_promoted_data.Increment();
152 return MARK_COMPACTOR;
153 }
154
155 // Have allocation in OLD and LO failed?
156 if (old_gen_exhausted_) {
157 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
158 return MARK_COMPACTOR;
159 }
160
161 // Is there enough space left in OLD to guarantee that a scavenge can
162 // succeed?
163 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000164 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 // for object promotion. It counts only the bytes that the memory
166 // allocator has not yet allocated from the OS and assigned to any space,
167 // and does not count available bytes already in the old space or code
168 // space. Undercounting is safe---we may get an unrequested full GC when
169 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000170 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
172 return MARK_COMPACTOR;
173 }
174
175 // Default
176 return SCAVENGER;
177}
178
179
180// TODO(1238405): Combine the infrastructure for --heap-stats and
181// --log-gc to avoid the complicated preprocessor and flag testing.
182#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
183void Heap::ReportStatisticsBeforeGC() {
184 // Heap::ReportHeapStatistics will also log NewSpace statistics when
185 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
186 // following logic is used to avoid double logging.
187#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000188 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000189 if (FLAG_heap_stats) {
190 ReportHeapStatistics("Before GC");
191 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000192 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000194 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195#elif defined(DEBUG)
196 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000199 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 }
201#elif defined(ENABLE_LOGGING_AND_PROFILING)
202 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 new_space_.CollectStatistics();
204 new_space_.ReportStatistics();
205 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 }
207#endif
208}
209
210
211// TODO(1238405): Combine the infrastructure for --heap-stats and
212// --log-gc to avoid the complicated preprocessor and flag testing.
213void Heap::ReportStatisticsAfterGC() {
214 // Similar to the before GC, we use some complicated logic to ensure that
215 // NewSpace statistics are logged exactly once when --log-gc is turned on.
216#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
217 if (FLAG_heap_stats) {
218 ReportHeapStatistics("After GC");
219 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000220 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000221 }
222#elif defined(DEBUG)
223 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
224#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000225 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226#endif
227}
228#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
229
230
231void Heap::GarbageCollectionPrologue() {
kasper.lund7276f142008-07-30 08:49:36 +0000232 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233#ifdef DEBUG
234 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
235 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237 if (FLAG_verify_heap) {
238 Verify();
239 }
240
241 if (FLAG_gc_verbose) Print();
242
243 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000244 // Not all spaces have remembered set bits that we care about.
245 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 map_space_->PrintRSet();
247 lo_space_->PrintRSet();
248 }
249#endif
250
251#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
252 ReportStatisticsBeforeGC();
253#endif
254}
255
256int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000257 int total = 0;
258 AllSpaces spaces;
259 while (Space* space = spaces.next()) total += space->Size();
260 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261}
262
263void Heap::GarbageCollectionEpilogue() {
264#ifdef DEBUG
265 allow_allocation(true);
266 ZapFromSpace();
267
268 if (FLAG_verify_heap) {
269 Verify();
270 }
271
272 if (FLAG_print_global_handles) GlobalHandles::Print();
273 if (FLAG_print_handles) PrintHandles();
274 if (FLAG_gc_verbose) Print();
275 if (FLAG_code_stats) ReportCodeStatistics("After GC");
276#endif
277
278 Counters::alive_after_last_gc.Set(SizeOfObjects());
279
280 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
281 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
282 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
283#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
284 ReportStatisticsAfterGC();
285#endif
286}
287
288
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000289void Heap::CollectAllGarbage() {
290 // Since we are ignoring the return value, the exact choice of space does
291 // not matter, so long as we do not specify NEW_SPACE, which would not
292 // cause a full GC.
293 CollectGarbage(0, OLD_POINTER_SPACE);
294}
295
296
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000297void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000298 // If the garbage collector interface is exposed through the global
299 // gc() function, we avoid being clever about forcing GCs when
300 // contexts are disposed and leave it to the embedder to make
301 // informed decisions about when to force a collection.
302 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000303 HistogramTimerScope scope(&Counters::gc_context);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000304 CollectAllGarbage();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000305 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000306 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000307}
308
309
310void Heap::NotifyContextDisposed() {
311 context_disposed_pending_ = true;
312}
313
314
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000315bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
316 // The VM is in the GC state until exiting this function.
317 VMState state(GC);
318
319#ifdef DEBUG
320 // Reset the allocation timeout to the GC interval, but make sure to
321 // allow at least a few allocations after a collection. The reason
322 // for this is that we have a lot of allocation sequences and we
323 // assume that a garbage collection will allow the subsequent
324 // allocation attempts to go through.
325 allocation_timeout_ = Max(6, FLAG_gc_interval);
326#endif
327
328 { GCTracer tracer;
329 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000330 // The GC count was incremented in the prologue. Tell the tracer about
331 // it.
332 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333
334 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000335 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 tracer.set_collector(collector);
337
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000338 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 ? &Counters::gc_scavenger
340 : &Counters::gc_compactor;
341 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000342 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 rate->Stop();
344
345 GarbageCollectionEpilogue();
346 }
347
348
349#ifdef ENABLE_LOGGING_AND_PROFILING
350 if (FLAG_log_gc) HeapProfiler::WriteSample();
351#endif
352
353 switch (space) {
354 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000355 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000356 case OLD_POINTER_SPACE:
357 return old_pointer_space_->Available() >= requested_size;
358 case OLD_DATA_SPACE:
359 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 case CODE_SPACE:
361 return code_space_->Available() >= requested_size;
362 case MAP_SPACE:
363 return map_space_->Available() >= requested_size;
364 case LO_SPACE:
365 return lo_space_->Available() >= requested_size;
366 }
367 return false;
368}
369
370
kasper.lund7276f142008-07-30 08:49:36 +0000371void Heap::PerformScavenge() {
372 GCTracer tracer;
373 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
374}
375
376
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000377#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000378// Helper class for verifying the symbol table.
379class SymbolTableVerifier : public ObjectVisitor {
380 public:
381 SymbolTableVerifier() { }
382 void VisitPointers(Object** start, Object** end) {
383 // Visit all HeapObject pointers in [start, end).
384 for (Object** p = start; p < end; p++) {
385 if ((*p)->IsHeapObject()) {
386 // Check that the symbol is actually a symbol.
387 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000388 }
389 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000390 }
391};
392#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000393
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000394
395static void VerifySymbolTable() {
396#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000397 SymbolTableVerifier verifier;
398 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table());
399 symbol_table->IterateElements(&verifier);
400#endif // DEBUG
401}
402
403
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000404void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000405 GarbageCollector collector,
406 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000407 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000408 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
409 ASSERT(!allocation_allowed_);
410 global_gc_prologue_callback_();
411 }
412
413 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000414 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000415
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000416 int old_gen_size = PromotedSpaceSize();
417 old_gen_promotion_limit_ =
418 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
419 old_gen_allocation_limit_ =
420 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000421 old_gen_exhausted_ = false;
422
423 // If we have used the mark-compact collector to collect the new
424 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000425 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000426 // case where (1) a new space collection was requested, (2) the
427 // collector selection policy selected the mark-compact collector,
428 // and (3) the mark-compact collector policy selected not to
429 // compact the new space. In that case, there is no more (usable)
430 // free space in the new space after the collection compared to
431 // before.
432 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
433 Scavenge();
434 }
435 } else {
436 Scavenge();
437 }
438 Counters::objs_since_last_young.Set(0);
439
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000440 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000441
kasper.lund7276f142008-07-30 08:49:36 +0000442 if (collector == MARK_COMPACTOR) {
443 // Register the amount of external allocated memory.
444 amount_of_external_allocated_memory_at_last_global_gc_ =
445 amount_of_external_allocated_memory_;
446 }
447
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000448 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
449 ASSERT(!allocation_allowed_);
450 global_gc_epilogue_callback_();
451 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000452 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000453}
454
455
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000456void Heap::PostGarbageCollectionProcessing() {
457 // Process weak handles post gc.
458 GlobalHandles::PostGarbageCollectionProcessing();
459 // Update flat string readers.
460 FlatStringReader::PostGarbageCollectionProcessing();
461}
462
463
kasper.lund7276f142008-07-30 08:49:36 +0000464void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000466 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000467 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468 LOG(ResourceEvent("markcompact", "begin"));
469
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000470 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000472 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000474 MarkCompactPrologue(is_compacting);
475
476 MarkCompactCollector::CollectGarbage();
477
478 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000479
480 LOG(ResourceEvent("markcompact", "end"));
481
482 gc_state_ = NOT_IN_GC;
483
484 Shrink();
485
486 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000487 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000488}
489
490
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000491void Heap::MarkCompactPrologue(bool is_compacting) {
492 // At any old GC clear the keyed lookup cache to enable collection of unused
493 // maps.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000494 ClearKeyedLookupCache();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000495
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000496 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000497
498 Top::MarkCompactPrologue(is_compacting);
499 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500}
501
502
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000503void Heap::MarkCompactEpilogue(bool is_compacting) {
504 Top::MarkCompactEpilogue(is_compacting);
505 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506}
507
508
509Object* Heap::FindCodeObject(Address a) {
510 Object* obj = code_space_->FindObject(a);
511 if (obj->IsFailure()) {
512 obj = lo_space_->FindObject(a);
513 }
kasper.lund7276f142008-07-30 08:49:36 +0000514 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515 return obj;
516}
517
518
519// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000520class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521 public:
522
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000523 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524
525 void VisitPointers(Object** start, Object** end) {
526 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000527 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528 }
529
530 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000531 void ScavengePointer(Object** p) {
532 Object* object = *p;
533 if (!Heap::InNewSpace(object)) return;
534 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
535 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000536 }
537};
538
539
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000540// A queue of pointers and maps of to-be-promoted objects during a
541// scavenge collection.
542class PromotionQueue {
543 public:
544 void Initialize(Address start_address) {
545 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
546 }
547
548 bool is_empty() { return front_ <= rear_; }
549
550 void insert(HeapObject* object, Map* map) {
551 *(--rear_) = object;
552 *(--rear_) = map;
553 // Assert no overflow into live objects.
554 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
555 }
556
557 void remove(HeapObject** object, Map** map) {
558 *object = *(--front_);
559 *map = Map::cast(*(--front_));
560 // Assert no underflow.
561 ASSERT(front_ >= rear_);
562 }
563
564 private:
565 // The front of the queue is higher in memory than the rear.
566 HeapObject** front_;
567 HeapObject** rear_;
568};
569
570
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000571// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000572static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573
574
575#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000576// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000577// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000578class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 public:
580 void VisitPointers(Object** start, Object**end) {
581 for (Object** current = start; current < end; current++) {
582 if ((*current)->IsHeapObject()) {
583 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
584 }
585 }
586 }
587};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000588
589
590static void VerifyNonPointerSpacePointers() {
591 // Verify that there are no pointers to new space in spaces where we
592 // do not expect them.
593 VerifyNonPointerSpacePointersVisitor v;
594 HeapObjectIterator code_it(Heap::code_space());
595 while (code_it.has_next()) {
596 HeapObject* object = code_it.next();
597 if (object->IsCode()) {
598 Code::cast(object)->ConvertICTargetsFromAddressToObject();
599 object->Iterate(&v);
600 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
601 } else {
602 // If we find non-code objects in code space (e.g., free list
603 // nodes) we want to verify them as well.
604 object->Iterate(&v);
605 }
606 }
607
608 HeapObjectIterator data_it(Heap::old_data_space());
609 while (data_it.has_next()) data_it.next()->Iterate(&v);
610}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611#endif
612
613void Heap::Scavenge() {
614#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000615 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000616#endif
617
618 gc_state_ = SCAVENGE;
619
620 // Implements Cheney's copying algorithm
621 LOG(ResourceEvent("scavenge", "begin"));
622
623 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000624 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625 scavenge_count_ > new_space_growth_limit_) {
626 // Double the size of the new space, and double the limit. The next
627 // doubling attempt will occur after the current new_space_growth_limit_
628 // more collections.
629 // TODO(1240712): NewSpace::Double has a return value which is
630 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000631 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000632 new_space_growth_limit_ *= 2;
633 }
634
635 // Flip the semispaces. After flipping, to space is empty, from space has
636 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000637 new_space_.Flip();
638 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000639
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000640 // We need to sweep newly copied objects which can be either in the
641 // to space or promoted to the old generation. For to-space
642 // objects, we treat the bottom of the to space as a queue. Newly
643 // copied and unswept objects lie between a 'front' mark and the
644 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000645 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000646 // Promoted objects can go into various old-generation spaces, and
647 // can be allocated internally in the spaces (from the free list).
648 // We treat the top of the to space as a queue of addresses of
649 // promoted objects. The addresses of newly promoted and unswept
650 // objects lie between a 'front' mark and a 'rear' mark that is
651 // updated as a side effect of promoting an object.
652 //
653 // There is guaranteed to be enough room at the top of the to space
654 // for the addresses of promoted objects: every object promoted
655 // frees up its size in bytes from the top of the new space, and
656 // objects are at least one pointer in size.
657 Address new_space_front = new_space_.ToSpaceLow();
658 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000659
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000660 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000661 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000662 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000663
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000664 // Copy objects reachable from weak pointers.
665 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
666
667 // Copy objects reachable from the old generation. By definition,
668 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000669 IterateRSet(old_pointer_space_, &ScavengePointer);
670 IterateRSet(map_space_, &ScavengePointer);
671 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000672
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000673 do {
674 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000675
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000676 // The addresses new_space_front and new_space_.top() define a
677 // queue of unprocessed copied objects. Process them until the
678 // queue is empty.
679 while (new_space_front < new_space_.top()) {
680 HeapObject* object = HeapObject::FromAddress(new_space_front);
681 object->Iterate(&scavenge_visitor);
682 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000683 }
684
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000685 // Promote and process all the to-be-promoted objects.
686 while (!promotion_queue.is_empty()) {
687 HeapObject* source;
688 Map* map;
689 promotion_queue.remove(&source, &map);
690 // Copy the from-space object to its new location (given by the
691 // forwarding address) and fix its map.
692 HeapObject* target = source->map_word().ToForwardingAddress();
693 CopyBlock(reinterpret_cast<Object**>(target->address()),
694 reinterpret_cast<Object**>(source->address()),
695 source->SizeFromMap(map));
696 target->set_map(map);
697
698#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
699 // Update NewSpace stats if necessary.
700 RecordCopiedObject(target);
701#endif
702 // Visit the newly copied object for pointers to new space.
703 target->Iterate(&scavenge_visitor);
704 UpdateRSet(target);
705 }
706
707 // Take another spin if there are now unswept objects in new space
708 // (there are currently no more unswept promoted objects).
709 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000710
711 // Set age mark.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000712 new_space_.set_age_mark(new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713
714 LOG(ResourceEvent("scavenge", "end"));
715
716 gc_state_ = NOT_IN_GC;
717}
718
719
720void Heap::ClearRSetRange(Address start, int size_in_bytes) {
721 uint32_t start_bit;
722 Address start_word_address =
723 Page::ComputeRSetBitPosition(start, 0, &start_bit);
724 uint32_t end_bit;
725 Address end_word_address =
726 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
727 0,
728 &end_bit);
729
730 // We want to clear the bits in the starting word starting with the
731 // first bit, and in the ending word up to and including the last
732 // bit. Build a pair of bitmasks to do that.
733 uint32_t start_bitmask = start_bit - 1;
734 uint32_t end_bitmask = ~((end_bit << 1) - 1);
735
736 // If the start address and end address are the same, we mask that
737 // word once, otherwise mask the starting and ending word
738 // separately and all the ones in between.
739 if (start_word_address == end_word_address) {
740 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
741 } else {
742 Memory::uint32_at(start_word_address) &= start_bitmask;
743 Memory::uint32_at(end_word_address) &= end_bitmask;
744 start_word_address += kIntSize;
745 memset(start_word_address, 0, end_word_address - start_word_address);
746 }
747}
748
749
750class UpdateRSetVisitor: public ObjectVisitor {
751 public:
752
753 void VisitPointer(Object** p) {
754 UpdateRSet(p);
755 }
756
757 void VisitPointers(Object** start, Object** end) {
758 // Update a store into slots [start, end), used (a) to update remembered
759 // set when promoting a young object to old space or (b) to rebuild
760 // remembered sets after a mark-compact collection.
761 for (Object** p = start; p < end; p++) UpdateRSet(p);
762 }
763 private:
764
765 void UpdateRSet(Object** p) {
766 // The remembered set should not be set. It should be clear for objects
767 // newly copied to old space, and it is cleared before rebuilding in the
768 // mark-compact collector.
769 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
770 if (Heap::InNewSpace(*p)) {
771 Page::SetRSet(reinterpret_cast<Address>(p), 0);
772 }
773 }
774};
775
776
777int Heap::UpdateRSet(HeapObject* obj) {
778 ASSERT(!InNewSpace(obj));
779 // Special handling of fixed arrays to iterate the body based on the start
780 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
781 // will not work because Page::SetRSet needs to have the start of the
782 // object.
783 if (obj->IsFixedArray()) {
784 FixedArray* array = FixedArray::cast(obj);
785 int length = array->length();
786 for (int i = 0; i < length; i++) {
787 int offset = FixedArray::kHeaderSize + i * kPointerSize;
788 ASSERT(!Page::IsRSetSet(obj->address(), offset));
789 if (Heap::InNewSpace(array->get(i))) {
790 Page::SetRSet(obj->address(), offset);
791 }
792 }
793 } else if (!obj->IsCode()) {
794 // Skip code object, we know it does not contain inter-generational
795 // pointers.
796 UpdateRSetVisitor v;
797 obj->Iterate(&v);
798 }
799 return obj->Size();
800}
801
802
803void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000804 // By definition, we do not care about remembered set bits in code or data
805 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000806 map_space_->ClearRSet();
807 RebuildRSets(map_space_);
808
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000809 old_pointer_space_->ClearRSet();
810 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811
812 Heap::lo_space_->ClearRSet();
813 RebuildRSets(lo_space_);
814}
815
816
817void Heap::RebuildRSets(PagedSpace* space) {
818 HeapObjectIterator it(space);
819 while (it.has_next()) Heap::UpdateRSet(it.next());
820}
821
822
823void Heap::RebuildRSets(LargeObjectSpace* space) {
824 LargeObjectIterator it(space);
825 while (it.has_next()) Heap::UpdateRSet(it.next());
826}
827
828
829#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
830void Heap::RecordCopiedObject(HeapObject* obj) {
831 bool should_record = false;
832#ifdef DEBUG
833 should_record = FLAG_heap_stats;
834#endif
835#ifdef ENABLE_LOGGING_AND_PROFILING
836 should_record = should_record || FLAG_log_gc;
837#endif
838 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000839 if (new_space_.Contains(obj)) {
840 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000841 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000842 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000843 }
844 }
845}
846#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
847
848
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000849
850HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000851 HeapObject* target,
852 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000853 // Copy the content of source to target.
854 CopyBlock(reinterpret_cast<Object**>(target->address()),
855 reinterpret_cast<Object**>(source->address()),
856 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000857
kasper.lund7276f142008-07-30 08:49:36 +0000858 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000859 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000860
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000861#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000862 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 RecordCopiedObject(target);
864#endif
865
866 return target;
867}
868
869
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000870static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000871 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000872 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000873 InstanceType type = map->instance_type();
874 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
875 ASSERT(object->IsString() && !object->IsSymbol());
876 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000877}
878
879
880void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
881 ASSERT(InFromSpace(object));
882 MapWord first_word = object->map_word();
883 ASSERT(!first_word.IsForwardingAddress());
884
885 // Optimization: Bypass flattened ConsString objects.
886 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000887 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000888 *p = object;
889 // After patching *p we have to repeat the checks that object is in the
890 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000891 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000892 first_word = object->map_word();
893 if (first_word.IsForwardingAddress()) {
894 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000895 return;
896 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000897 }
898
kasper.lund7276f142008-07-30 08:49:36 +0000899 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000900 // We rely on live objects in new space to be at least two pointers,
901 // so we can store the from-space address and map pointer of promoted
902 // objects in the to space.
903 ASSERT(object_size >= 2 * kPointerSize);
904
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000905 // If the object should be promoted, we try to copy it to old space.
906 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000907 OldSpace* target_space = Heap::TargetSpace(object);
908 ASSERT(target_space == Heap::old_pointer_space_ ||
909 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000910 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000911 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000912 HeapObject* target = HeapObject::cast(result);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000913 if (target_space == Heap::old_pointer_space_) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000914 // Save the from-space object pointer and its map pointer at the
915 // top of the to space to be swept and copied later. Write the
916 // forwarding address over the map word of the from-space
917 // object.
918 promotion_queue.insert(object, first_word.ToMap());
919 object->set_map_word(MapWord::FromForwardingAddress(target));
920
921 // Give the space allocated for the result a proper map by
922 // treating it as a free list node (not linked into the free
923 // list).
924 FreeListNode* node = FreeListNode::FromAddress(target->address());
925 node->set_size(object_size);
926
927 *p = target;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000928 } else {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000929 // Objects promoted to the data space can be copied immediately
930 // and not revisited---we will never sweep that space for
931 // pointers and the copied objects do not contain pointers to
932 // new space objects.
933 *p = MigrateObject(object, target, object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000934#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000935 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000936 (*p)->Iterate(&v);
937#endif
938 }
939 return;
940 }
941 }
942
943 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000944 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000945 // Failed allocation at this point is utterly unexpected.
946 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000947 *p = MigrateObject(object, HeapObject::cast(result), object_size);
948}
949
950
951void Heap::ScavengePointer(HeapObject** p) {
952 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000953}
954
955
956Object* Heap::AllocatePartialMap(InstanceType instance_type,
957 int instance_size) {
958 Object* result = AllocateRawMap(Map::kSize);
959 if (result->IsFailure()) return result;
960
961 // Map::cast cannot be used due to uninitialized map field.
962 reinterpret_cast<Map*>(result)->set_map(meta_map());
963 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
964 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000965 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000966 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
967 return result;
968}
969
970
971Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
972 Object* result = AllocateRawMap(Map::kSize);
973 if (result->IsFailure()) return result;
974
975 Map* map = reinterpret_cast<Map*>(result);
976 map->set_map(meta_map());
977 map->set_instance_type(instance_type);
978 map->set_prototype(null_value());
979 map->set_constructor(null_value());
980 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000981 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000982 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983 map->set_code_cache(empty_fixed_array());
984 map->set_unused_property_fields(0);
985 map->set_bit_field(0);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +0000986 map->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000987 return map;
988}
989
990
991bool Heap::CreateInitialMaps() {
992 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
993 if (obj->IsFailure()) return false;
994
995 // Map::cast cannot be used due to uninitialized map field.
996 meta_map_ = reinterpret_cast<Map*>(obj);
997 meta_map()->set_map(meta_map());
998
999 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
1000 if (obj->IsFailure()) return false;
1001 fixed_array_map_ = Map::cast(obj);
1002
1003 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1004 if (obj->IsFailure()) return false;
1005 oddball_map_ = Map::cast(obj);
1006
1007 // Allocate the empty array
1008 obj = AllocateEmptyFixedArray();
1009 if (obj->IsFailure()) return false;
1010 empty_fixed_array_ = FixedArray::cast(obj);
1011
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001012 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 if (obj->IsFailure()) return false;
1014 null_value_ = obj;
1015
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001016 // Allocate the empty descriptor array. AllocateMap can now be used.
1017 obj = AllocateEmptyFixedArray();
1018 if (obj->IsFailure()) return false;
1019 // There is a check against empty_descriptor_array() in cast().
1020 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001021
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001022 // Fix the instance_descriptors for the existing maps.
1023 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 meta_map()->set_code_cache(empty_fixed_array());
1025
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001026 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001027 fixed_array_map()->set_code_cache(empty_fixed_array());
1028
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001029 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001030 oddball_map()->set_code_cache(empty_fixed_array());
1031
1032 // Fix prototype object for existing maps.
1033 meta_map()->set_prototype(null_value());
1034 meta_map()->set_constructor(null_value());
1035
1036 fixed_array_map()->set_prototype(null_value());
1037 fixed_array_map()->set_constructor(null_value());
1038 oddball_map()->set_prototype(null_value());
1039 oddball_map()->set_constructor(null_value());
1040
1041 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1042 if (obj->IsFailure()) return false;
1043 heap_number_map_ = Map::cast(obj);
1044
1045 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1046 if (obj->IsFailure()) return false;
1047 proxy_map_ = Map::cast(obj);
1048
1049#define ALLOCATE_STRING_MAP(type, size, name) \
1050 obj = AllocateMap(type, size); \
1051 if (obj->IsFailure()) return false; \
1052 name##_map_ = Map::cast(obj);
1053 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
1054#undef ALLOCATE_STRING_MAP
1055
ager@chromium.org7c537e22008-10-16 08:43:32 +00001056 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001057 if (obj->IsFailure()) return false;
1058 undetectable_short_string_map_ = Map::cast(obj);
1059 undetectable_short_string_map_->set_is_undetectable();
1060
ager@chromium.org7c537e22008-10-16 08:43:32 +00001061 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001062 if (obj->IsFailure()) return false;
1063 undetectable_medium_string_map_ = Map::cast(obj);
1064 undetectable_medium_string_map_->set_is_undetectable();
1065
ager@chromium.org7c537e22008-10-16 08:43:32 +00001066 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067 if (obj->IsFailure()) return false;
1068 undetectable_long_string_map_ = Map::cast(obj);
1069 undetectable_long_string_map_->set_is_undetectable();
1070
ager@chromium.org7c537e22008-10-16 08:43:32 +00001071 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001072 if (obj->IsFailure()) return false;
1073 undetectable_short_ascii_string_map_ = Map::cast(obj);
1074 undetectable_short_ascii_string_map_->set_is_undetectable();
1075
ager@chromium.org7c537e22008-10-16 08:43:32 +00001076 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001077 if (obj->IsFailure()) return false;
1078 undetectable_medium_ascii_string_map_ = Map::cast(obj);
1079 undetectable_medium_ascii_string_map_->set_is_undetectable();
1080
ager@chromium.org7c537e22008-10-16 08:43:32 +00001081 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001082 if (obj->IsFailure()) return false;
1083 undetectable_long_ascii_string_map_ = Map::cast(obj);
1084 undetectable_long_ascii_string_map_->set_is_undetectable();
1085
1086 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
1087 if (obj->IsFailure()) return false;
1088 byte_array_map_ = Map::cast(obj);
1089
1090 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1091 if (obj->IsFailure()) return false;
1092 code_map_ = Map::cast(obj);
1093
1094 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1095 if (obj->IsFailure()) return false;
1096 one_word_filler_map_ = Map::cast(obj);
1097
1098 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1099 if (obj->IsFailure()) return false;
1100 two_word_filler_map_ = Map::cast(obj);
1101
1102#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1103 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1104 if (obj->IsFailure()) return false; \
1105 name##_map_ = Map::cast(obj);
1106 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1107#undef ALLOCATE_STRUCT_MAP
1108
ager@chromium.org236ad962008-09-25 09:45:57 +00001109 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001110 if (obj->IsFailure()) return false;
1111 hash_table_map_ = Map::cast(obj);
1112
ager@chromium.org236ad962008-09-25 09:45:57 +00001113 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001114 if (obj->IsFailure()) return false;
1115 context_map_ = Map::cast(obj);
1116
ager@chromium.org236ad962008-09-25 09:45:57 +00001117 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001118 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001119 catch_context_map_ = Map::cast(obj);
1120
1121 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1122 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001123 global_context_map_ = Map::cast(obj);
1124
1125 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1126 if (obj->IsFailure()) return false;
1127 boilerplate_function_map_ = Map::cast(obj);
1128
1129 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1130 if (obj->IsFailure()) return false;
1131 shared_function_info_map_ = Map::cast(obj);
1132
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001133 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001134 return true;
1135}
1136
1137
1138Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1139 // Statically ensure that it is safe to allocate heap numbers in paged
1140 // spaces.
1141 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001142 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001143 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001144 if (result->IsFailure()) return result;
1145
1146 HeapObject::cast(result)->set_map(heap_number_map());
1147 HeapNumber::cast(result)->set_value(value);
1148 return result;
1149}
1150
1151
1152Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001153 // Use general version, if we're forced to always allocate.
1154 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001155 // This version of AllocateHeapNumber is optimized for
1156 // allocation in new space.
1157 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1158 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001159 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160 if (result->IsFailure()) return result;
1161 HeapObject::cast(result)->set_map(heap_number_map());
1162 HeapNumber::cast(result)->set_value(value);
1163 return result;
1164}
1165
1166
1167Object* Heap::CreateOddball(Map* map,
1168 const char* to_string,
1169 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001170 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001171 if (result->IsFailure()) return result;
1172 return Oddball::cast(result)->Initialize(to_string, to_number);
1173}
1174
1175
1176bool Heap::CreateApiObjects() {
1177 Object* obj;
1178
1179 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1180 if (obj->IsFailure()) return false;
1181 neander_map_ = Map::cast(obj);
1182
1183 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1184 if (obj->IsFailure()) return false;
1185 Object* elements = AllocateFixedArray(2);
1186 if (elements->IsFailure()) return false;
1187 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1188 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1189 message_listeners_ = JSObject::cast(obj);
1190
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001191 return true;
1192}
1193
1194void Heap::CreateFixedStubs() {
1195 // Here we create roots for fixed stubs. They are needed at GC
1196 // for cooking and uncooking (check out frames.cc).
1197 // The eliminates the need for doing dictionary lookup in the
1198 // stub cache for these stubs.
1199 HandleScope scope;
1200 {
1201 CEntryStub stub;
1202 c_entry_code_ = *stub.GetCode();
1203 }
1204 {
1205 CEntryDebugBreakStub stub;
1206 c_entry_debug_break_code_ = *stub.GetCode();
1207 }
1208 {
1209 JSEntryStub stub;
1210 js_entry_code_ = *stub.GetCode();
1211 }
1212 {
1213 JSConstructEntryStub stub;
1214 js_construct_entry_code_ = *stub.GetCode();
1215 }
1216}
1217
1218
1219bool Heap::CreateInitialObjects() {
1220 Object* obj;
1221
1222 // The -0 value must be set before NumberFromDouble works.
1223 obj = AllocateHeapNumber(-0.0, TENURED);
1224 if (obj->IsFailure()) return false;
1225 minus_zero_value_ = obj;
1226 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1227
1228 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1229 if (obj->IsFailure()) return false;
1230 nan_value_ = obj;
1231
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001232 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001233 if (obj->IsFailure()) return false;
1234 undefined_value_ = obj;
1235 ASSERT(!InNewSpace(undefined_value()));
1236
1237 // Allocate initial symbol table.
1238 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1239 if (obj->IsFailure()) return false;
1240 symbol_table_ = obj;
1241
1242 // Assign the print strings for oddballs after creating symboltable.
1243 Object* symbol = LookupAsciiSymbol("undefined");
1244 if (symbol->IsFailure()) return false;
1245 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1246 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1247
1248 // Assign the print strings for oddballs after creating symboltable.
1249 symbol = LookupAsciiSymbol("null");
1250 if (symbol->IsFailure()) return false;
1251 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1252 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1253
1254 // Allocate the null_value
1255 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1256 if (obj->IsFailure()) return false;
1257
1258 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1259 if (obj->IsFailure()) return false;
1260 true_value_ = obj;
1261
1262 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1263 if (obj->IsFailure()) return false;
1264 false_value_ = obj;
1265
1266 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1267 if (obj->IsFailure()) return false;
1268 the_hole_value_ = obj;
1269
1270 // Allocate the empty string.
1271 obj = AllocateRawAsciiString(0, TENURED);
1272 if (obj->IsFailure()) return false;
1273 empty_string_ = String::cast(obj);
1274
1275#define SYMBOL_INITIALIZE(name, string) \
1276 obj = LookupAsciiSymbol(string); \
1277 if (obj->IsFailure()) return false; \
1278 (name##_) = String::cast(obj);
1279 SYMBOL_LIST(SYMBOL_INITIALIZE)
1280#undef SYMBOL_INITIALIZE
1281
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001282 // Allocate the hidden symbol which is used to identify the hidden properties
1283 // in JSObjects. The hash code has a special value so that it will not match
1284 // the empty string when searching for the property. It cannot be part of the
1285 // SYMBOL_LIST because it needs to be allocated manually with the special
1286 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1287 // that it will always be at the first entry in property descriptors.
1288 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1289 if (obj->IsFailure()) return false;
1290 hidden_symbol_ = String::cast(obj);
1291
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001292 // Allocate the proxy for __proto__.
1293 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1294 if (obj->IsFailure()) return false;
1295 prototype_accessors_ = Proxy::cast(obj);
1296
1297 // Allocate the code_stubs dictionary.
1298 obj = Dictionary::Allocate(4);
1299 if (obj->IsFailure()) return false;
1300 code_stubs_ = Dictionary::cast(obj);
1301
1302 // Allocate the non_monomorphic_cache used in stub-cache.cc
1303 obj = Dictionary::Allocate(4);
1304 if (obj->IsFailure()) return false;
1305 non_monomorphic_cache_ = Dictionary::cast(obj);
1306
1307 CreateFixedStubs();
1308
1309 // Allocate the number->string conversion cache
1310 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1311 if (obj->IsFailure()) return false;
1312 number_string_cache_ = FixedArray::cast(obj);
1313
1314 // Allocate cache for single character strings.
1315 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1316 if (obj->IsFailure()) return false;
1317 single_character_string_cache_ = FixedArray::cast(obj);
1318
1319 // Allocate cache for external strings pointing to native source code.
1320 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1321 if (obj->IsFailure()) return false;
1322 natives_source_cache_ = FixedArray::cast(obj);
1323
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001324 // Handling of script id generation is in Factory::NewScript.
1325 last_script_id_ = undefined_value();
1326
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001327 // Initialize keyed lookup cache.
1328 ClearKeyedLookupCache();
1329
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001330 // Initialize compilation cache.
1331 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001332
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001333 return true;
1334}
1335
1336
1337static inline int double_get_hash(double d) {
1338 DoubleRepresentation rep(d);
1339 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1340 (Heap::kNumberStringCacheSize - 1));
1341}
1342
1343
1344static inline int smi_get_hash(Smi* smi) {
1345 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1346}
1347
1348
1349
1350Object* Heap::GetNumberStringCache(Object* number) {
1351 int hash;
1352 if (number->IsSmi()) {
1353 hash = smi_get_hash(Smi::cast(number));
1354 } else {
1355 hash = double_get_hash(number->Number());
1356 }
1357 Object* key = number_string_cache_->get(hash * 2);
1358 if (key == number) {
1359 return String::cast(number_string_cache_->get(hash * 2 + 1));
1360 } else if (key->IsHeapNumber() &&
1361 number->IsHeapNumber() &&
1362 key->Number() == number->Number()) {
1363 return String::cast(number_string_cache_->get(hash * 2 + 1));
1364 }
1365 return undefined_value();
1366}
1367
1368
1369void Heap::SetNumberStringCache(Object* number, String* string) {
1370 int hash;
1371 if (number->IsSmi()) {
1372 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001373 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374 } else {
1375 hash = double_get_hash(number->Number());
1376 number_string_cache_->set(hash * 2, number);
1377 }
1378 number_string_cache_->set(hash * 2 + 1, string);
1379}
1380
1381
1382Object* Heap::SmiOrNumberFromDouble(double value,
1383 bool new_object,
1384 PretenureFlag pretenure) {
1385 // We need to distinguish the minus zero value and this cannot be
1386 // done after conversion to int. Doing this by comparing bit
1387 // patterns is faster than using fpclassify() et al.
1388 static const DoubleRepresentation plus_zero(0.0);
1389 static const DoubleRepresentation minus_zero(-0.0);
1390 static const DoubleRepresentation nan(OS::nan_value());
1391 ASSERT(minus_zero_value_ != NULL);
1392 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1393
1394 DoubleRepresentation rep(value);
1395 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1396 if (rep.bits == minus_zero.bits) {
1397 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1398 : minus_zero_value_;
1399 }
1400 if (rep.bits == nan.bits) {
1401 return new_object
1402 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1403 : nan_value_;
1404 }
1405
1406 // Try to represent the value as a tagged small integer.
1407 int int_value = FastD2I(value);
1408 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1409 return Smi::FromInt(int_value);
1410 }
1411
1412 // Materialize the value in the heap.
1413 return AllocateHeapNumber(value, pretenure);
1414}
1415
1416
1417Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1418 return SmiOrNumberFromDouble(value,
1419 true /* number object must be new */,
1420 pretenure);
1421}
1422
1423
1424Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1425 return SmiOrNumberFromDouble(value,
1426 false /* use preallocated NaN, -0.0 */,
1427 pretenure);
1428}
1429
1430
1431Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1432 // Statically ensure that it is safe to allocate proxies in paged spaces.
1433 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001434 AllocationSpace space =
1435 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001436 Object* result = Allocate(proxy_map(), space);
1437 if (result->IsFailure()) return result;
1438
1439 Proxy::cast(result)->set_proxy(proxy);
1440 return result;
1441}
1442
1443
1444Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1445 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1446 if (result->IsFailure()) return result;
1447
1448 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1449 share->set_name(name);
1450 Code* illegal = Builtins::builtin(Builtins::Illegal);
1451 share->set_code(illegal);
1452 share->set_expected_nof_properties(0);
1453 share->set_length(0);
1454 share->set_formal_parameter_count(0);
1455 share->set_instance_class_name(Object_symbol());
1456 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001457 share->set_script(undefined_value());
1458 share->set_start_position_and_type(0);
1459 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001460 share->set_inferred_name(empty_string());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001461 return result;
1462}
1463
1464
ager@chromium.org870a0b62008-11-04 11:43:05 +00001465Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001466 String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001467 int first_length = first->length();
1468 int second_length = second->length();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001469 int length = first_length + second_length;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001470 bool is_ascii = first->IsAsciiRepresentation()
1471 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001472
1473 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001474 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001475 ASSERT(first->IsFlat());
1476 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001477 if (is_ascii) {
1478 Object* result = AllocateRawAsciiString(length);
1479 if (result->IsFailure()) return result;
1480 // Copy the characters into the new object.
1481 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001482 String::WriteToFlat(first, dest, 0, first_length);
1483 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001484 return result;
1485 } else {
1486 Object* result = AllocateRawTwoByteString(length);
1487 if (result->IsFailure()) return result;
1488 // Copy the characters into the new object.
1489 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001490 String::WriteToFlat(first, dest, 0, first_length);
1491 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001492 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001493 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494 }
1495
1496 Map* map;
1497 if (length <= String::kMaxShortStringSize) {
1498 map = is_ascii ? short_cons_ascii_string_map()
1499 : short_cons_string_map();
1500 } else if (length <= String::kMaxMediumStringSize) {
1501 map = is_ascii ? medium_cons_ascii_string_map()
1502 : medium_cons_string_map();
1503 } else {
1504 map = is_ascii ? long_cons_ascii_string_map()
1505 : long_cons_string_map();
1506 }
1507
1508 Object* result = Allocate(map, NEW_SPACE);
1509 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001510 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001511 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001512 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1513 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001514 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001515 return result;
1516}
1517
1518
ager@chromium.org870a0b62008-11-04 11:43:05 +00001519Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001520 int start,
1521 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522 int length = end - start;
1523
1524 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001525 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001526 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001527 }
1528
1529 Map* map;
1530 if (length <= String::kMaxShortStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001531 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001532 short_sliced_ascii_string_map() :
1533 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001534 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001535 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001536 medium_sliced_ascii_string_map() :
1537 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001538 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001539 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001540 long_sliced_ascii_string_map() :
1541 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001542 }
1543
1544 Object* result = Allocate(map, NEW_SPACE);
1545 if (result->IsFailure()) return result;
1546
1547 SlicedString* sliced_string = SlicedString::cast(result);
1548 sliced_string->set_buffer(buffer);
1549 sliced_string->set_start(start);
1550 sliced_string->set_length(length);
1551
1552 return result;
1553}
1554
1555
ager@chromium.org870a0b62008-11-04 11:43:05 +00001556Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001557 int start,
1558 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559 int length = end - start;
1560
ager@chromium.org7c537e22008-10-16 08:43:32 +00001561 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001562 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001563 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001564 }
1565
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001567 if (!buffer->IsFlat()) {
1568 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001569 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570
ager@chromium.org5ec48922009-05-05 07:25:34 +00001571 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001572 ? AllocateRawAsciiString(length)
1573 : AllocateRawTwoByteString(length);
1574 if (result->IsFailure()) return result;
1575
1576 // Copy the characters into the new object.
1577 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001578 StringHasher hasher(length);
1579 int i = 0;
1580 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001581 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001582 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001583 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001585 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001586 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001587 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001588 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001589 }
1590 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001591 return result;
1592}
1593
1594
1595Object* Heap::AllocateExternalStringFromAscii(
1596 ExternalAsciiString::Resource* resource) {
1597 Map* map;
1598 int length = resource->length();
1599 if (length <= String::kMaxShortStringSize) {
1600 map = short_external_ascii_string_map();
1601 } else if (length <= String::kMaxMediumStringSize) {
1602 map = medium_external_ascii_string_map();
1603 } else {
1604 map = long_external_ascii_string_map();
1605 }
1606
1607 Object* result = Allocate(map, NEW_SPACE);
1608 if (result->IsFailure()) return result;
1609
1610 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1611 external_string->set_length(length);
1612 external_string->set_resource(resource);
1613
1614 return result;
1615}
1616
1617
1618Object* Heap::AllocateExternalStringFromTwoByte(
1619 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001620 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621
ager@chromium.org6f10e412009-02-13 10:11:16 +00001622 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623 Object* result = Allocate(map, NEW_SPACE);
1624 if (result->IsFailure()) return result;
1625
1626 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1627 external_string->set_length(length);
1628 external_string->set_resource(resource);
1629
1630 return result;
1631}
1632
1633
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001634Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001635 if (code <= String::kMaxAsciiCharCode) {
1636 Object* value = Heap::single_character_string_cache()->get(code);
1637 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001638
1639 char buffer[1];
1640 buffer[0] = static_cast<char>(code);
1641 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1642
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001644 Heap::single_character_string_cache()->set(code, result);
1645 return result;
1646 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001647
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001648 Object* result = Heap::AllocateRawTwoByteString(1);
1649 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001650 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001651 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001652 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001653}
1654
1655
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001656Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1657 if (pretenure == NOT_TENURED) {
1658 return AllocateByteArray(length);
1659 }
1660 int size = ByteArray::SizeFor(length);
1661 AllocationSpace space =
1662 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1663
1664 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1665
1666 if (result->IsFailure()) return result;
1667
1668 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1669 reinterpret_cast<Array*>(result)->set_length(length);
1670 return result;
1671}
1672
1673
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001674Object* Heap::AllocateByteArray(int length) {
1675 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001676 AllocationSpace space =
1677 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001678
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001679 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001680
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001681 if (result->IsFailure()) return result;
1682
1683 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1684 reinterpret_cast<Array*>(result)->set_length(length);
1685 return result;
1686}
1687
1688
ager@chromium.org6f10e412009-02-13 10:11:16 +00001689void Heap::CreateFillerObjectAt(Address addr, int size) {
1690 if (size == 0) return;
1691 HeapObject* filler = HeapObject::FromAddress(addr);
1692 if (size == kPointerSize) {
1693 filler->set_map(Heap::one_word_filler_map());
1694 } else {
1695 filler->set_map(Heap::byte_array_map());
1696 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1697 }
1698}
1699
1700
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001701Object* Heap::CreateCode(const CodeDesc& desc,
1702 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001703 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001704 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705 // Compute size
1706 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1707 int sinfo_size = 0;
1708 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1709 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001710 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001711 Object* result;
1712 if (obj_size > MaxHeapObjectSize()) {
1713 result = lo_space_->AllocateRawCode(obj_size);
1714 } else {
1715 result = code_space_->AllocateRaw(obj_size);
1716 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001717
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001718 if (result->IsFailure()) return result;
1719
1720 // Initialize the object
1721 HeapObject::cast(result)->set_map(code_map());
1722 Code* code = Code::cast(result);
1723 code->set_instruction_size(desc.instr_size);
1724 code->set_relocation_size(desc.reloc_size);
1725 code->set_sinfo_size(sinfo_size);
1726 code->set_flags(flags);
1727 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001728 // Allow self references to created code object by patching the handle to
1729 // point to the newly allocated Code object.
1730 if (!self_reference.is_null()) {
1731 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001732 }
1733 // Migrate generated code.
1734 // The generated code can contain Object** values (typically from handles)
1735 // that are dereferenced during the copy to point directly to the actual heap
1736 // objects. These pointers can include references to the code object itself,
1737 // through the self_reference parameter.
1738 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001739 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001740 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001741
1742#ifdef DEBUG
1743 code->Verify();
1744#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001745 return code;
1746}
1747
1748
1749Object* Heap::CopyCode(Code* code) {
1750 // Allocate an object the same size as the code object.
1751 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001752 Object* result;
1753 if (obj_size > MaxHeapObjectSize()) {
1754 result = lo_space_->AllocateRawCode(obj_size);
1755 } else {
1756 result = code_space_->AllocateRaw(obj_size);
1757 }
1758
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001759 if (result->IsFailure()) return result;
1760
1761 // Copy code object.
1762 Address old_addr = code->address();
1763 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001764 CopyBlock(reinterpret_cast<Object**>(new_addr),
1765 reinterpret_cast<Object**>(old_addr),
1766 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001767 // Relocate the copy.
1768 Code* new_code = Code::cast(result);
1769 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001770 return new_code;
1771}
1772
1773
1774Object* Heap::Allocate(Map* map, AllocationSpace space) {
1775 ASSERT(gc_state_ == NOT_IN_GC);
1776 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001777 Object* result = AllocateRaw(map->instance_size(),
1778 space,
1779 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001780 if (result->IsFailure()) return result;
1781 HeapObject::cast(result)->set_map(map);
1782 return result;
1783}
1784
1785
1786Object* Heap::InitializeFunction(JSFunction* function,
1787 SharedFunctionInfo* shared,
1788 Object* prototype) {
1789 ASSERT(!prototype->IsMap());
1790 function->initialize_properties();
1791 function->initialize_elements();
1792 function->set_shared(shared);
1793 function->set_prototype_or_initial_map(prototype);
1794 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001795 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001796 return function;
1797}
1798
1799
1800Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001801 // Allocate the prototype. Make sure to use the object function
1802 // from the function's context, since the function can be from a
1803 // different context.
1804 JSFunction* object_function =
1805 function->context()->global_context()->object_function();
1806 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001807 if (prototype->IsFailure()) return prototype;
1808 // When creating the prototype for the function we must set its
1809 // constructor to the function.
1810 Object* result =
1811 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1812 function,
1813 DONT_ENUM);
1814 if (result->IsFailure()) return result;
1815 return prototype;
1816}
1817
1818
1819Object* Heap::AllocateFunction(Map* function_map,
1820 SharedFunctionInfo* shared,
1821 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001822 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001823 if (result->IsFailure()) return result;
1824 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1825}
1826
1827
1828Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001829 // To get fast allocation and map sharing for arguments objects we
1830 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001831
1832 // This calls Copy directly rather than using Heap::AllocateRaw so we
1833 // duplicate the check here.
1834 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1835
1836 JSObject* boilerplate =
1837 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001838
1839 // Make the clone.
1840 Map* map = boilerplate->map();
1841 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001842 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001843 if (result->IsFailure()) return result;
1844
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001845 // Copy the content. The arguments boilerplate doesn't have any
1846 // fields that point to new space so it's safe to skip the write
1847 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001848 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1849 reinterpret_cast<Object**>(boilerplate->address()),
1850 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001851
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001852 // Set the two properties.
1853 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001854 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001855 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1856 Smi::FromInt(length),
1857 SKIP_WRITE_BARRIER);
1858
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 // Check the state of the object
1860 ASSERT(JSObject::cast(result)->HasFastProperties());
1861 ASSERT(JSObject::cast(result)->HasFastElements());
1862
1863 return result;
1864}
1865
1866
1867Object* Heap::AllocateInitialMap(JSFunction* fun) {
1868 ASSERT(!fun->has_initial_map());
1869
ager@chromium.org7c537e22008-10-16 08:43:32 +00001870 // First create a new map with the expected number of properties being
1871 // allocated in-object.
1872 int expected_nof_properties = fun->shared()->expected_nof_properties();
1873 int instance_size = JSObject::kHeaderSize +
1874 expected_nof_properties * kPointerSize;
1875 if (instance_size > JSObject::kMaxInstanceSize) {
1876 instance_size = JSObject::kMaxInstanceSize;
1877 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1878 kPointerSize;
1879 }
1880 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001881 if (map_obj->IsFailure()) return map_obj;
1882
1883 // Fetch or allocate prototype.
1884 Object* prototype;
1885 if (fun->has_instance_prototype()) {
1886 prototype = fun->instance_prototype();
1887 } else {
1888 prototype = AllocateFunctionPrototype(fun);
1889 if (prototype->IsFailure()) return prototype;
1890 }
1891 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001892 map->set_inobject_properties(expected_nof_properties);
1893 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001894 map->set_prototype(prototype);
1895 return map;
1896}
1897
1898
1899void Heap::InitializeJSObjectFromMap(JSObject* obj,
1900 FixedArray* properties,
1901 Map* map) {
1902 obj->set_properties(properties);
1903 obj->initialize_elements();
1904 // TODO(1240798): Initialize the object's body using valid initial values
1905 // according to the object's initial map. For example, if the map's
1906 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1907 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1908 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1909 // verification code has to cope with (temporarily) invalid objects. See
1910 // for example, JSArray::JSArrayVerify).
1911 obj->InitializeBody(map->instance_size());
1912}
1913
1914
1915Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1916 // JSFunctions should be allocated using AllocateFunction to be
1917 // properly initialized.
1918 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1919
1920 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001921 int prop_size = map->unused_property_fields() - map->inobject_properties();
1922 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001923 if (properties->IsFailure()) return properties;
1924
1925 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001926 AllocationSpace space =
1927 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001928 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1929 Object* obj = Allocate(map, space);
1930 if (obj->IsFailure()) return obj;
1931
1932 // Initialize the JSObject.
1933 InitializeJSObjectFromMap(JSObject::cast(obj),
1934 FixedArray::cast(properties),
1935 map);
1936 return obj;
1937}
1938
1939
1940Object* Heap::AllocateJSObject(JSFunction* constructor,
1941 PretenureFlag pretenure) {
1942 // Allocate the 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 // Allocate the object based on the constructors initial map.
1950 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1951}
1952
1953
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001954Object* Heap::CopyJSObject(JSObject* source) {
1955 // Never used to copy functions. If functions need to be copied we
1956 // have to be careful to clear the literals array.
1957 ASSERT(!source->IsJSFunction());
1958
1959 // Make the clone.
1960 Map* map = source->map();
1961 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001962 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001963
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001964 // If we're forced to always allocate, we use the general allocation
1965 // functions which may leave us with an object in old space.
1966 if (always_allocate()) {
1967 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1968 if (clone->IsFailure()) return clone;
1969 Address clone_address = HeapObject::cast(clone)->address();
1970 CopyBlock(reinterpret_cast<Object**>(clone_address),
1971 reinterpret_cast<Object**>(source->address()),
1972 object_size);
1973 // Update write barrier for all fields that lie beyond the header.
1974 for (int offset = JSObject::kHeaderSize;
1975 offset < object_size;
1976 offset += kPointerSize) {
1977 RecordWrite(clone_address, offset);
1978 }
1979 } else {
1980 clone = new_space_.AllocateRaw(object_size);
1981 if (clone->IsFailure()) return clone;
1982 ASSERT(Heap::InNewSpace(clone));
1983 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00001984 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001985 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1986 reinterpret_cast<Object**>(source->address()),
1987 object_size);
1988 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001989
1990 FixedArray* elements = FixedArray::cast(source->elements());
1991 FixedArray* properties = FixedArray::cast(source->properties());
1992 // Update elements if necessary.
1993 if (elements->length()> 0) {
1994 Object* elem = CopyFixedArray(elements);
1995 if (elem->IsFailure()) return elem;
1996 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1997 }
1998 // Update properties if necessary.
1999 if (properties->length() > 0) {
2000 Object* prop = CopyFixedArray(properties);
2001 if (prop->IsFailure()) return prop;
2002 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2003 }
2004 // Return the new clone.
2005 return clone;
2006}
2007
2008
2009Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2010 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002011 // Allocate initial map if absent.
2012 if (!constructor->has_initial_map()) {
2013 Object* initial_map = AllocateInitialMap(constructor);
2014 if (initial_map->IsFailure()) return initial_map;
2015 constructor->set_initial_map(Map::cast(initial_map));
2016 Map::cast(initial_map)->set_constructor(constructor);
2017 }
2018
2019 Map* map = constructor->initial_map();
2020
2021 // Check that the already allocated object has the same size as
2022 // objects allocated using the constructor.
2023 ASSERT(map->instance_size() == object->map()->instance_size());
2024
2025 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002026 int prop_size = map->unused_property_fields() - map->inobject_properties();
2027 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002028 if (properties->IsFailure()) return properties;
2029
2030 // Reset the map for the object.
2031 object->set_map(constructor->initial_map());
2032
2033 // Reinitialize the object from the constructor map.
2034 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2035 return object;
2036}
2037
2038
2039Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2040 PretenureFlag pretenure) {
2041 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2042 if (result->IsFailure()) return result;
2043
2044 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002045 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002046 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002047 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002048 }
2049 return result;
2050}
2051
2052
2053Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2054 PretenureFlag pretenure) {
2055 // Count the number of characters in the UTF-8 string and check if
2056 // it is an ASCII string.
2057 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2058 decoder->Reset(string.start(), string.length());
2059 int chars = 0;
2060 bool is_ascii = true;
2061 while (decoder->has_more()) {
2062 uc32 r = decoder->GetNext();
2063 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2064 chars++;
2065 }
2066
2067 // If the string is ascii, we do not need to convert the characters
2068 // since UTF8 is backwards compatible with ascii.
2069 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2070
2071 Object* result = AllocateRawTwoByteString(chars, pretenure);
2072 if (result->IsFailure()) return result;
2073
2074 // Convert and copy the characters into the new object.
2075 String* string_result = String::cast(result);
2076 decoder->Reset(string.start(), string.length());
2077 for (int i = 0; i < chars; i++) {
2078 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002079 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080 }
2081 return result;
2082}
2083
2084
2085Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2086 PretenureFlag pretenure) {
2087 // Check if the string is an ASCII string.
2088 int i = 0;
2089 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2090
2091 Object* result;
2092 if (i == string.length()) { // It's an ASCII string.
2093 result = AllocateRawAsciiString(string.length(), pretenure);
2094 } else { // It's not an ASCII string.
2095 result = AllocateRawTwoByteString(string.length(), pretenure);
2096 }
2097 if (result->IsFailure()) return result;
2098
2099 // Copy the characters into the new object, which may be either ASCII or
2100 // UTF-16.
2101 String* string_result = String::cast(result);
2102 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002103 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002104 }
2105 return result;
2106}
2107
2108
2109Map* Heap::SymbolMapForString(String* string) {
2110 // If the string is in new space it cannot be used as a symbol.
2111 if (InNewSpace(string)) return NULL;
2112
2113 // Find the corresponding symbol map for strings.
2114 Map* map = string->map();
2115
2116 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2117 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2118 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2119
2120 if (map == short_string_map()) return short_symbol_map();
2121 if (map == medium_string_map()) return medium_symbol_map();
2122 if (map == long_string_map()) return long_symbol_map();
2123
2124 if (map == short_cons_string_map()) return short_cons_symbol_map();
2125 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2126 if (map == long_cons_string_map()) return long_cons_symbol_map();
2127
2128 if (map == short_cons_ascii_string_map()) {
2129 return short_cons_ascii_symbol_map();
2130 }
2131 if (map == medium_cons_ascii_string_map()) {
2132 return medium_cons_ascii_symbol_map();
2133 }
2134 if (map == long_cons_ascii_string_map()) {
2135 return long_cons_ascii_symbol_map();
2136 }
2137
2138 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002139 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2140 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002141
2142 if (map == short_sliced_ascii_string_map()) {
2143 return short_sliced_ascii_symbol_map();
2144 }
2145 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002146 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002147 }
2148 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002149 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002150 }
2151
ager@chromium.org6f10e412009-02-13 10:11:16 +00002152 if (map == short_external_string_map()) {
2153 return short_external_symbol_map();
2154 }
2155 if (map == medium_external_string_map()) {
2156 return medium_external_symbol_map();
2157 }
2158 if (map == long_external_string_map()) {
2159 return long_external_symbol_map();
2160 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002161
2162 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002163 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002164 }
2165 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002166 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002167 }
2168 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002169 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002170 }
2171
2172 // No match found.
2173 return NULL;
2174}
2175
2176
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002177Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2178 int chars,
2179 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002180 // Ensure the chars matches the number of characters in the buffer.
2181 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2182 // Determine whether the string is ascii.
2183 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002184 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002185 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2186 }
2187 buffer->Rewind();
2188
2189 // Compute map and object size.
2190 int size;
2191 Map* map;
2192
2193 if (is_ascii) {
2194 if (chars <= String::kMaxShortStringSize) {
2195 map = short_ascii_symbol_map();
2196 } else if (chars <= String::kMaxMediumStringSize) {
2197 map = medium_ascii_symbol_map();
2198 } else {
2199 map = long_ascii_symbol_map();
2200 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002201 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002202 } else {
2203 if (chars <= String::kMaxShortStringSize) {
2204 map = short_symbol_map();
2205 } else if (chars <= String::kMaxMediumStringSize) {
2206 map = medium_symbol_map();
2207 } else {
2208 map = long_symbol_map();
2209 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002210 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002211 }
2212
2213 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002214 AllocationSpace space =
2215 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002216 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002217 if (result->IsFailure()) return result;
2218
2219 reinterpret_cast<HeapObject*>(result)->set_map(map);
2220 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002221 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002222 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002223
ager@chromium.org870a0b62008-11-04 11:43:05 +00002224 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002225
2226 // Fill in the characters.
2227 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002228 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002229 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002230 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002231}
2232
2233
2234Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002235 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002236 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002237 if (size > MaxHeapObjectSize()) {
2238 space = LO_SPACE;
2239 }
2240
2241 // Use AllocateRaw rather than Allocate because the object's size cannot be
2242 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002243 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002244 if (result->IsFailure()) return result;
2245
2246 // Determine the map based on the string's length.
2247 Map* map;
2248 if (length <= String::kMaxShortStringSize) {
2249 map = short_ascii_string_map();
2250 } else if (length <= String::kMaxMediumStringSize) {
2251 map = medium_ascii_string_map();
2252 } else {
2253 map = long_ascii_string_map();
2254 }
2255
2256 // Partially initialize the object.
2257 HeapObject::cast(result)->set_map(map);
2258 String::cast(result)->set_length(length);
2259 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2260 return result;
2261}
2262
2263
2264Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002265 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002266 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002267 if (size > MaxHeapObjectSize()) {
2268 space = LO_SPACE;
2269 }
2270
2271 // Use AllocateRaw rather than Allocate because the object's size cannot be
2272 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002273 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002274 if (result->IsFailure()) return result;
2275
2276 // Determine the map based on the string's length.
2277 Map* map;
2278 if (length <= String::kMaxShortStringSize) {
2279 map = short_string_map();
2280 } else if (length <= String::kMaxMediumStringSize) {
2281 map = medium_string_map();
2282 } else {
2283 map = long_string_map();
2284 }
2285
2286 // Partially initialize the object.
2287 HeapObject::cast(result)->set_map(map);
2288 String::cast(result)->set_length(length);
2289 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2290 return result;
2291}
2292
2293
2294Object* Heap::AllocateEmptyFixedArray() {
2295 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002296 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002297 if (result->IsFailure()) return result;
2298 // Initialize the object.
2299 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2300 reinterpret_cast<Array*>(result)->set_length(0);
2301 return result;
2302}
2303
2304
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002305Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002306 // Use the general function if we're forced to always allocate.
2307 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002308 // Allocate the raw data for a fixed array.
2309 int size = FixedArray::SizeFor(length);
2310 return (size > MaxHeapObjectSize())
2311 ? lo_space_->AllocateRawFixedArray(size)
2312 : new_space_.AllocateRaw(size);
2313}
2314
2315
2316Object* Heap::CopyFixedArray(FixedArray* src) {
2317 int len = src->length();
2318 Object* obj = AllocateRawFixedArray(len);
2319 if (obj->IsFailure()) return obj;
2320 if (Heap::InNewSpace(obj)) {
2321 HeapObject* dst = HeapObject::cast(obj);
2322 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2323 reinterpret_cast<Object**>(src->address()),
2324 FixedArray::SizeFor(len));
2325 return obj;
2326 }
2327 HeapObject::cast(obj)->set_map(src->map());
2328 FixedArray* result = FixedArray::cast(obj);
2329 result->set_length(len);
2330 // Copy the content
2331 WriteBarrierMode mode = result->GetWriteBarrierMode();
2332 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2333 return result;
2334}
2335
2336
2337Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002338 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002339 Object* result = AllocateRawFixedArray(length);
2340 if (!result->IsFailure()) {
2341 // Initialize header.
2342 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2343 FixedArray* array = FixedArray::cast(result);
2344 array->set_length(length);
2345 Object* value = undefined_value();
2346 // Initialize body.
2347 for (int index = 0; index < length; index++) {
2348 array->set(index, value, SKIP_WRITE_BARRIER);
2349 }
2350 }
2351 return result;
2352}
2353
2354
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002355Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2356 ASSERT(empty_fixed_array()->IsFixedArray());
2357 if (length == 0) return empty_fixed_array();
2358
2359 int size = FixedArray::SizeFor(length);
2360 Object* result;
2361 if (size > MaxHeapObjectSize()) {
2362 result = lo_space_->AllocateRawFixedArray(size);
2363 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002364 AllocationSpace space =
2365 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002366 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002367 }
2368 if (result->IsFailure()) return result;
2369
2370 // Initialize the object.
2371 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2372 FixedArray* array = FixedArray::cast(result);
2373 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002374 Object* value = undefined_value();
2375 for (int index = 0; index < length; index++) {
2376 array->set(index, value, SKIP_WRITE_BARRIER);
2377 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002378 return array;
2379}
2380
2381
2382Object* Heap::AllocateFixedArrayWithHoles(int length) {
2383 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002384 Object* result = AllocateRawFixedArray(length);
2385 if (!result->IsFailure()) {
2386 // Initialize header.
2387 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2388 FixedArray* array = FixedArray::cast(result);
2389 array->set_length(length);
2390 // Initialize body.
2391 Object* value = the_hole_value();
2392 for (int index = 0; index < length; index++) {
2393 array->set(index, value, SKIP_WRITE_BARRIER);
2394 }
2395 }
2396 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002397}
2398
2399
2400Object* Heap::AllocateHashTable(int length) {
2401 Object* result = Heap::AllocateFixedArray(length);
2402 if (result->IsFailure()) return result;
2403 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2404 ASSERT(result->IsDictionary());
2405 return result;
2406}
2407
2408
2409Object* Heap::AllocateGlobalContext() {
2410 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2411 if (result->IsFailure()) return result;
2412 Context* context = reinterpret_cast<Context*>(result);
2413 context->set_map(global_context_map());
2414 ASSERT(context->IsGlobalContext());
2415 ASSERT(result->IsContext());
2416 return result;
2417}
2418
2419
2420Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2421 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2422 Object* result = Heap::AllocateFixedArray(length);
2423 if (result->IsFailure()) return result;
2424 Context* context = reinterpret_cast<Context*>(result);
2425 context->set_map(context_map());
2426 context->set_closure(function);
2427 context->set_fcontext(context);
2428 context->set_previous(NULL);
2429 context->set_extension(NULL);
2430 context->set_global(function->context()->global());
2431 ASSERT(!context->IsGlobalContext());
2432 ASSERT(context->is_function_context());
2433 ASSERT(result->IsContext());
2434 return result;
2435}
2436
2437
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002438Object* Heap::AllocateWithContext(Context* previous,
2439 JSObject* extension,
2440 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002441 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2442 if (result->IsFailure()) return result;
2443 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002444 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002445 context->set_closure(previous->closure());
2446 context->set_fcontext(previous->fcontext());
2447 context->set_previous(previous);
2448 context->set_extension(extension);
2449 context->set_global(previous->global());
2450 ASSERT(!context->IsGlobalContext());
2451 ASSERT(!context->is_function_context());
2452 ASSERT(result->IsContext());
2453 return result;
2454}
2455
2456
2457Object* Heap::AllocateStruct(InstanceType type) {
2458 Map* map;
2459 switch (type) {
2460#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2461STRUCT_LIST(MAKE_CASE)
2462#undef MAKE_CASE
2463 default:
2464 UNREACHABLE();
2465 return Failure::InternalError();
2466 }
2467 int size = map->instance_size();
2468 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002469 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002470 Object* result = Heap::Allocate(map, space);
2471 if (result->IsFailure()) return result;
2472 Struct::cast(result)->InitializeBody(size);
2473 return result;
2474}
2475
2476
2477#ifdef DEBUG
2478
2479void Heap::Print() {
2480 if (!HasBeenSetup()) return;
2481 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002482 AllSpaces spaces;
2483 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002484}
2485
2486
2487void Heap::ReportCodeStatistics(const char* title) {
2488 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2489 PagedSpace::ResetCodeStatistics();
2490 // We do not look for code in new space, map space, or old space. If code
2491 // somehow ends up in those spaces, we would miss it here.
2492 code_space_->CollectCodeStatistics();
2493 lo_space_->CollectCodeStatistics();
2494 PagedSpace::ReportCodeStatistics();
2495}
2496
2497
2498// This function expects that NewSpace's allocated objects histogram is
2499// populated (via a call to CollectStatistics or else as a side effect of a
2500// just-completed scavenge collection).
2501void Heap::ReportHeapStatistics(const char* title) {
2502 USE(title);
2503 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2504 title, gc_count_);
2505 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002506 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2507 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002508
2509 PrintF("\n");
2510 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2511 GlobalHandles::PrintStats();
2512 PrintF("\n");
2513
2514 PrintF("Heap statistics : ");
2515 MemoryAllocator::ReportStatistics();
2516 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002517 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002518 PrintF("Old pointer space : ");
2519 old_pointer_space_->ReportStatistics();
2520 PrintF("Old data space : ");
2521 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002522 PrintF("Code space : ");
2523 code_space_->ReportStatistics();
2524 PrintF("Map space : ");
2525 map_space_->ReportStatistics();
2526 PrintF("Large object space : ");
2527 lo_space_->ReportStatistics();
2528 PrintF(">>>>>> ========================================= >>>>>>\n");
2529}
2530
2531#endif // DEBUG
2532
2533bool Heap::Contains(HeapObject* value) {
2534 return Contains(value->address());
2535}
2536
2537
2538bool Heap::Contains(Address addr) {
2539 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2540 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002541 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002542 old_pointer_space_->Contains(addr) ||
2543 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002544 code_space_->Contains(addr) ||
2545 map_space_->Contains(addr) ||
2546 lo_space_->SlowContains(addr));
2547}
2548
2549
2550bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2551 return InSpace(value->address(), space);
2552}
2553
2554
2555bool Heap::InSpace(Address addr, AllocationSpace space) {
2556 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2557 if (!HasBeenSetup()) return false;
2558
2559 switch (space) {
2560 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002561 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002562 case OLD_POINTER_SPACE:
2563 return old_pointer_space_->Contains(addr);
2564 case OLD_DATA_SPACE:
2565 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002566 case CODE_SPACE:
2567 return code_space_->Contains(addr);
2568 case MAP_SPACE:
2569 return map_space_->Contains(addr);
2570 case LO_SPACE:
2571 return lo_space_->SlowContains(addr);
2572 }
2573
2574 return false;
2575}
2576
2577
2578#ifdef DEBUG
2579void Heap::Verify() {
2580 ASSERT(HasBeenSetup());
2581
2582 VerifyPointersVisitor visitor;
2583 Heap::IterateRoots(&visitor);
2584
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002585 AllSpaces spaces;
2586 while (Space* space = spaces.next()) {
2587 space->Verify();
2588 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002589}
2590#endif // DEBUG
2591
2592
2593Object* Heap::LookupSymbol(Vector<const char> string) {
2594 Object* symbol = NULL;
2595 Object* new_table =
2596 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2597 if (new_table->IsFailure()) return new_table;
2598 symbol_table_ = new_table;
2599 ASSERT(symbol != NULL);
2600 return symbol;
2601}
2602
2603
2604Object* Heap::LookupSymbol(String* string) {
2605 if (string->IsSymbol()) return string;
2606 Object* symbol = NULL;
2607 Object* new_table =
2608 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2609 if (new_table->IsFailure()) return new_table;
2610 symbol_table_ = new_table;
2611 ASSERT(symbol != NULL);
2612 return symbol;
2613}
2614
2615
ager@chromium.org7c537e22008-10-16 08:43:32 +00002616bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2617 if (string->IsSymbol()) {
2618 *symbol = string;
2619 return true;
2620 }
2621 SymbolTable* table = SymbolTable::cast(symbol_table_);
2622 return table->LookupSymbolIfExists(string, symbol);
2623}
2624
2625
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002626#ifdef DEBUG
2627void Heap::ZapFromSpace() {
2628 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002629 for (Address a = new_space_.FromSpaceLow();
2630 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002631 a += kPointerSize) {
2632 Memory::Address_at(a) = kFromSpaceZapValue;
2633 }
2634}
2635#endif // DEBUG
2636
2637
2638void Heap::IterateRSetRange(Address object_start,
2639 Address object_end,
2640 Address rset_start,
2641 ObjectSlotCallback copy_object_func) {
2642 Address object_address = object_start;
2643 Address rset_address = rset_start;
2644
2645 // Loop over all the pointers in [object_start, object_end).
2646 while (object_address < object_end) {
2647 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002648 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002649 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002650 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002651 // Do not dereference pointers at or past object_end.
2652 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2653 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002654 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002655 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2656 }
2657 // If this pointer does not need to be remembered anymore, clear
2658 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002659 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002660 }
2661 object_address += kPointerSize;
2662 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002663 // Update the remembered set if it has changed.
2664 if (result_rset != rset_word) {
2665 Memory::uint32_at(rset_address) = result_rset;
2666 }
2667 } else {
2668 // No bits in the word were set. This is the common case.
2669 object_address += kPointerSize * kBitsPerInt;
2670 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002671 rset_address += kIntSize;
2672 }
2673}
2674
2675
2676void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2677 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002678 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002679
2680 PageIterator it(space, PageIterator::PAGES_IN_USE);
2681 while (it.has_next()) {
2682 Page* page = it.next();
2683 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2684 page->RSetStart(), copy_object_func);
2685 }
2686}
2687
2688
2689#ifdef DEBUG
2690#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2691#else
2692#define SYNCHRONIZE_TAG(tag)
2693#endif
2694
2695void Heap::IterateRoots(ObjectVisitor* v) {
2696 IterateStrongRoots(v);
2697 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2698 SYNCHRONIZE_TAG("symbol_table");
2699}
2700
2701
2702void Heap::IterateStrongRoots(ObjectVisitor* v) {
2703#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002704 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002705 STRONG_ROOT_LIST(ROOT_ITERATE);
2706#undef ROOT_ITERATE
2707 SYNCHRONIZE_TAG("strong_root_list");
2708
2709#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002710 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002711 STRUCT_LIST(STRUCT_MAP_ITERATE);
2712#undef STRUCT_MAP_ITERATE
2713 SYNCHRONIZE_TAG("struct_map");
2714
2715#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002716 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002717 SYMBOL_LIST(SYMBOL_ITERATE)
2718#undef SYMBOL_ITERATE
ager@chromium.org3b45ab52009-03-19 22:21:34 +00002719 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002720 SYNCHRONIZE_TAG("symbol");
2721
2722 Bootstrapper::Iterate(v);
2723 SYNCHRONIZE_TAG("bootstrapper");
2724 Top::Iterate(v);
2725 SYNCHRONIZE_TAG("top");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002726
2727#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002728 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002729#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002730 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002731 CompilationCache::Iterate(v);
2732 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002733
2734 // Iterate over local handles in handle scopes.
2735 HandleScopeImplementer::Iterate(v);
2736 SYNCHRONIZE_TAG("handlescope");
2737
2738 // Iterate over the builtin code objects and code stubs in the heap. Note
2739 // that it is not strictly necessary to iterate over code objects on
2740 // scavenge collections. We still do it here because this same function
2741 // is used by the mark-sweep collector and the deserializer.
2742 Builtins::IterateBuiltins(v);
2743 SYNCHRONIZE_TAG("builtins");
2744
2745 // Iterate over global handles.
2746 GlobalHandles::IterateRoots(v);
2747 SYNCHRONIZE_TAG("globalhandles");
2748
2749 // Iterate over pointers being held by inactive threads.
2750 ThreadManager::Iterate(v);
2751 SYNCHRONIZE_TAG("threadmanager");
2752}
2753#undef SYNCHRONIZE_TAG
2754
2755
2756// Flag is set when the heap has been configured. The heap can be repeatedly
2757// configured through the API until it is setup.
2758static bool heap_configured = false;
2759
2760// TODO(1236194): Since the heap size is configurable on the command line
2761// and through the API, we should gracefully handle the case that the heap
2762// size is not big enough to fit all the initial objects.
2763bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2764 if (HasBeenSetup()) return false;
2765
2766 if (semispace_size > 0) semispace_size_ = semispace_size;
2767 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2768
2769 // The new space size must be a power of two to support single-bit testing
2770 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002771 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002772 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2773 young_generation_size_ = 2 * semispace_size_;
2774
2775 // The old generation is paged.
2776 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2777
2778 heap_configured = true;
2779 return true;
2780}
2781
2782
kasper.lund7276f142008-07-30 08:49:36 +00002783bool Heap::ConfigureHeapDefault() {
2784 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2785}
2786
2787
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002788int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002789 return old_pointer_space_->Size()
2790 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002791 + code_space_->Size()
2792 + map_space_->Size()
2793 + lo_space_->Size();
2794}
2795
2796
kasper.lund7276f142008-07-30 08:49:36 +00002797int Heap::PromotedExternalMemorySize() {
2798 if (amount_of_external_allocated_memory_
2799 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2800 return amount_of_external_allocated_memory_
2801 - amount_of_external_allocated_memory_at_last_global_gc_;
2802}
2803
2804
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002805bool Heap::Setup(bool create_heap_objects) {
2806 // Initialize heap spaces and initial maps and objects. Whenever something
2807 // goes wrong, just return false. The caller should check the results and
2808 // call Heap::TearDown() to release allocated memory.
2809 //
2810 // If the heap is not yet configured (eg, through the API), configure it.
2811 // Configuration is based on the flags new-space-size (really the semispace
2812 // size) and old-space-size if set or the initial values of semispace_size_
2813 // and old_generation_size_ otherwise.
2814 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002815 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002816 }
2817
2818 // Setup memory allocator and allocate an initial chunk of memory. The
2819 // initial chunk is double the size of the new space to ensure that we can
2820 // find a pair of semispaces that are contiguous and aligned to their size.
2821 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2822 void* chunk
2823 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2824 if (chunk == NULL) return false;
2825
2826 // Put the initial chunk of the old space at the start of the initial
2827 // chunk, then the two new space semispaces, then the initial chunk of
2828 // code space. Align the pair of semispaces to their size, which must be
2829 // a power of 2.
2830 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002831 Address code_space_start = reinterpret_cast<Address>(chunk);
2832 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2833 Address old_space_start = new_space_start + young_generation_size_;
2834 int code_space_size = new_space_start - code_space_start;
2835 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002836
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002837 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002838 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002839
2840 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002841 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002842 old_pointer_space_ =
2843 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2844 if (old_pointer_space_ == NULL) return false;
2845 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2846 return false;
2847 }
2848 old_data_space_ =
2849 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2850 if (old_data_space_ == NULL) return false;
2851 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2852 old_space_size >> 1)) {
2853 return false;
2854 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002855
2856 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002857 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002858 code_space_ =
2859 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002860 if (code_space_ == NULL) return false;
2861 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2862
2863 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002864 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002865 if (map_space_ == NULL) return false;
2866 // Setting up a paged space without giving it a virtual memory range big
2867 // enough to hold at least a page will cause it to allocate.
2868 if (!map_space_->Setup(NULL, 0)) return false;
2869
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002870 // The large object code space may contain code or data. We set the memory
2871 // to be non-executable here for safety, but this means we need to enable it
2872 // explicitly when allocating large code objects.
2873 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002874 if (lo_space_ == NULL) return false;
2875 if (!lo_space_->Setup()) return false;
2876
2877 if (create_heap_objects) {
2878 // Create initial maps.
2879 if (!CreateInitialMaps()) return false;
2880 if (!CreateApiObjects()) return false;
2881
2882 // Create initial objects
2883 if (!CreateInitialObjects()) return false;
2884 }
2885
2886 LOG(IntEvent("heap-capacity", Capacity()));
2887 LOG(IntEvent("heap-available", Available()));
2888
2889 return true;
2890}
2891
2892
2893void Heap::TearDown() {
2894 GlobalHandles::TearDown();
2895
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002896 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002897
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002898 if (old_pointer_space_ != NULL) {
2899 old_pointer_space_->TearDown();
2900 delete old_pointer_space_;
2901 old_pointer_space_ = NULL;
2902 }
2903
2904 if (old_data_space_ != NULL) {
2905 old_data_space_->TearDown();
2906 delete old_data_space_;
2907 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002908 }
2909
2910 if (code_space_ != NULL) {
2911 code_space_->TearDown();
2912 delete code_space_;
2913 code_space_ = NULL;
2914 }
2915
2916 if (map_space_ != NULL) {
2917 map_space_->TearDown();
2918 delete map_space_;
2919 map_space_ = NULL;
2920 }
2921
2922 if (lo_space_ != NULL) {
2923 lo_space_->TearDown();
2924 delete lo_space_;
2925 lo_space_ = NULL;
2926 }
2927
2928 MemoryAllocator::TearDown();
2929}
2930
2931
2932void Heap::Shrink() {
2933 // Try to shrink map, old, and code spaces.
2934 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002935 old_pointer_space_->Shrink();
2936 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002937 code_space_->Shrink();
2938}
2939
2940
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002941#ifdef ENABLE_HEAP_PROTECTION
2942
2943void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002944 if (HasBeenSetup()) {
2945 new_space_.Protect();
2946 map_space_->Protect();
2947 old_pointer_space_->Protect();
2948 old_data_space_->Protect();
2949 code_space_->Protect();
2950 lo_space_->Protect();
2951 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002952}
2953
2954
2955void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002956 if (HasBeenSetup()) {
2957 new_space_.Unprotect();
2958 map_space_->Unprotect();
2959 old_pointer_space_->Unprotect();
2960 old_data_space_->Unprotect();
2961 code_space_->Unprotect();
2962 lo_space_->Unprotect();
2963 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002964}
2965
2966#endif
2967
2968
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002969#ifdef DEBUG
2970
2971class PrintHandleVisitor: public ObjectVisitor {
2972 public:
2973 void VisitPointers(Object** start, Object** end) {
2974 for (Object** p = start; p < end; p++)
2975 PrintF(" handle %p to %p\n", p, *p);
2976 }
2977};
2978
2979void Heap::PrintHandles() {
2980 PrintF("Handles:\n");
2981 PrintHandleVisitor v;
2982 HandleScopeImplementer::Iterate(&v);
2983}
2984
2985#endif
2986
2987
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002988Space* AllSpaces::next() {
2989 switch (counter_++) {
2990 case NEW_SPACE:
2991 return Heap::new_space();
2992 case OLD_POINTER_SPACE:
2993 return Heap::old_pointer_space();
2994 case OLD_DATA_SPACE:
2995 return Heap::old_data_space();
2996 case CODE_SPACE:
2997 return Heap::code_space();
2998 case MAP_SPACE:
2999 return Heap::map_space();
3000 case LO_SPACE:
3001 return Heap::lo_space();
3002 default:
3003 return NULL;
3004 }
3005}
3006
3007
3008PagedSpace* PagedSpaces::next() {
3009 switch (counter_++) {
3010 case OLD_POINTER_SPACE:
3011 return Heap::old_pointer_space();
3012 case OLD_DATA_SPACE:
3013 return Heap::old_data_space();
3014 case CODE_SPACE:
3015 return Heap::code_space();
3016 case MAP_SPACE:
3017 return Heap::map_space();
3018 default:
3019 return NULL;
3020 }
3021}
3022
3023
3024
3025OldSpace* OldSpaces::next() {
3026 switch (counter_++) {
3027 case OLD_POINTER_SPACE:
3028 return Heap::old_pointer_space();
3029 case OLD_DATA_SPACE:
3030 return Heap::old_data_space();
3031 case CODE_SPACE:
3032 return Heap::code_space();
3033 default:
3034 return NULL;
3035 }
3036}
3037
3038
kasper.lund7276f142008-07-30 08:49:36 +00003039SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3040}
3041
3042
3043SpaceIterator::~SpaceIterator() {
3044 // Delete active iterator if any.
3045 delete iterator_;
3046}
3047
3048
3049bool SpaceIterator::has_next() {
3050 // Iterate until no more spaces.
3051 return current_space_ != LAST_SPACE;
3052}
3053
3054
3055ObjectIterator* SpaceIterator::next() {
3056 if (iterator_ != NULL) {
3057 delete iterator_;
3058 iterator_ = NULL;
3059 // Move to the next space
3060 current_space_++;
3061 if (current_space_ > LAST_SPACE) {
3062 return NULL;
3063 }
3064 }
3065
3066 // Return iterator for the new current space.
3067 return CreateIterator();
3068}
3069
3070
3071// Create an iterator for the space to iterate.
3072ObjectIterator* SpaceIterator::CreateIterator() {
3073 ASSERT(iterator_ == NULL);
3074
3075 switch (current_space_) {
3076 case NEW_SPACE:
3077 iterator_ = new SemiSpaceIterator(Heap::new_space());
3078 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003079 case OLD_POINTER_SPACE:
3080 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3081 break;
3082 case OLD_DATA_SPACE:
3083 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003084 break;
3085 case CODE_SPACE:
3086 iterator_ = new HeapObjectIterator(Heap::code_space());
3087 break;
3088 case MAP_SPACE:
3089 iterator_ = new HeapObjectIterator(Heap::map_space());
3090 break;
3091 case LO_SPACE:
3092 iterator_ = new LargeObjectIterator(Heap::lo_space());
3093 break;
3094 }
3095
3096 // Return the newly allocated iterator;
3097 ASSERT(iterator_ != NULL);
3098 return iterator_;
3099}
3100
3101
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003102HeapIterator::HeapIterator() {
3103 Init();
3104}
3105
3106
3107HeapIterator::~HeapIterator() {
3108 Shutdown();
3109}
3110
3111
3112void HeapIterator::Init() {
3113 // Start the iteration.
3114 space_iterator_ = new SpaceIterator();
3115 object_iterator_ = space_iterator_->next();
3116}
3117
3118
3119void HeapIterator::Shutdown() {
3120 // Make sure the last iterator is deallocated.
3121 delete space_iterator_;
3122 space_iterator_ = NULL;
3123 object_iterator_ = NULL;
3124}
3125
3126
3127bool HeapIterator::has_next() {
3128 // No iterator means we are done.
3129 if (object_iterator_ == NULL) return false;
3130
3131 if (object_iterator_->has_next_object()) {
3132 // If the current iterator has more objects we are fine.
3133 return true;
3134 } else {
3135 // Go though the spaces looking for one that has objects.
3136 while (space_iterator_->has_next()) {
3137 object_iterator_ = space_iterator_->next();
3138 if (object_iterator_->has_next_object()) {
3139 return true;
3140 }
3141 }
3142 }
3143 // Done with the last space.
3144 object_iterator_ = NULL;
3145 return false;
3146}
3147
3148
3149HeapObject* HeapIterator::next() {
3150 if (has_next()) {
3151 return object_iterator_->next_object();
3152 } else {
3153 return NULL;
3154 }
3155}
3156
3157
3158void HeapIterator::reset() {
3159 // Restart the iterator.
3160 Shutdown();
3161 Init();
3162}
3163
3164
3165//
3166// HeapProfiler class implementation.
3167//
3168#ifdef ENABLE_LOGGING_AND_PROFILING
3169void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3170 InstanceType type = obj->map()->instance_type();
3171 ASSERT(0 <= type && type <= LAST_TYPE);
3172 info[type].increment_number(1);
3173 info[type].increment_bytes(obj->Size());
3174}
3175#endif
3176
3177
3178#ifdef ENABLE_LOGGING_AND_PROFILING
3179void HeapProfiler::WriteSample() {
3180 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3181
3182 HistogramInfo info[LAST_TYPE+1];
3183#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3184 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3185#undef DEF_TYPE_NAME
3186
3187 HeapIterator iterator;
3188 while (iterator.has_next()) {
3189 CollectStats(iterator.next(), info);
3190 }
3191
3192 // Lump all the string types together.
3193 int string_number = 0;
3194 int string_bytes = 0;
3195#define INCREMENT_SIZE(type, size, name) \
3196 string_number += info[type].number(); \
3197 string_bytes += info[type].bytes();
3198 STRING_TYPE_LIST(INCREMENT_SIZE)
3199#undef INCREMENT_SIZE
3200 if (string_bytes > 0) {
3201 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3202 }
3203
3204 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3205 if (info[i].bytes() > 0) {
3206 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3207 info[i].bytes()));
3208 }
3209 }
3210
3211 LOG(HeapSampleEndEvent("Heap", "allocated"));
3212}
3213
3214
3215#endif
3216
3217
3218
3219#ifdef DEBUG
3220
3221static bool search_for_any_global;
3222static Object* search_target;
3223static bool found_target;
3224static List<Object*> object_stack(20);
3225
3226
3227// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3228static const int kMarkTag = 2;
3229
3230static void MarkObjectRecursively(Object** p);
3231class MarkObjectVisitor : public ObjectVisitor {
3232 public:
3233 void VisitPointers(Object** start, Object** end) {
3234 // Copy all HeapObject pointers in [start, end)
3235 for (Object** p = start; p < end; p++) {
3236 if ((*p)->IsHeapObject())
3237 MarkObjectRecursively(p);
3238 }
3239 }
3240};
3241
3242static MarkObjectVisitor mark_visitor;
3243
3244static void MarkObjectRecursively(Object** p) {
3245 if (!(*p)->IsHeapObject()) return;
3246
3247 HeapObject* obj = HeapObject::cast(*p);
3248
3249 Object* map = obj->map();
3250
3251 if (!map->IsHeapObject()) return; // visited before
3252
3253 if (found_target) return; // stop if target found
3254 object_stack.Add(obj);
3255 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3256 (!search_for_any_global && (obj == search_target))) {
3257 found_target = true;
3258 return;
3259 }
3260
3261 if (obj->IsCode()) {
3262 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3263 }
3264
3265 // not visited yet
3266 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3267
3268 Address map_addr = map_p->address();
3269
3270 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3271
3272 MarkObjectRecursively(&map);
3273
3274 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3275 &mark_visitor);
3276
3277 if (!found_target) // don't pop if found the target
3278 object_stack.RemoveLast();
3279}
3280
3281
3282static void UnmarkObjectRecursively(Object** p);
3283class UnmarkObjectVisitor : public ObjectVisitor {
3284 public:
3285 void VisitPointers(Object** start, Object** end) {
3286 // Copy all HeapObject pointers in [start, end)
3287 for (Object** p = start; p < end; p++) {
3288 if ((*p)->IsHeapObject())
3289 UnmarkObjectRecursively(p);
3290 }
3291 }
3292};
3293
3294static UnmarkObjectVisitor unmark_visitor;
3295
3296static void UnmarkObjectRecursively(Object** p) {
3297 if (!(*p)->IsHeapObject()) return;
3298
3299 HeapObject* obj = HeapObject::cast(*p);
3300
3301 Object* map = obj->map();
3302
3303 if (map->IsHeapObject()) return; // unmarked already
3304
3305 Address map_addr = reinterpret_cast<Address>(map);
3306
3307 map_addr -= kMarkTag;
3308
3309 ASSERT_TAG_ALIGNED(map_addr);
3310
3311 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3312
3313 obj->set_map(reinterpret_cast<Map*>(map_p));
3314
3315 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3316
3317 obj->IterateBody(Map::cast(map_p)->instance_type(),
3318 obj->SizeFromMap(Map::cast(map_p)),
3319 &unmark_visitor);
3320
3321 if (obj->IsCode()) {
3322 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3323 }
3324}
3325
3326
3327static void MarkRootObjectRecursively(Object** root) {
3328 if (search_for_any_global) {
3329 ASSERT(search_target == NULL);
3330 } else {
3331 ASSERT(search_target->IsHeapObject());
3332 }
3333 found_target = false;
3334 object_stack.Clear();
3335
3336 MarkObjectRecursively(root);
3337 UnmarkObjectRecursively(root);
3338
3339 if (found_target) {
3340 PrintF("=====================================\n");
3341 PrintF("==== Path to object ====\n");
3342 PrintF("=====================================\n\n");
3343
3344 ASSERT(!object_stack.is_empty());
3345 for (int i = 0; i < object_stack.length(); i++) {
3346 if (i > 0) PrintF("\n |\n |\n V\n\n");
3347 Object* obj = object_stack[i];
3348 obj->Print();
3349 }
3350 PrintF("=====================================\n");
3351 }
3352}
3353
3354
3355// Helper class for visiting HeapObjects recursively.
3356class MarkRootVisitor: public ObjectVisitor {
3357 public:
3358 void VisitPointers(Object** start, Object** end) {
3359 // Visit all HeapObject pointers in [start, end)
3360 for (Object** p = start; p < end; p++) {
3361 if ((*p)->IsHeapObject())
3362 MarkRootObjectRecursively(p);
3363 }
3364 }
3365};
3366
3367
3368// Triggers a depth-first traversal of reachable objects from roots
3369// and finds a path to a specific heap object and prints it.
3370void Heap::TracePathToObject() {
3371 search_target = NULL;
3372 search_for_any_global = false;
3373
3374 MarkRootVisitor root_visitor;
3375 IterateRoots(&root_visitor);
3376}
3377
3378
3379// Triggers a depth-first traversal of reachable objects from roots
3380// and finds a path to any global object and prints it. Useful for
3381// determining the source for leaks of global objects.
3382void Heap::TracePathToGlobal() {
3383 search_target = NULL;
3384 search_for_any_global = true;
3385
3386 MarkRootVisitor root_visitor;
3387 IterateRoots(&root_visitor);
3388}
3389#endif
3390
3391
kasper.lund7276f142008-07-30 08:49:36 +00003392GCTracer::GCTracer()
3393 : start_time_(0.0),
3394 start_size_(0.0),
3395 gc_count_(0),
3396 full_gc_count_(0),
3397 is_compacting_(false),
3398 marked_count_(0) {
3399 // These two fields reflect the state of the previous full collection.
3400 // Set them before they are changed by the collector.
3401 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3402 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3403 if (!FLAG_trace_gc) return;
3404 start_time_ = OS::TimeCurrentMillis();
3405 start_size_ = SizeOfHeapObjects();
3406}
3407
3408
3409GCTracer::~GCTracer() {
3410 if (!FLAG_trace_gc) return;
3411 // Printf ONE line iff flag is set.
3412 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3413 CollectorString(),
3414 start_size_, SizeOfHeapObjects(),
3415 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3416}
3417
3418
3419const char* GCTracer::CollectorString() {
3420 switch (collector_) {
3421 case SCAVENGER:
3422 return "Scavenge";
3423 case MARK_COMPACTOR:
3424 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3425 : "Mark-sweep";
3426 }
3427 return "Unknown GC";
3428}
3429
3430
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003431#ifdef DEBUG
3432bool Heap::GarbageCollectionGreedyCheck() {
3433 ASSERT(FLAG_gc_greedy);
3434 if (Bootstrapper::IsActive()) return true;
3435 if (disallow_allocation_failure()) return true;
3436 return CollectGarbage(0, NEW_SPACE);
3437}
3438#endif
3439
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003440} } // namespace v8::internal