blob: 0a276ca9959e1b6ffedfbfba3b23d4e75d35419e [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 the V8 project authors. All rights reserved.
2// 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"
34#include "compilation-cache.h"
35#include "debug.h"
36#include "heap-profiler.h"
37#include "global-handles.h"
38#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
Steve Block3ce2e202009-11-05 08:53:23 +000042#include "snapshot.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043#include "v8threads.h"
Steve Block6ded16b2010-05-10 14:33:55 +010044#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000045#include "regexp-macro-assembler.h"
Steve Blockd0582a62009-12-15 09:54:21 +000046#include "arm/regexp-macro-assembler-arm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000047#endif
48
Steve Block6ded16b2010-05-10 14:33:55 +010049
Steve Blocka7e24c12009-10-30 11:49:00 +000050namespace v8 {
51namespace internal {
52
53
54String* Heap::hidden_symbol_;
55Object* Heap::roots_[Heap::kRootListLength];
56
57
58NewSpace Heap::new_space_;
59OldSpace* Heap::old_pointer_space_ = NULL;
60OldSpace* Heap::old_data_space_ = NULL;
61OldSpace* Heap::code_space_ = NULL;
62MapSpace* Heap::map_space_ = NULL;
63CellSpace* Heap::cell_space_ = NULL;
64LargeObjectSpace* Heap::lo_space_ = NULL;
65
66static const int kMinimumPromotionLimit = 2*MB;
67static const int kMinimumAllocationLimit = 8*MB;
68
69int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
70int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
71
72int Heap::old_gen_exhausted_ = false;
73
74int Heap::amount_of_external_allocated_memory_ = 0;
75int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
76
77// semispace_size_ should be a power of 2 and old_generation_size_ should be
78// a multiple of Page::kPageSize.
79#if defined(ANDROID)
Leon Clarked91b9f72010-01-27 17:25:45 +000080int Heap::max_semispace_size_ = 2*MB;
81int Heap::max_old_generation_size_ = 192*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000082int Heap::initial_semispace_size_ = 128*KB;
83size_t Heap::code_range_size_ = 0;
84#elif defined(V8_TARGET_ARCH_X64)
Steve Block3ce2e202009-11-05 08:53:23 +000085int Heap::max_semispace_size_ = 16*MB;
86int Heap::max_old_generation_size_ = 1*GB;
Steve Blocka7e24c12009-10-30 11:49:00 +000087int Heap::initial_semispace_size_ = 1*MB;
Steve Block3ce2e202009-11-05 08:53:23 +000088size_t Heap::code_range_size_ = 512*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000089#else
Steve Block3ce2e202009-11-05 08:53:23 +000090int Heap::max_semispace_size_ = 8*MB;
91int Heap::max_old_generation_size_ = 512*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000092int Heap::initial_semispace_size_ = 512*KB;
93size_t Heap::code_range_size_ = 0;
94#endif
95
Steve Block3ce2e202009-11-05 08:53:23 +000096// The snapshot semispace size will be the default semispace size if
97// snapshotting is used and will be the requested semispace size as
98// set up by ConfigureHeap otherwise.
99int Heap::reserved_semispace_size_ = Heap::max_semispace_size_;
100
Steve Block6ded16b2010-05-10 14:33:55 +0100101List<Heap::GCPrologueCallbackPair> Heap::gc_prologue_callbacks_;
102List<Heap::GCEpilogueCallbackPair> Heap::gc_epilogue_callbacks_;
103
Steve Blocka7e24c12009-10-30 11:49:00 +0000104GCCallback Heap::global_gc_prologue_callback_ = NULL;
105GCCallback Heap::global_gc_epilogue_callback_ = NULL;
106
107// Variables set based on semispace_size_ and old_generation_size_ in
108// ConfigureHeap.
Steve Block3ce2e202009-11-05 08:53:23 +0000109
110// Will be 4 * reserved_semispace_size_ to ensure that young
111// generation can be aligned to its size.
Steve Blocka7e24c12009-10-30 11:49:00 +0000112int Heap::survived_since_last_expansion_ = 0;
113int Heap::external_allocation_limit_ = 0;
114
115Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
116
117int Heap::mc_count_ = 0;
118int Heap::gc_count_ = 0;
119
Steve Block6ded16b2010-05-10 14:33:55 +0100120int Heap::unflattened_strings_length_ = 0;
121
Steve Blocka7e24c12009-10-30 11:49:00 +0000122int Heap::always_allocate_scope_depth_ = 0;
Steve Blockd0582a62009-12-15 09:54:21 +0000123int Heap::linear_allocation_scope_depth_ = 0;
Steve Block6ded16b2010-05-10 14:33:55 +0100124int Heap::contexts_disposed_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000125
126#ifdef DEBUG
127bool Heap::allocation_allowed_ = true;
128
129int Heap::allocation_timeout_ = 0;
130bool Heap::disallow_allocation_failure_ = false;
131#endif // DEBUG
132
133
134int Heap::Capacity() {
135 if (!HasBeenSetup()) return 0;
136
137 return new_space_.Capacity() +
138 old_pointer_space_->Capacity() +
139 old_data_space_->Capacity() +
140 code_space_->Capacity() +
141 map_space_->Capacity() +
142 cell_space_->Capacity();
143}
144
145
Steve Block3ce2e202009-11-05 08:53:23 +0000146int Heap::CommittedMemory() {
147 if (!HasBeenSetup()) return 0;
148
149 return new_space_.CommittedMemory() +
150 old_pointer_space_->CommittedMemory() +
151 old_data_space_->CommittedMemory() +
152 code_space_->CommittedMemory() +
153 map_space_->CommittedMemory() +
154 cell_space_->CommittedMemory() +
155 lo_space_->Size();
156}
157
158
Steve Blocka7e24c12009-10-30 11:49:00 +0000159int Heap::Available() {
160 if (!HasBeenSetup()) return 0;
161
162 return new_space_.Available() +
163 old_pointer_space_->Available() +
164 old_data_space_->Available() +
165 code_space_->Available() +
166 map_space_->Available() +
167 cell_space_->Available();
168}
169
170
171bool Heap::HasBeenSetup() {
172 return old_pointer_space_ != NULL &&
173 old_data_space_ != NULL &&
174 code_space_ != NULL &&
175 map_space_ != NULL &&
176 cell_space_ != NULL &&
177 lo_space_ != NULL;
178}
179
180
181GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
182 // Is global GC requested?
183 if (space != NEW_SPACE || FLAG_gc_global) {
184 Counters::gc_compactor_caused_by_request.Increment();
185 return MARK_COMPACTOR;
186 }
187
188 // Is enough data promoted to justify a global GC?
189 if (OldGenerationPromotionLimitReached()) {
190 Counters::gc_compactor_caused_by_promoted_data.Increment();
191 return MARK_COMPACTOR;
192 }
193
194 // Have allocation in OLD and LO failed?
195 if (old_gen_exhausted_) {
196 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
197 return MARK_COMPACTOR;
198 }
199
200 // Is there enough space left in OLD to guarantee that a scavenge can
201 // succeed?
202 //
203 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
204 // for object promotion. It counts only the bytes that the memory
205 // allocator has not yet allocated from the OS and assigned to any space,
206 // and does not count available bytes already in the old space or code
207 // space. Undercounting is safe---we may get an unrequested full GC when
208 // a scavenge would have succeeded.
209 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
210 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
211 return MARK_COMPACTOR;
212 }
213
214 // Default
215 return SCAVENGER;
216}
217
218
219// TODO(1238405): Combine the infrastructure for --heap-stats and
220// --log-gc to avoid the complicated preprocessor and flag testing.
221#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
222void Heap::ReportStatisticsBeforeGC() {
223 // Heap::ReportHeapStatistics will also log NewSpace statistics when
224 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
225 // following logic is used to avoid double logging.
226#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
227 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
228 if (FLAG_heap_stats) {
229 ReportHeapStatistics("Before GC");
230 } else if (FLAG_log_gc) {
231 new_space_.ReportStatistics();
232 }
233 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
234#elif defined(DEBUG)
235 if (FLAG_heap_stats) {
236 new_space_.CollectStatistics();
237 ReportHeapStatistics("Before GC");
238 new_space_.ClearHistograms();
239 }
240#elif defined(ENABLE_LOGGING_AND_PROFILING)
241 if (FLAG_log_gc) {
242 new_space_.CollectStatistics();
243 new_space_.ReportStatistics();
244 new_space_.ClearHistograms();
245 }
246#endif
247}
248
249
250#if defined(ENABLE_LOGGING_AND_PROFILING)
251void Heap::PrintShortHeapStatistics() {
252 if (!FLAG_trace_gc_verbose) return;
253 PrintF("Memory allocator, used: %8d, available: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000254 MemoryAllocator::Size(),
255 MemoryAllocator::Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000256 PrintF("New space, used: %8d, available: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000257 Heap::new_space_.Size(),
258 new_space_.Available());
259 PrintF("Old pointers, used: %8d, available: %8d, waste: %8d\n",
260 old_pointer_space_->Size(),
261 old_pointer_space_->Available(),
262 old_pointer_space_->Waste());
263 PrintF("Old data space, used: %8d, available: %8d, waste: %8d\n",
264 old_data_space_->Size(),
265 old_data_space_->Available(),
266 old_data_space_->Waste());
267 PrintF("Code space, used: %8d, available: %8d, waste: %8d\n",
268 code_space_->Size(),
269 code_space_->Available(),
270 code_space_->Waste());
271 PrintF("Map space, used: %8d, available: %8d, waste: %8d\n",
272 map_space_->Size(),
273 map_space_->Available(),
274 map_space_->Waste());
275 PrintF("Cell space, used: %8d, available: %8d, waste: %8d\n",
276 cell_space_->Size(),
277 cell_space_->Available(),
278 cell_space_->Waste());
Steve Blocka7e24c12009-10-30 11:49:00 +0000279 PrintF("Large object space, used: %8d, avaialble: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000280 lo_space_->Size(),
281 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000282}
283#endif
284
285
286// TODO(1238405): Combine the infrastructure for --heap-stats and
287// --log-gc to avoid the complicated preprocessor and flag testing.
288void Heap::ReportStatisticsAfterGC() {
289 // Similar to the before GC, we use some complicated logic to ensure that
290 // NewSpace statistics are logged exactly once when --log-gc is turned on.
291#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
292 if (FLAG_heap_stats) {
293 new_space_.CollectStatistics();
294 ReportHeapStatistics("After GC");
295 } else if (FLAG_log_gc) {
296 new_space_.ReportStatistics();
297 }
298#elif defined(DEBUG)
299 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
300#elif defined(ENABLE_LOGGING_AND_PROFILING)
301 if (FLAG_log_gc) new_space_.ReportStatistics();
302#endif
303}
304#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
305
306
307void Heap::GarbageCollectionPrologue() {
308 TranscendentalCache::Clear();
Steve Block6ded16b2010-05-10 14:33:55 +0100309 ClearJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000310 gc_count_++;
Steve Block6ded16b2010-05-10 14:33:55 +0100311 unflattened_strings_length_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000312#ifdef DEBUG
313 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
314 allow_allocation(false);
315
316 if (FLAG_verify_heap) {
317 Verify();
318 }
319
320 if (FLAG_gc_verbose) Print();
321
322 if (FLAG_print_rset) {
323 // Not all spaces have remembered set bits that we care about.
324 old_pointer_space_->PrintRSet();
325 map_space_->PrintRSet();
326 lo_space_->PrintRSet();
327 }
328#endif
329
330#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
331 ReportStatisticsBeforeGC();
332#endif
333}
334
335int Heap::SizeOfObjects() {
336 int total = 0;
337 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +0000338 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000339 total += space->Size();
340 }
341 return total;
342}
343
344void Heap::GarbageCollectionEpilogue() {
345#ifdef DEBUG
346 allow_allocation(true);
347 ZapFromSpace();
348
349 if (FLAG_verify_heap) {
350 Verify();
351 }
352
353 if (FLAG_print_global_handles) GlobalHandles::Print();
354 if (FLAG_print_handles) PrintHandles();
355 if (FLAG_gc_verbose) Print();
356 if (FLAG_code_stats) ReportCodeStatistics("After GC");
357#endif
358
359 Counters::alive_after_last_gc.Set(SizeOfObjects());
360
361 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
362 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
363#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
364 ReportStatisticsAfterGC();
365#endif
366#ifdef ENABLE_DEBUGGER_SUPPORT
367 Debug::AfterGarbageCollection();
368#endif
369}
370
371
372void Heap::CollectAllGarbage(bool force_compaction) {
373 // Since we are ignoring the return value, the exact choice of space does
374 // not matter, so long as we do not specify NEW_SPACE, which would not
375 // cause a full GC.
376 MarkCompactCollector::SetForceCompaction(force_compaction);
377 CollectGarbage(0, OLD_POINTER_SPACE);
378 MarkCompactCollector::SetForceCompaction(false);
379}
380
381
Steve Blocka7e24c12009-10-30 11:49:00 +0000382bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
383 // The VM is in the GC state until exiting this function.
384 VMState state(GC);
385
386#ifdef DEBUG
387 // Reset the allocation timeout to the GC interval, but make sure to
388 // allow at least a few allocations after a collection. The reason
389 // for this is that we have a lot of allocation sequences and we
390 // assume that a garbage collection will allow the subsequent
391 // allocation attempts to go through.
392 allocation_timeout_ = Max(6, FLAG_gc_interval);
393#endif
394
395 { GCTracer tracer;
396 GarbageCollectionPrologue();
397 // The GC count was incremented in the prologue. Tell the tracer about
398 // it.
399 tracer.set_gc_count(gc_count_);
400
401 GarbageCollector collector = SelectGarbageCollector(space);
402 // Tell the tracer which collector we've selected.
403 tracer.set_collector(collector);
404
405 HistogramTimer* rate = (collector == SCAVENGER)
406 ? &Counters::gc_scavenger
407 : &Counters::gc_compactor;
408 rate->Start();
409 PerformGarbageCollection(space, collector, &tracer);
410 rate->Stop();
411
412 GarbageCollectionEpilogue();
413 }
414
415
416#ifdef ENABLE_LOGGING_AND_PROFILING
417 if (FLAG_log_gc) HeapProfiler::WriteSample();
418#endif
419
420 switch (space) {
421 case NEW_SPACE:
422 return new_space_.Available() >= requested_size;
423 case OLD_POINTER_SPACE:
424 return old_pointer_space_->Available() >= requested_size;
425 case OLD_DATA_SPACE:
426 return old_data_space_->Available() >= requested_size;
427 case CODE_SPACE:
428 return code_space_->Available() >= requested_size;
429 case MAP_SPACE:
430 return map_space_->Available() >= requested_size;
431 case CELL_SPACE:
432 return cell_space_->Available() >= requested_size;
433 case LO_SPACE:
434 return lo_space_->Available() >= requested_size;
435 }
436 return false;
437}
438
439
440void Heap::PerformScavenge() {
441 GCTracer tracer;
442 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
443}
444
445
446#ifdef DEBUG
447// Helper class for verifying the symbol table.
448class SymbolTableVerifier : public ObjectVisitor {
449 public:
450 SymbolTableVerifier() { }
451 void VisitPointers(Object** start, Object** end) {
452 // Visit all HeapObject pointers in [start, end).
453 for (Object** p = start; p < end; p++) {
454 if ((*p)->IsHeapObject()) {
455 // Check that the symbol is actually a symbol.
456 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
457 }
458 }
459 }
460};
461#endif // DEBUG
462
463
464static void VerifySymbolTable() {
465#ifdef DEBUG
466 SymbolTableVerifier verifier;
467 Heap::symbol_table()->IterateElements(&verifier);
468#endif // DEBUG
469}
470
471
Leon Clarkee46be812010-01-19 14:06:41 +0000472void Heap::ReserveSpace(
473 int new_space_size,
474 int pointer_space_size,
475 int data_space_size,
476 int code_space_size,
477 int map_space_size,
478 int cell_space_size,
479 int large_object_size) {
480 NewSpace* new_space = Heap::new_space();
481 PagedSpace* old_pointer_space = Heap::old_pointer_space();
482 PagedSpace* old_data_space = Heap::old_data_space();
483 PagedSpace* code_space = Heap::code_space();
484 PagedSpace* map_space = Heap::map_space();
485 PagedSpace* cell_space = Heap::cell_space();
486 LargeObjectSpace* lo_space = Heap::lo_space();
487 bool gc_performed = true;
488 while (gc_performed) {
489 gc_performed = false;
490 if (!new_space->ReserveSpace(new_space_size)) {
491 Heap::CollectGarbage(new_space_size, NEW_SPACE);
492 gc_performed = true;
493 }
494 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
495 Heap::CollectGarbage(pointer_space_size, OLD_POINTER_SPACE);
496 gc_performed = true;
497 }
498 if (!(old_data_space->ReserveSpace(data_space_size))) {
499 Heap::CollectGarbage(data_space_size, OLD_DATA_SPACE);
500 gc_performed = true;
501 }
502 if (!(code_space->ReserveSpace(code_space_size))) {
503 Heap::CollectGarbage(code_space_size, CODE_SPACE);
504 gc_performed = true;
505 }
506 if (!(map_space->ReserveSpace(map_space_size))) {
507 Heap::CollectGarbage(map_space_size, MAP_SPACE);
508 gc_performed = true;
509 }
510 if (!(cell_space->ReserveSpace(cell_space_size))) {
511 Heap::CollectGarbage(cell_space_size, CELL_SPACE);
512 gc_performed = true;
513 }
514 // We add a slack-factor of 2 in order to have space for the remembered
515 // set and a series of large-object allocations that are only just larger
516 // than the page size.
517 large_object_size *= 2;
518 // The ReserveSpace method on the large object space checks how much
519 // we can expand the old generation. This includes expansion caused by
520 // allocation in the other spaces.
521 large_object_size += cell_space_size + map_space_size + code_space_size +
522 data_space_size + pointer_space_size;
523 if (!(lo_space->ReserveSpace(large_object_size))) {
524 Heap::CollectGarbage(large_object_size, LO_SPACE);
525 gc_performed = true;
526 }
527 }
528}
529
530
Steve Blocka7e24c12009-10-30 11:49:00 +0000531void Heap::EnsureFromSpaceIsCommitted() {
532 if (new_space_.CommitFromSpaceIfNeeded()) return;
533
534 // Committing memory to from space failed.
535 // Try shrinking and try again.
536 Shrink();
537 if (new_space_.CommitFromSpaceIfNeeded()) return;
538
539 // Committing memory to from space failed again.
540 // Memory is exhausted and we will die.
541 V8::FatalProcessOutOfMemory("Committing semi space failed.");
542}
543
544
Steve Block6ded16b2010-05-10 14:33:55 +0100545class ClearThreadJSFunctionResultCachesVisitor: public ThreadVisitor {
546 virtual void VisitThread(ThreadLocalTop* top) {
547 Context* context = top->context_;
548 if (context == NULL) return;
549
550 FixedArray* caches =
551 context->global()->global_context()->jsfunction_result_caches();
552 int length = caches->length();
553 for (int i = 0; i < length; i++) {
554 JSFunctionResultCache::cast(caches->get(i))->Clear();
555 }
556 }
557};
558
559
560void Heap::ClearJSFunctionResultCaches() {
561 if (Bootstrapper::IsActive()) return;
562 ClearThreadJSFunctionResultCachesVisitor visitor;
563 ThreadManager::IterateThreads(&visitor);
564}
565
566
Steve Blocka7e24c12009-10-30 11:49:00 +0000567void Heap::PerformGarbageCollection(AllocationSpace space,
568 GarbageCollector collector,
569 GCTracer* tracer) {
570 VerifySymbolTable();
571 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
572 ASSERT(!allocation_allowed_);
Steve Block6ded16b2010-05-10 14:33:55 +0100573 GCTracer::ExternalScope scope(tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000574 global_gc_prologue_callback_();
575 }
Steve Block6ded16b2010-05-10 14:33:55 +0100576
577 GCType gc_type =
578 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
579
580 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
581 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
582 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
583 }
584 }
585
Steve Blocka7e24c12009-10-30 11:49:00 +0000586 EnsureFromSpaceIsCommitted();
Steve Block6ded16b2010-05-10 14:33:55 +0100587
Steve Blocka7e24c12009-10-30 11:49:00 +0000588 if (collector == MARK_COMPACTOR) {
Steve Block6ded16b2010-05-10 14:33:55 +0100589 // Perform mark-sweep with optional compaction.
Steve Blocka7e24c12009-10-30 11:49:00 +0000590 MarkCompact(tracer);
591
592 int old_gen_size = PromotedSpaceSize();
593 old_gen_promotion_limit_ =
594 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
595 old_gen_allocation_limit_ =
596 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
597 old_gen_exhausted_ = false;
Steve Block6ded16b2010-05-10 14:33:55 +0100598 } else {
599 Scavenge();
Steve Blocka7e24c12009-10-30 11:49:00 +0000600 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000601
602 Counters::objs_since_last_young.Set(0);
603
Steve Block3ce2e202009-11-05 08:53:23 +0000604 if (collector == MARK_COMPACTOR) {
605 DisableAssertNoAllocation allow_allocation;
Steve Block6ded16b2010-05-10 14:33:55 +0100606 GCTracer::ExternalScope scope(tracer);
Steve Block3ce2e202009-11-05 08:53:23 +0000607 GlobalHandles::PostGarbageCollectionProcessing();
608 }
609
610 // Update relocatables.
611 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000612
613 if (collector == MARK_COMPACTOR) {
614 // Register the amount of external allocated memory.
615 amount_of_external_allocated_memory_at_last_global_gc_ =
616 amount_of_external_allocated_memory_;
617 }
618
Steve Block6ded16b2010-05-10 14:33:55 +0100619 GCCallbackFlags callback_flags = tracer->is_compacting()
620 ? kGCCallbackFlagCompacted
621 : kNoGCCallbackFlags;
622 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
623 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
624 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
625 }
626 }
627
Steve Blocka7e24c12009-10-30 11:49:00 +0000628 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
629 ASSERT(!allocation_allowed_);
Steve Block6ded16b2010-05-10 14:33:55 +0100630 GCTracer::ExternalScope scope(tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000631 global_gc_epilogue_callback_();
632 }
633 VerifySymbolTable();
634}
635
636
Steve Blocka7e24c12009-10-30 11:49:00 +0000637void Heap::MarkCompact(GCTracer* tracer) {
638 gc_state_ = MARK_COMPACT;
639 mc_count_++;
640 tracer->set_full_gc_count(mc_count_);
641 LOG(ResourceEvent("markcompact", "begin"));
642
643 MarkCompactCollector::Prepare(tracer);
644
645 bool is_compacting = MarkCompactCollector::IsCompacting();
646
647 MarkCompactPrologue(is_compacting);
648
649 MarkCompactCollector::CollectGarbage();
650
651 MarkCompactEpilogue(is_compacting);
652
653 LOG(ResourceEvent("markcompact", "end"));
654
655 gc_state_ = NOT_IN_GC;
656
657 Shrink();
658
659 Counters::objs_since_last_full.Set(0);
Steve Block6ded16b2010-05-10 14:33:55 +0100660
661 contexts_disposed_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000662}
663
664
665void Heap::MarkCompactPrologue(bool is_compacting) {
666 // At any old GC clear the keyed lookup cache to enable collection of unused
667 // maps.
668 KeyedLookupCache::Clear();
669 ContextSlotCache::Clear();
670 DescriptorLookupCache::Clear();
671
672 CompilationCache::MarkCompactPrologue();
673
674 Top::MarkCompactPrologue(is_compacting);
675 ThreadManager::MarkCompactPrologue(is_compacting);
Leon Clarkee46be812010-01-19 14:06:41 +0000676
Kristian Monsen25f61362010-05-21 11:50:48 +0100677 CompletelyClearInstanceofCache();
678
Leon Clarkee46be812010-01-19 14:06:41 +0000679 if (is_compacting) FlushNumberStringCache();
Steve Blocka7e24c12009-10-30 11:49:00 +0000680}
681
682
683void Heap::MarkCompactEpilogue(bool is_compacting) {
684 Top::MarkCompactEpilogue(is_compacting);
685 ThreadManager::MarkCompactEpilogue(is_compacting);
686}
687
688
689Object* Heap::FindCodeObject(Address a) {
690 Object* obj = code_space_->FindObject(a);
691 if (obj->IsFailure()) {
692 obj = lo_space_->FindObject(a);
693 }
694 ASSERT(!obj->IsFailure());
695 return obj;
696}
697
698
699// Helper class for copying HeapObjects
700class ScavengeVisitor: public ObjectVisitor {
701 public:
702
703 void VisitPointer(Object** p) { ScavengePointer(p); }
704
705 void VisitPointers(Object** start, Object** end) {
706 // Copy all HeapObject pointers in [start, end)
707 for (Object** p = start; p < end; p++) ScavengePointer(p);
708 }
709
710 private:
711 void ScavengePointer(Object** p) {
712 Object* object = *p;
713 if (!Heap::InNewSpace(object)) return;
714 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
715 reinterpret_cast<HeapObject*>(object));
716 }
717};
718
719
720// A queue of pointers and maps of to-be-promoted objects during a
721// scavenge collection.
722class PromotionQueue {
723 public:
724 void Initialize(Address start_address) {
725 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
726 }
727
728 bool is_empty() { return front_ <= rear_; }
729
730 void insert(HeapObject* object, Map* map) {
731 *(--rear_) = object;
732 *(--rear_) = map;
733 // Assert no overflow into live objects.
734 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
735 }
736
737 void remove(HeapObject** object, Map** map) {
738 *object = *(--front_);
739 *map = Map::cast(*(--front_));
740 // Assert no underflow.
741 ASSERT(front_ >= rear_);
742 }
743
744 private:
745 // The front of the queue is higher in memory than the rear.
746 HeapObject** front_;
747 HeapObject** rear_;
748};
749
750
751// Shared state read by the scavenge collector and set by ScavengeObject.
752static PromotionQueue promotion_queue;
753
754
755#ifdef DEBUG
756// Visitor class to verify pointers in code or data space do not point into
757// new space.
758class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
759 public:
760 void VisitPointers(Object** start, Object**end) {
761 for (Object** current = start; current < end; current++) {
762 if ((*current)->IsHeapObject()) {
763 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
764 }
765 }
766 }
767};
768
769
770static void VerifyNonPointerSpacePointers() {
771 // Verify that there are no pointers to new space in spaces where we
772 // do not expect them.
773 VerifyNonPointerSpacePointersVisitor v;
774 HeapObjectIterator code_it(Heap::code_space());
Leon Clarked91b9f72010-01-27 17:25:45 +0000775 for (HeapObject* object = code_it.next();
776 object != NULL; object = code_it.next())
Steve Blocka7e24c12009-10-30 11:49:00 +0000777 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000778
779 HeapObjectIterator data_it(Heap::old_data_space());
Leon Clarked91b9f72010-01-27 17:25:45 +0000780 for (HeapObject* object = data_it.next();
781 object != NULL; object = data_it.next())
782 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000783}
784#endif
785
786
Steve Block6ded16b2010-05-10 14:33:55 +0100787void Heap::CheckNewSpaceExpansionCriteria() {
788 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
789 survived_since_last_expansion_ > new_space_.Capacity()) {
790 // Grow the size of new space if there is room to grow and enough
791 // data has survived scavenge since the last expansion.
792 new_space_.Grow();
793 survived_since_last_expansion_ = 0;
794 }
795}
796
797
Steve Blocka7e24c12009-10-30 11:49:00 +0000798void Heap::Scavenge() {
799#ifdef DEBUG
800 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
801#endif
802
803 gc_state_ = SCAVENGE;
804
805 // Implements Cheney's copying algorithm
806 LOG(ResourceEvent("scavenge", "begin"));
807
808 // Clear descriptor cache.
809 DescriptorLookupCache::Clear();
810
811 // Used for updating survived_since_last_expansion_ at function end.
812 int survived_watermark = PromotedSpaceSize();
813
Steve Block6ded16b2010-05-10 14:33:55 +0100814 CheckNewSpaceExpansionCriteria();
Steve Blocka7e24c12009-10-30 11:49:00 +0000815
816 // Flip the semispaces. After flipping, to space is empty, from space has
817 // live objects.
818 new_space_.Flip();
819 new_space_.ResetAllocationInfo();
820
821 // We need to sweep newly copied objects which can be either in the
822 // to space or promoted to the old generation. For to-space
823 // objects, we treat the bottom of the to space as a queue. Newly
824 // copied and unswept objects lie between a 'front' mark and the
825 // allocation pointer.
826 //
827 // Promoted objects can go into various old-generation spaces, and
828 // can be allocated internally in the spaces (from the free list).
829 // We treat the top of the to space as a queue of addresses of
830 // promoted objects. The addresses of newly promoted and unswept
831 // objects lie between a 'front' mark and a 'rear' mark that is
832 // updated as a side effect of promoting an object.
833 //
834 // There is guaranteed to be enough room at the top of the to space
835 // for the addresses of promoted objects: every object promoted
836 // frees up its size in bytes from the top of the new space, and
837 // objects are at least one pointer in size.
838 Address new_space_front = new_space_.ToSpaceLow();
839 promotion_queue.Initialize(new_space_.ToSpaceHigh());
840
841 ScavengeVisitor scavenge_visitor;
842 // Copy roots.
Leon Clarkee46be812010-01-19 14:06:41 +0000843 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000844
845 // Copy objects reachable from the old generation. By definition,
846 // there are no intergenerational pointers in code or data spaces.
847 IterateRSet(old_pointer_space_, &ScavengePointer);
848 IterateRSet(map_space_, &ScavengePointer);
849 lo_space_->IterateRSet(&ScavengePointer);
850
851 // Copy objects reachable from cells by scavenging cell values directly.
852 HeapObjectIterator cell_iterator(cell_space_);
Leon Clarked91b9f72010-01-27 17:25:45 +0000853 for (HeapObject* cell = cell_iterator.next();
854 cell != NULL; cell = cell_iterator.next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000855 if (cell->IsJSGlobalPropertyCell()) {
856 Address value_address =
857 reinterpret_cast<Address>(cell) +
858 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
859 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
860 }
861 }
862
Leon Clarkee46be812010-01-19 14:06:41 +0000863 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
864
Steve Block6ded16b2010-05-10 14:33:55 +0100865 UpdateNewSpaceReferencesInExternalStringTable(
866 &UpdateNewSpaceReferenceInExternalStringTableEntry);
867
Leon Clarkee46be812010-01-19 14:06:41 +0000868 ASSERT(new_space_front == new_space_.top());
869
870 // Set age mark.
871 new_space_.set_age_mark(new_space_.top());
872
873 // Update how much has survived scavenge.
Steve Block6ded16b2010-05-10 14:33:55 +0100874 IncrementYoungSurvivorsCounter(
875 (PromotedSpaceSize() - survived_watermark) + new_space_.Size());
Leon Clarkee46be812010-01-19 14:06:41 +0000876
877 LOG(ResourceEvent("scavenge", "end"));
878
879 gc_state_ = NOT_IN_GC;
880}
881
882
Steve Block6ded16b2010-05-10 14:33:55 +0100883String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Object** p) {
884 MapWord first_word = HeapObject::cast(*p)->map_word();
885
886 if (!first_word.IsForwardingAddress()) {
887 // Unreachable external string can be finalized.
888 FinalizeExternalString(String::cast(*p));
889 return NULL;
890 }
891
892 // String is still reachable.
893 return String::cast(first_word.ToForwardingAddress());
894}
895
896
897void Heap::UpdateNewSpaceReferencesInExternalStringTable(
898 ExternalStringTableUpdaterCallback updater_func) {
Leon Clarkee46be812010-01-19 14:06:41 +0000899 ExternalStringTable::Verify();
900
901 if (ExternalStringTable::new_space_strings_.is_empty()) return;
902
903 Object** start = &ExternalStringTable::new_space_strings_[0];
904 Object** end = start + ExternalStringTable::new_space_strings_.length();
905 Object** last = start;
906
907 for (Object** p = start; p < end; ++p) {
908 ASSERT(Heap::InFromSpace(*p));
Steve Block6ded16b2010-05-10 14:33:55 +0100909 String* target = updater_func(p);
Leon Clarkee46be812010-01-19 14:06:41 +0000910
Steve Block6ded16b2010-05-10 14:33:55 +0100911 if (target == NULL) continue;
Leon Clarkee46be812010-01-19 14:06:41 +0000912
Leon Clarkee46be812010-01-19 14:06:41 +0000913 ASSERT(target->IsExternalString());
914
915 if (Heap::InNewSpace(target)) {
916 // String is still in new space. Update the table entry.
917 *last = target;
918 ++last;
919 } else {
920 // String got promoted. Move it to the old string list.
921 ExternalStringTable::AddOldString(target);
922 }
923 }
924
925 ASSERT(last <= end);
926 ExternalStringTable::ShrinkNewStrings(static_cast<int>(last - start));
927}
928
929
930Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
931 Address new_space_front) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000932 do {
933 ASSERT(new_space_front <= new_space_.top());
934
935 // The addresses new_space_front and new_space_.top() define a
936 // queue of unprocessed copied objects. Process them until the
937 // queue is empty.
938 while (new_space_front < new_space_.top()) {
939 HeapObject* object = HeapObject::FromAddress(new_space_front);
Leon Clarkee46be812010-01-19 14:06:41 +0000940 object->Iterate(scavenge_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +0000941 new_space_front += object->Size();
942 }
943
944 // Promote and process all the to-be-promoted objects.
945 while (!promotion_queue.is_empty()) {
946 HeapObject* source;
947 Map* map;
948 promotion_queue.remove(&source, &map);
949 // Copy the from-space object to its new location (given by the
950 // forwarding address) and fix its map.
951 HeapObject* target = source->map_word().ToForwardingAddress();
952 CopyBlock(reinterpret_cast<Object**>(target->address()),
953 reinterpret_cast<Object**>(source->address()),
954 source->SizeFromMap(map));
955 target->set_map(map);
956
957#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
958 // Update NewSpace stats if necessary.
959 RecordCopiedObject(target);
960#endif
961 // Visit the newly copied object for pointers to new space.
Leon Clarkee46be812010-01-19 14:06:41 +0000962 target->Iterate(scavenge_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +0000963 UpdateRSet(target);
964 }
965
966 // Take another spin if there are now unswept objects in new space
967 // (there are currently no more unswept promoted objects).
968 } while (new_space_front < new_space_.top());
969
Leon Clarkee46be812010-01-19 14:06:41 +0000970 return new_space_front;
Steve Blocka7e24c12009-10-30 11:49:00 +0000971}
972
973
974void Heap::ClearRSetRange(Address start, int size_in_bytes) {
975 uint32_t start_bit;
976 Address start_word_address =
977 Page::ComputeRSetBitPosition(start, 0, &start_bit);
978 uint32_t end_bit;
979 Address end_word_address =
980 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
981 0,
982 &end_bit);
983
984 // We want to clear the bits in the starting word starting with the
985 // first bit, and in the ending word up to and including the last
986 // bit. Build a pair of bitmasks to do that.
987 uint32_t start_bitmask = start_bit - 1;
988 uint32_t end_bitmask = ~((end_bit << 1) - 1);
989
990 // If the start address and end address are the same, we mask that
991 // word once, otherwise mask the starting and ending word
992 // separately and all the ones in between.
993 if (start_word_address == end_word_address) {
994 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
995 } else {
996 Memory::uint32_at(start_word_address) &= start_bitmask;
997 Memory::uint32_at(end_word_address) &= end_bitmask;
998 start_word_address += kIntSize;
999 memset(start_word_address, 0, end_word_address - start_word_address);
1000 }
1001}
1002
1003
1004class UpdateRSetVisitor: public ObjectVisitor {
1005 public:
1006
1007 void VisitPointer(Object** p) {
1008 UpdateRSet(p);
1009 }
1010
1011 void VisitPointers(Object** start, Object** end) {
1012 // Update a store into slots [start, end), used (a) to update remembered
1013 // set when promoting a young object to old space or (b) to rebuild
1014 // remembered sets after a mark-compact collection.
1015 for (Object** p = start; p < end; p++) UpdateRSet(p);
1016 }
1017 private:
1018
1019 void UpdateRSet(Object** p) {
1020 // The remembered set should not be set. It should be clear for objects
1021 // newly copied to old space, and it is cleared before rebuilding in the
1022 // mark-compact collector.
1023 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
1024 if (Heap::InNewSpace(*p)) {
1025 Page::SetRSet(reinterpret_cast<Address>(p), 0);
1026 }
1027 }
1028};
1029
1030
1031int Heap::UpdateRSet(HeapObject* obj) {
1032 ASSERT(!InNewSpace(obj));
1033 // Special handling of fixed arrays to iterate the body based on the start
1034 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
1035 // will not work because Page::SetRSet needs to have the start of the
1036 // object for large object pages.
1037 if (obj->IsFixedArray()) {
1038 FixedArray* array = FixedArray::cast(obj);
1039 int length = array->length();
1040 for (int i = 0; i < length; i++) {
1041 int offset = FixedArray::kHeaderSize + i * kPointerSize;
1042 ASSERT(!Page::IsRSetSet(obj->address(), offset));
1043 if (Heap::InNewSpace(array->get(i))) {
1044 Page::SetRSet(obj->address(), offset);
1045 }
1046 }
1047 } else if (!obj->IsCode()) {
1048 // Skip code object, we know it does not contain inter-generational
1049 // pointers.
1050 UpdateRSetVisitor v;
1051 obj->Iterate(&v);
1052 }
1053 return obj->Size();
1054}
1055
1056
1057void Heap::RebuildRSets() {
1058 // By definition, we do not care about remembered set bits in code,
1059 // data, or cell spaces.
1060 map_space_->ClearRSet();
1061 RebuildRSets(map_space_);
1062
1063 old_pointer_space_->ClearRSet();
1064 RebuildRSets(old_pointer_space_);
1065
1066 Heap::lo_space_->ClearRSet();
1067 RebuildRSets(lo_space_);
1068}
1069
1070
1071void Heap::RebuildRSets(PagedSpace* space) {
1072 HeapObjectIterator it(space);
Leon Clarked91b9f72010-01-27 17:25:45 +00001073 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1074 Heap::UpdateRSet(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001075}
1076
1077
1078void Heap::RebuildRSets(LargeObjectSpace* space) {
1079 LargeObjectIterator it(space);
Leon Clarked91b9f72010-01-27 17:25:45 +00001080 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1081 Heap::UpdateRSet(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001082}
1083
1084
1085#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1086void Heap::RecordCopiedObject(HeapObject* obj) {
1087 bool should_record = false;
1088#ifdef DEBUG
1089 should_record = FLAG_heap_stats;
1090#endif
1091#ifdef ENABLE_LOGGING_AND_PROFILING
1092 should_record = should_record || FLAG_log_gc;
1093#endif
1094 if (should_record) {
1095 if (new_space_.Contains(obj)) {
1096 new_space_.RecordAllocation(obj);
1097 } else {
1098 new_space_.RecordPromotion(obj);
1099 }
1100 }
1101}
1102#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1103
1104
1105
1106HeapObject* Heap::MigrateObject(HeapObject* source,
1107 HeapObject* target,
1108 int size) {
1109 // Copy the content of source to target.
1110 CopyBlock(reinterpret_cast<Object**>(target->address()),
1111 reinterpret_cast<Object**>(source->address()),
1112 size);
1113
1114 // Set the forwarding address.
1115 source->set_map_word(MapWord::FromForwardingAddress(target));
1116
1117#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1118 // Update NewSpace stats if necessary.
1119 RecordCopiedObject(target);
1120#endif
1121
1122 return target;
1123}
1124
1125
1126static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
1127 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
1128 ASSERT(object->map() == map);
1129 InstanceType type = map->instance_type();
1130 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
1131 ASSERT(object->IsString() && !object->IsSymbol());
1132 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
1133}
1134
1135
1136void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1137 ASSERT(InFromSpace(object));
1138 MapWord first_word = object->map_word();
1139 ASSERT(!first_word.IsForwardingAddress());
1140
1141 // Optimization: Bypass flattened ConsString objects.
1142 if (IsShortcutCandidate(object, first_word.ToMap())) {
1143 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
1144 *p = object;
1145 // After patching *p we have to repeat the checks that object is in the
1146 // active semispace of the young generation and not already copied.
1147 if (!InNewSpace(object)) return;
1148 first_word = object->map_word();
1149 if (first_word.IsForwardingAddress()) {
1150 *p = first_word.ToForwardingAddress();
1151 return;
1152 }
1153 }
1154
1155 int object_size = object->SizeFromMap(first_word.ToMap());
1156 // We rely on live objects in new space to be at least two pointers,
1157 // so we can store the from-space address and map pointer of promoted
1158 // objects in the to space.
1159 ASSERT(object_size >= 2 * kPointerSize);
1160
1161 // If the object should be promoted, we try to copy it to old space.
1162 if (ShouldBePromoted(object->address(), object_size)) {
1163 Object* result;
1164 if (object_size > MaxObjectSizeInPagedSpace()) {
1165 result = lo_space_->AllocateRawFixedArray(object_size);
1166 if (!result->IsFailure()) {
1167 // Save the from-space object pointer and its map pointer at the
1168 // top of the to space to be swept and copied later. Write the
1169 // forwarding address over the map word of the from-space
1170 // object.
1171 HeapObject* target = HeapObject::cast(result);
1172 promotion_queue.insert(object, first_word.ToMap());
1173 object->set_map_word(MapWord::FromForwardingAddress(target));
1174
1175 // Give the space allocated for the result a proper map by
1176 // treating it as a free list node (not linked into the free
1177 // list).
1178 FreeListNode* node = FreeListNode::FromAddress(target->address());
1179 node->set_size(object_size);
1180
1181 *p = target;
1182 return;
1183 }
1184 } else {
1185 OldSpace* target_space = Heap::TargetSpace(object);
1186 ASSERT(target_space == Heap::old_pointer_space_ ||
1187 target_space == Heap::old_data_space_);
1188 result = target_space->AllocateRaw(object_size);
1189 if (!result->IsFailure()) {
1190 HeapObject* target = HeapObject::cast(result);
1191 if (target_space == Heap::old_pointer_space_) {
1192 // Save the from-space object pointer and its map pointer at the
1193 // top of the to space to be swept and copied later. Write the
1194 // forwarding address over the map word of the from-space
1195 // object.
1196 promotion_queue.insert(object, first_word.ToMap());
1197 object->set_map_word(MapWord::FromForwardingAddress(target));
1198
1199 // Give the space allocated for the result a proper map by
1200 // treating it as a free list node (not linked into the free
1201 // list).
1202 FreeListNode* node = FreeListNode::FromAddress(target->address());
1203 node->set_size(object_size);
1204
1205 *p = target;
1206 } else {
1207 // Objects promoted to the data space can be copied immediately
1208 // and not revisited---we will never sweep that space for
1209 // pointers and the copied objects do not contain pointers to
1210 // new space objects.
1211 *p = MigrateObject(object, target, object_size);
1212#ifdef DEBUG
1213 VerifyNonPointerSpacePointersVisitor v;
1214 (*p)->Iterate(&v);
1215#endif
1216 }
1217 return;
1218 }
1219 }
1220 }
1221 // The object should remain in new space or the old space allocation failed.
1222 Object* result = new_space_.AllocateRaw(object_size);
1223 // Failed allocation at this point is utterly unexpected.
1224 ASSERT(!result->IsFailure());
1225 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1226}
1227
1228
1229void Heap::ScavengePointer(HeapObject** p) {
1230 ScavengeObject(p, *p);
1231}
1232
1233
1234Object* Heap::AllocatePartialMap(InstanceType instance_type,
1235 int instance_size) {
1236 Object* result = AllocateRawMap();
1237 if (result->IsFailure()) return result;
1238
1239 // Map::cast cannot be used due to uninitialized map field.
1240 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1241 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1242 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1243 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001244 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001245 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001246 reinterpret_cast<Map*>(result)->set_bit_field(0);
1247 reinterpret_cast<Map*>(result)->set_bit_field2(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001248 return result;
1249}
1250
1251
1252Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
1253 Object* result = AllocateRawMap();
1254 if (result->IsFailure()) return result;
1255
1256 Map* map = reinterpret_cast<Map*>(result);
1257 map->set_map(meta_map());
1258 map->set_instance_type(instance_type);
1259 map->set_prototype(null_value());
1260 map->set_constructor(null_value());
1261 map->set_instance_size(instance_size);
1262 map->set_inobject_properties(0);
1263 map->set_pre_allocated_property_fields(0);
1264 map->set_instance_descriptors(empty_descriptor_array());
1265 map->set_code_cache(empty_fixed_array());
1266 map->set_unused_property_fields(0);
1267 map->set_bit_field(0);
Leon Clarked91b9f72010-01-27 17:25:45 +00001268 map->set_bit_field2(1 << Map::kIsExtensible);
Leon Clarkee46be812010-01-19 14:06:41 +00001269
1270 // If the map object is aligned fill the padding area with Smi 0 objects.
1271 if (Map::kPadStart < Map::kSize) {
1272 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1273 0,
1274 Map::kSize - Map::kPadStart);
1275 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001276 return map;
1277}
1278
1279
Steve Block6ded16b2010-05-10 14:33:55 +01001280Object* Heap::AllocateCodeCache() {
1281 Object* result = AllocateStruct(CODE_CACHE_TYPE);
1282 if (result->IsFailure()) return result;
1283 CodeCache* code_cache = CodeCache::cast(result);
1284 code_cache->set_default_cache(empty_fixed_array());
1285 code_cache->set_normal_type_cache(undefined_value());
1286 return code_cache;
1287}
1288
1289
Steve Blocka7e24c12009-10-30 11:49:00 +00001290const Heap::StringTypeTable Heap::string_type_table[] = {
1291#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1292 {type, size, k##camel_name##MapRootIndex},
1293 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1294#undef STRING_TYPE_ELEMENT
1295};
1296
1297
1298const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1299#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1300 {contents, k##name##RootIndex},
1301 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1302#undef CONSTANT_SYMBOL_ELEMENT
1303};
1304
1305
1306const Heap::StructTable Heap::struct_table[] = {
1307#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1308 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1309 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1310#undef STRUCT_TABLE_ELEMENT
1311};
1312
1313
1314bool Heap::CreateInitialMaps() {
1315 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1316 if (obj->IsFailure()) return false;
1317 // Map::cast cannot be used due to uninitialized map field.
1318 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1319 set_meta_map(new_meta_map);
1320 new_meta_map->set_map(new_meta_map);
1321
1322 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
1323 if (obj->IsFailure()) return false;
1324 set_fixed_array_map(Map::cast(obj));
1325
1326 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1327 if (obj->IsFailure()) return false;
1328 set_oddball_map(Map::cast(obj));
1329
Steve Block6ded16b2010-05-10 14:33:55 +01001330 // Allocate the empty array.
Steve Blocka7e24c12009-10-30 11:49:00 +00001331 obj = AllocateEmptyFixedArray();
1332 if (obj->IsFailure()) return false;
1333 set_empty_fixed_array(FixedArray::cast(obj));
1334
1335 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1336 if (obj->IsFailure()) return false;
1337 set_null_value(obj);
1338
1339 // Allocate the empty descriptor array.
1340 obj = AllocateEmptyFixedArray();
1341 if (obj->IsFailure()) return false;
1342 set_empty_descriptor_array(DescriptorArray::cast(obj));
1343
1344 // Fix the instance_descriptors for the existing maps.
1345 meta_map()->set_instance_descriptors(empty_descriptor_array());
1346 meta_map()->set_code_cache(empty_fixed_array());
1347
1348 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
1349 fixed_array_map()->set_code_cache(empty_fixed_array());
1350
1351 oddball_map()->set_instance_descriptors(empty_descriptor_array());
1352 oddball_map()->set_code_cache(empty_fixed_array());
1353
1354 // Fix prototype object for existing maps.
1355 meta_map()->set_prototype(null_value());
1356 meta_map()->set_constructor(null_value());
1357
1358 fixed_array_map()->set_prototype(null_value());
1359 fixed_array_map()->set_constructor(null_value());
1360
1361 oddball_map()->set_prototype(null_value());
1362 oddball_map()->set_constructor(null_value());
1363
1364 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1365 if (obj->IsFailure()) return false;
1366 set_heap_number_map(Map::cast(obj));
1367
1368 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1369 if (obj->IsFailure()) return false;
1370 set_proxy_map(Map::cast(obj));
1371
1372 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1373 const StringTypeTable& entry = string_type_table[i];
1374 obj = AllocateMap(entry.type, entry.size);
1375 if (obj->IsFailure()) return false;
1376 roots_[entry.index] = Map::cast(obj);
1377 }
1378
Steve Blockd0582a62009-12-15 09:54:21 +00001379 obj = AllocateMap(STRING_TYPE, SeqTwoByteString::kAlignedSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00001380 if (obj->IsFailure()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00001381 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001382 Map::cast(obj)->set_is_undetectable();
1383
Steve Blockd0582a62009-12-15 09:54:21 +00001384 obj = AllocateMap(ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00001385 if (obj->IsFailure()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00001386 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001387 Map::cast(obj)->set_is_undetectable();
1388
1389 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
1390 if (obj->IsFailure()) return false;
1391 set_byte_array_map(Map::cast(obj));
1392
1393 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1394 if (obj->IsFailure()) return false;
1395 set_pixel_array_map(Map::cast(obj));
1396
Steve Block3ce2e202009-11-05 08:53:23 +00001397 obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1398 ExternalArray::kAlignedSize);
1399 if (obj->IsFailure()) return false;
1400 set_external_byte_array_map(Map::cast(obj));
1401
1402 obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1403 ExternalArray::kAlignedSize);
1404 if (obj->IsFailure()) return false;
1405 set_external_unsigned_byte_array_map(Map::cast(obj));
1406
1407 obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1408 ExternalArray::kAlignedSize);
1409 if (obj->IsFailure()) return false;
1410 set_external_short_array_map(Map::cast(obj));
1411
1412 obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1413 ExternalArray::kAlignedSize);
1414 if (obj->IsFailure()) return false;
1415 set_external_unsigned_short_array_map(Map::cast(obj));
1416
1417 obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1418 ExternalArray::kAlignedSize);
1419 if (obj->IsFailure()) return false;
1420 set_external_int_array_map(Map::cast(obj));
1421
1422 obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1423 ExternalArray::kAlignedSize);
1424 if (obj->IsFailure()) return false;
1425 set_external_unsigned_int_array_map(Map::cast(obj));
1426
1427 obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1428 ExternalArray::kAlignedSize);
1429 if (obj->IsFailure()) return false;
1430 set_external_float_array_map(Map::cast(obj));
1431
Steve Blocka7e24c12009-10-30 11:49:00 +00001432 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1433 if (obj->IsFailure()) return false;
1434 set_code_map(Map::cast(obj));
1435
1436 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1437 JSGlobalPropertyCell::kSize);
1438 if (obj->IsFailure()) return false;
1439 set_global_property_cell_map(Map::cast(obj));
1440
1441 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1442 if (obj->IsFailure()) return false;
1443 set_one_pointer_filler_map(Map::cast(obj));
1444
1445 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1446 if (obj->IsFailure()) return false;
1447 set_two_pointer_filler_map(Map::cast(obj));
1448
1449 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1450 const StructTable& entry = struct_table[i];
1451 obj = AllocateMap(entry.type, entry.size);
1452 if (obj->IsFailure()) return false;
1453 roots_[entry.index] = Map::cast(obj);
1454 }
1455
1456 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1457 if (obj->IsFailure()) return false;
1458 set_hash_table_map(Map::cast(obj));
1459
1460 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1461 if (obj->IsFailure()) return false;
1462 set_context_map(Map::cast(obj));
1463
1464 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1465 if (obj->IsFailure()) return false;
1466 set_catch_context_map(Map::cast(obj));
1467
1468 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1469 if (obj->IsFailure()) return false;
1470 set_global_context_map(Map::cast(obj));
1471
Steve Block6ded16b2010-05-10 14:33:55 +01001472 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
1473 SharedFunctionInfo::kAlignedSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00001474 if (obj->IsFailure()) return false;
1475 set_shared_function_info_map(Map::cast(obj));
1476
1477 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
1478 return true;
1479}
1480
1481
1482Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1483 // Statically ensure that it is safe to allocate heap numbers in paged
1484 // spaces.
1485 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1486 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1487
Steve Blocka7e24c12009-10-30 11:49:00 +00001488 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
1489 if (result->IsFailure()) return result;
1490
1491 HeapObject::cast(result)->set_map(heap_number_map());
1492 HeapNumber::cast(result)->set_value(value);
1493 return result;
1494}
1495
1496
1497Object* Heap::AllocateHeapNumber(double value) {
1498 // Use general version, if we're forced to always allocate.
1499 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1500
1501 // This version of AllocateHeapNumber is optimized for
1502 // allocation in new space.
1503 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1504 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1505 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
1506 if (result->IsFailure()) return result;
1507 HeapObject::cast(result)->set_map(heap_number_map());
1508 HeapNumber::cast(result)->set_value(value);
1509 return result;
1510}
1511
1512
1513Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
1514 Object* result = AllocateRawCell();
1515 if (result->IsFailure()) return result;
1516 HeapObject::cast(result)->set_map(global_property_cell_map());
1517 JSGlobalPropertyCell::cast(result)->set_value(value);
1518 return result;
1519}
1520
1521
Steve Block6ded16b2010-05-10 14:33:55 +01001522Object* Heap::CreateOddball(const char* to_string,
Steve Blocka7e24c12009-10-30 11:49:00 +00001523 Object* to_number) {
Steve Block6ded16b2010-05-10 14:33:55 +01001524 Object* result = Allocate(oddball_map(), OLD_DATA_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001525 if (result->IsFailure()) return result;
1526 return Oddball::cast(result)->Initialize(to_string, to_number);
1527}
1528
1529
1530bool Heap::CreateApiObjects() {
1531 Object* obj;
1532
1533 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1534 if (obj->IsFailure()) return false;
1535 set_neander_map(Map::cast(obj));
1536
1537 obj = Heap::AllocateJSObjectFromMap(neander_map());
1538 if (obj->IsFailure()) return false;
1539 Object* elements = AllocateFixedArray(2);
1540 if (elements->IsFailure()) return false;
1541 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1542 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1543 set_message_listeners(JSObject::cast(obj));
1544
1545 return true;
1546}
1547
1548
1549void Heap::CreateCEntryStub() {
1550 CEntryStub stub(1);
1551 set_c_entry_code(*stub.GetCode());
1552}
1553
1554
Steve Block6ded16b2010-05-10 14:33:55 +01001555#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001556void Heap::CreateRegExpCEntryStub() {
1557 RegExpCEntryStub stub;
1558 set_re_c_entry_code(*stub.GetCode());
1559}
1560#endif
1561
1562
Steve Blocka7e24c12009-10-30 11:49:00 +00001563void Heap::CreateJSEntryStub() {
1564 JSEntryStub stub;
1565 set_js_entry_code(*stub.GetCode());
1566}
1567
1568
1569void Heap::CreateJSConstructEntryStub() {
1570 JSConstructEntryStub stub;
1571 set_js_construct_entry_code(*stub.GetCode());
1572}
1573
1574
1575void Heap::CreateFixedStubs() {
1576 // Here we create roots for fixed stubs. They are needed at GC
1577 // for cooking and uncooking (check out frames.cc).
1578 // The eliminates the need for doing dictionary lookup in the
1579 // stub cache for these stubs.
1580 HandleScope scope;
1581 // gcc-4.4 has problem generating correct code of following snippet:
1582 // { CEntryStub stub;
1583 // c_entry_code_ = *stub.GetCode();
1584 // }
Leon Clarke4515c472010-02-03 11:58:03 +00001585 // { DebuggerStatementStub stub;
1586 // debugger_statement_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00001587 // }
1588 // To workaround the problem, make separate functions without inlining.
1589 Heap::CreateCEntryStub();
Steve Blocka7e24c12009-10-30 11:49:00 +00001590 Heap::CreateJSEntryStub();
1591 Heap::CreateJSConstructEntryStub();
Steve Block6ded16b2010-05-10 14:33:55 +01001592#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001593 Heap::CreateRegExpCEntryStub();
1594#endif
1595}
1596
1597
1598bool Heap::CreateInitialObjects() {
1599 Object* obj;
1600
1601 // The -0 value must be set before NumberFromDouble works.
1602 obj = AllocateHeapNumber(-0.0, TENURED);
1603 if (obj->IsFailure()) return false;
1604 set_minus_zero_value(obj);
1605 ASSERT(signbit(minus_zero_value()->Number()) != 0);
1606
1607 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1608 if (obj->IsFailure()) return false;
1609 set_nan_value(obj);
1610
1611 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1612 if (obj->IsFailure()) return false;
1613 set_undefined_value(obj);
1614 ASSERT(!InNewSpace(undefined_value()));
1615
1616 // Allocate initial symbol table.
1617 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1618 if (obj->IsFailure()) return false;
1619 // Don't use set_symbol_table() due to asserts.
1620 roots_[kSymbolTableRootIndex] = obj;
1621
1622 // Assign the print strings for oddballs after creating symboltable.
1623 Object* symbol = LookupAsciiSymbol("undefined");
1624 if (symbol->IsFailure()) return false;
1625 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1626 Oddball::cast(undefined_value())->set_to_number(nan_value());
1627
Steve Blocka7e24c12009-10-30 11:49:00 +00001628 // Allocate the null_value
1629 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1630 if (obj->IsFailure()) return false;
1631
Steve Block6ded16b2010-05-10 14:33:55 +01001632 obj = CreateOddball("true", Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00001633 if (obj->IsFailure()) return false;
1634 set_true_value(obj);
1635
Steve Block6ded16b2010-05-10 14:33:55 +01001636 obj = CreateOddball("false", Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00001637 if (obj->IsFailure()) return false;
1638 set_false_value(obj);
1639
Steve Block6ded16b2010-05-10 14:33:55 +01001640 obj = CreateOddball("hole", Smi::FromInt(-1));
Steve Blocka7e24c12009-10-30 11:49:00 +00001641 if (obj->IsFailure()) return false;
1642 set_the_hole_value(obj);
1643
Steve Block6ded16b2010-05-10 14:33:55 +01001644 obj = CreateOddball("no_interceptor_result_sentinel", Smi::FromInt(-2));
Steve Blocka7e24c12009-10-30 11:49:00 +00001645 if (obj->IsFailure()) return false;
1646 set_no_interceptor_result_sentinel(obj);
1647
Steve Block6ded16b2010-05-10 14:33:55 +01001648 obj = CreateOddball("termination_exception", Smi::FromInt(-3));
Steve Blocka7e24c12009-10-30 11:49:00 +00001649 if (obj->IsFailure()) return false;
1650 set_termination_exception(obj);
1651
1652 // Allocate the empty string.
1653 obj = AllocateRawAsciiString(0, TENURED);
1654 if (obj->IsFailure()) return false;
1655 set_empty_string(String::cast(obj));
1656
1657 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1658 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1659 if (obj->IsFailure()) return false;
1660 roots_[constant_symbol_table[i].index] = String::cast(obj);
1661 }
1662
1663 // Allocate the hidden symbol which is used to identify the hidden properties
1664 // in JSObjects. The hash code has a special value so that it will not match
1665 // the empty string when searching for the property. It cannot be part of the
1666 // loop above because it needs to be allocated manually with the special
1667 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1668 // that it will always be at the first entry in property descriptors.
1669 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1670 if (obj->IsFailure()) return false;
1671 hidden_symbol_ = String::cast(obj);
1672
1673 // Allocate the proxy for __proto__.
1674 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1675 if (obj->IsFailure()) return false;
1676 set_prototype_accessors(Proxy::cast(obj));
1677
1678 // Allocate the code_stubs dictionary. The initial size is set to avoid
1679 // expanding the dictionary during bootstrapping.
1680 obj = NumberDictionary::Allocate(128);
1681 if (obj->IsFailure()) return false;
1682 set_code_stubs(NumberDictionary::cast(obj));
1683
1684 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1685 // is set to avoid expanding the dictionary during bootstrapping.
1686 obj = NumberDictionary::Allocate(64);
1687 if (obj->IsFailure()) return false;
1688 set_non_monomorphic_cache(NumberDictionary::cast(obj));
1689
Kristian Monsen25f61362010-05-21 11:50:48 +01001690 set_instanceof_cache_function(Smi::FromInt(0));
1691 set_instanceof_cache_map(Smi::FromInt(0));
1692 set_instanceof_cache_answer(Smi::FromInt(0));
1693
Steve Blocka7e24c12009-10-30 11:49:00 +00001694 CreateFixedStubs();
1695
Leon Clarkee46be812010-01-19 14:06:41 +00001696 if (InitializeNumberStringCache()->IsFailure()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001697
Steve Block6ded16b2010-05-10 14:33:55 +01001698 // Allocate cache for single character ASCII strings.
1699 obj = AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +00001700 if (obj->IsFailure()) return false;
1701 set_single_character_string_cache(FixedArray::cast(obj));
1702
1703 // Allocate cache for external strings pointing to native source code.
1704 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1705 if (obj->IsFailure()) return false;
1706 set_natives_source_cache(FixedArray::cast(obj));
1707
1708 // Handling of script id generation is in Factory::NewScript.
1709 set_last_script_id(undefined_value());
1710
1711 // Initialize keyed lookup cache.
1712 KeyedLookupCache::Clear();
1713
1714 // Initialize context slot cache.
1715 ContextSlotCache::Clear();
1716
1717 // Initialize descriptor cache.
1718 DescriptorLookupCache::Clear();
1719
1720 // Initialize compilation cache.
1721 CompilationCache::Clear();
1722
1723 return true;
1724}
1725
1726
Leon Clarkee46be812010-01-19 14:06:41 +00001727Object* Heap::InitializeNumberStringCache() {
1728 // Compute the size of the number string cache based on the max heap size.
1729 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
1730 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
1731 int number_string_cache_size = max_semispace_size_ / 512;
1732 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
Steve Block6ded16b2010-05-10 14:33:55 +01001733 Object* obj = AllocateFixedArray(number_string_cache_size * 2, TENURED);
Leon Clarkee46be812010-01-19 14:06:41 +00001734 if (!obj->IsFailure()) set_number_string_cache(FixedArray::cast(obj));
1735 return obj;
1736}
1737
1738
1739void Heap::FlushNumberStringCache() {
1740 // Flush the number to string cache.
1741 int len = number_string_cache()->length();
1742 for (int i = 0; i < len; i++) {
1743 number_string_cache()->set_undefined(i);
1744 }
1745}
1746
1747
Steve Blocka7e24c12009-10-30 11:49:00 +00001748static inline int double_get_hash(double d) {
1749 DoubleRepresentation rep(d);
Leon Clarkee46be812010-01-19 14:06:41 +00001750 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
Steve Blocka7e24c12009-10-30 11:49:00 +00001751}
1752
1753
1754static inline int smi_get_hash(Smi* smi) {
Leon Clarkee46be812010-01-19 14:06:41 +00001755 return smi->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001756}
1757
1758
Steve Blocka7e24c12009-10-30 11:49:00 +00001759Object* Heap::GetNumberStringCache(Object* number) {
1760 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00001761 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00001762 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00001763 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00001764 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00001765 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00001766 }
1767 Object* key = number_string_cache()->get(hash * 2);
1768 if (key == number) {
1769 return String::cast(number_string_cache()->get(hash * 2 + 1));
1770 } else if (key->IsHeapNumber() &&
1771 number->IsHeapNumber() &&
1772 key->Number() == number->Number()) {
1773 return String::cast(number_string_cache()->get(hash * 2 + 1));
1774 }
1775 return undefined_value();
1776}
1777
1778
1779void Heap::SetNumberStringCache(Object* number, String* string) {
1780 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00001781 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00001782 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00001783 hash = smi_get_hash(Smi::cast(number)) & mask;
Leon Clarke4515c472010-02-03 11:58:03 +00001784 number_string_cache()->set(hash * 2, Smi::cast(number));
Steve Blocka7e24c12009-10-30 11:49:00 +00001785 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00001786 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00001787 number_string_cache()->set(hash * 2, number);
1788 }
1789 number_string_cache()->set(hash * 2 + 1, string);
1790}
1791
1792
Steve Block6ded16b2010-05-10 14:33:55 +01001793Object* Heap::NumberToString(Object* number, bool check_number_string_cache) {
Andrei Popescu402d9372010-02-26 13:31:12 +00001794 Counters::number_to_string_runtime.Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01001795 if (check_number_string_cache) {
1796 Object* cached = GetNumberStringCache(number);
1797 if (cached != undefined_value()) {
1798 return cached;
1799 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001800 }
1801
1802 char arr[100];
1803 Vector<char> buffer(arr, ARRAY_SIZE(arr));
1804 const char* str;
1805 if (number->IsSmi()) {
1806 int num = Smi::cast(number)->value();
1807 str = IntToCString(num, buffer);
1808 } else {
1809 double num = HeapNumber::cast(number)->value();
1810 str = DoubleToCString(num, buffer);
1811 }
1812 Object* result = AllocateStringFromAscii(CStrVector(str));
1813
1814 if (!result->IsFailure()) {
1815 SetNumberStringCache(number, String::cast(result));
1816 }
1817 return result;
1818}
1819
1820
Steve Block3ce2e202009-11-05 08:53:23 +00001821Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
1822 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
1823}
1824
1825
1826Heap::RootListIndex Heap::RootIndexForExternalArrayType(
1827 ExternalArrayType array_type) {
1828 switch (array_type) {
1829 case kExternalByteArray:
1830 return kExternalByteArrayMapRootIndex;
1831 case kExternalUnsignedByteArray:
1832 return kExternalUnsignedByteArrayMapRootIndex;
1833 case kExternalShortArray:
1834 return kExternalShortArrayMapRootIndex;
1835 case kExternalUnsignedShortArray:
1836 return kExternalUnsignedShortArrayMapRootIndex;
1837 case kExternalIntArray:
1838 return kExternalIntArrayMapRootIndex;
1839 case kExternalUnsignedIntArray:
1840 return kExternalUnsignedIntArrayMapRootIndex;
1841 case kExternalFloatArray:
1842 return kExternalFloatArrayMapRootIndex;
1843 default:
1844 UNREACHABLE();
1845 return kUndefinedValueRootIndex;
1846 }
1847}
1848
1849
Steve Blocka7e24c12009-10-30 11:49:00 +00001850Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01001851 // We need to distinguish the minus zero value and this cannot be
1852 // done after conversion to int. Doing this by comparing bit
1853 // patterns is faster than using fpclassify() et al.
1854 static const DoubleRepresentation minus_zero(-0.0);
1855
1856 DoubleRepresentation rep(value);
1857 if (rep.bits == minus_zero.bits) {
1858 return AllocateHeapNumber(-0.0, pretenure);
1859 }
1860
1861 int int_value = FastD2I(value);
1862 if (value == int_value && Smi::IsValid(int_value)) {
1863 return Smi::FromInt(int_value);
1864 }
1865
1866 // Materialize the value in the heap.
1867 return AllocateHeapNumber(value, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00001868}
1869
1870
1871Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1872 // Statically ensure that it is safe to allocate proxies in paged spaces.
1873 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
1874 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1875 Object* result = Allocate(proxy_map(), space);
1876 if (result->IsFailure()) return result;
1877
1878 Proxy::cast(result)->set_proxy(proxy);
1879 return result;
1880}
1881
1882
1883Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1884 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
1885 if (result->IsFailure()) return result;
1886
1887 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1888 share->set_name(name);
1889 Code* illegal = Builtins::builtin(Builtins::Illegal);
1890 share->set_code(illegal);
1891 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1892 share->set_construct_stub(construct_stub);
1893 share->set_expected_nof_properties(0);
1894 share->set_length(0);
1895 share->set_formal_parameter_count(0);
1896 share->set_instance_class_name(Object_symbol());
1897 share->set_function_data(undefined_value());
1898 share->set_script(undefined_value());
1899 share->set_start_position_and_type(0);
1900 share->set_debug_info(undefined_value());
1901 share->set_inferred_name(empty_string());
1902 share->set_compiler_hints(0);
1903 share->set_this_property_assignments_count(0);
1904 share->set_this_property_assignments(undefined_value());
1905 return result;
1906}
1907
1908
Steve Blockd0582a62009-12-15 09:54:21 +00001909// Returns true for a character in a range. Both limits are inclusive.
1910static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
1911 // This makes uses of the the unsigned wraparound.
1912 return character - from <= to - from;
1913}
1914
1915
1916static inline Object* MakeOrFindTwoCharacterString(uint32_t c1, uint32_t c2) {
1917 String* symbol;
1918 // Numeric strings have a different hash algorithm not known by
1919 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
1920 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
1921 Heap::symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
1922 return symbol;
1923 // Now we know the length is 2, we might as well make use of that fact
1924 // when building the new string.
1925 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
1926 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
1927 Object* result = Heap::AllocateRawAsciiString(2);
1928 if (result->IsFailure()) return result;
1929 char* dest = SeqAsciiString::cast(result)->GetChars();
1930 dest[0] = c1;
1931 dest[1] = c2;
1932 return result;
1933 } else {
1934 Object* result = Heap::AllocateRawTwoByteString(2);
1935 if (result->IsFailure()) return result;
1936 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1937 dest[0] = c1;
1938 dest[1] = c2;
1939 return result;
1940 }
1941}
1942
1943
Steve Blocka7e24c12009-10-30 11:49:00 +00001944Object* Heap::AllocateConsString(String* first, String* second) {
1945 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00001946 if (first_length == 0) {
1947 return second;
1948 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001949
1950 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00001951 if (second_length == 0) {
1952 return first;
1953 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001954
1955 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00001956
1957 // Optimization for 2-byte strings often used as keys in a decompression
1958 // dictionary. Check whether we already have the string in the symbol
1959 // table to prevent creation of many unneccesary strings.
1960 if (length == 2) {
1961 unsigned c1 = first->Get(0);
1962 unsigned c2 = second->Get(0);
1963 return MakeOrFindTwoCharacterString(c1, c2);
1964 }
1965
Steve Block6ded16b2010-05-10 14:33:55 +01001966 bool first_is_ascii = first->IsAsciiRepresentation();
1967 bool second_is_ascii = second->IsAsciiRepresentation();
1968 bool is_ascii = first_is_ascii && second_is_ascii;
Steve Blocka7e24c12009-10-30 11:49:00 +00001969
1970 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00001971 // of the new cons string is too large.
1972 if (length > String::kMaxLength || length < 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001973 Top::context()->mark_out_of_memory();
1974 return Failure::OutOfMemoryException();
1975 }
1976
1977 // If the resulting string is small make a flat string.
1978 if (length < String::kMinNonFlatLength) {
1979 ASSERT(first->IsFlat());
1980 ASSERT(second->IsFlat());
1981 if (is_ascii) {
1982 Object* result = AllocateRawAsciiString(length);
1983 if (result->IsFailure()) return result;
1984 // Copy the characters into the new object.
1985 char* dest = SeqAsciiString::cast(result)->GetChars();
1986 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00001987 const char* src;
1988 if (first->IsExternalString()) {
1989 src = ExternalAsciiString::cast(first)->resource()->data();
1990 } else {
1991 src = SeqAsciiString::cast(first)->GetChars();
1992 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001993 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1994 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00001995 if (second->IsExternalString()) {
1996 src = ExternalAsciiString::cast(second)->resource()->data();
1997 } else {
1998 src = SeqAsciiString::cast(second)->GetChars();
1999 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002000 for (int i = 0; i < second_length; i++) *dest++ = src[i];
2001 return result;
2002 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002003 // For short external two-byte strings we check whether they can
2004 // be represented using ascii.
2005 if (!first_is_ascii) {
2006 first_is_ascii = first->IsExternalTwoByteStringWithAsciiChars();
2007 }
2008 if (first_is_ascii && !second_is_ascii) {
2009 second_is_ascii = second->IsExternalTwoByteStringWithAsciiChars();
2010 }
2011 if (first_is_ascii && second_is_ascii) {
2012 Object* result = AllocateRawAsciiString(length);
2013 if (result->IsFailure()) return result;
2014 // Copy the characters into the new object.
2015 char* dest = SeqAsciiString::cast(result)->GetChars();
2016 String::WriteToFlat(first, dest, 0, first_length);
2017 String::WriteToFlat(second, dest + first_length, 0, second_length);
2018 Counters::string_add_runtime_ext_to_ascii.Increment();
2019 return result;
2020 }
2021
Steve Blocka7e24c12009-10-30 11:49:00 +00002022 Object* result = AllocateRawTwoByteString(length);
2023 if (result->IsFailure()) return result;
2024 // Copy the characters into the new object.
2025 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2026 String::WriteToFlat(first, dest, 0, first_length);
2027 String::WriteToFlat(second, dest + first_length, 0, second_length);
2028 return result;
2029 }
2030 }
2031
Steve Blockd0582a62009-12-15 09:54:21 +00002032 Map* map = is_ascii ? cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002033
Leon Clarkee46be812010-01-19 14:06:41 +00002034 Object* result = Allocate(map, NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002035 if (result->IsFailure()) return result;
Leon Clarke4515c472010-02-03 11:58:03 +00002036
2037 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00002038 ConsString* cons_string = ConsString::cast(result);
Leon Clarke4515c472010-02-03 11:58:03 +00002039 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002040 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002041 cons_string->set_hash_field(String::kEmptyHashField);
2042 cons_string->set_first(first, mode);
2043 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002044 return result;
2045}
2046
2047
2048Object* Heap::AllocateSubString(String* buffer,
2049 int start,
Steve Block6ded16b2010-05-10 14:33:55 +01002050 int end,
2051 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002052 int length = end - start;
2053
2054 if (length == 1) {
2055 return Heap::LookupSingleCharacterStringFromCode(
2056 buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00002057 } else if (length == 2) {
2058 // Optimization for 2-byte strings often used as keys in a decompression
2059 // dictionary. Check whether we already have the string in the symbol
2060 // table to prevent creation of many unneccesary strings.
2061 unsigned c1 = buffer->Get(start);
2062 unsigned c2 = buffer->Get(start + 1);
2063 return MakeOrFindTwoCharacterString(c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00002064 }
2065
2066 // Make an attempt to flatten the buffer to reduce access time.
Steve Block6ded16b2010-05-10 14:33:55 +01002067 buffer->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002068
2069 Object* result = buffer->IsAsciiRepresentation()
Steve Block6ded16b2010-05-10 14:33:55 +01002070 ? AllocateRawAsciiString(length, pretenure )
2071 : AllocateRawTwoByteString(length, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00002072 if (result->IsFailure()) return result;
Steve Blockd0582a62009-12-15 09:54:21 +00002073 String* string_result = String::cast(result);
Steve Blocka7e24c12009-10-30 11:49:00 +00002074 // Copy the characters into the new object.
Steve Blockd0582a62009-12-15 09:54:21 +00002075 if (buffer->IsAsciiRepresentation()) {
2076 ASSERT(string_result->IsAsciiRepresentation());
2077 char* dest = SeqAsciiString::cast(string_result)->GetChars();
2078 String::WriteToFlat(buffer, dest, start, end);
2079 } else {
2080 ASSERT(string_result->IsTwoByteRepresentation());
2081 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
2082 String::WriteToFlat(buffer, dest, start, end);
Steve Blocka7e24c12009-10-30 11:49:00 +00002083 }
Steve Blockd0582a62009-12-15 09:54:21 +00002084
Steve Blocka7e24c12009-10-30 11:49:00 +00002085 return result;
2086}
2087
2088
2089Object* Heap::AllocateExternalStringFromAscii(
2090 ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00002091 size_t length = resource->length();
2092 if (length > static_cast<size_t>(String::kMaxLength)) {
2093 Top::context()->mark_out_of_memory();
2094 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00002095 }
2096
Steve Blockd0582a62009-12-15 09:54:21 +00002097 Map* map = external_ascii_string_map();
Leon Clarkee46be812010-01-19 14:06:41 +00002098 Object* result = Allocate(map, NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002099 if (result->IsFailure()) return result;
2100
2101 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002102 external_string->set_length(static_cast<int>(length));
2103 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002104 external_string->set_resource(resource);
2105
2106 return result;
2107}
2108
2109
2110Object* Heap::AllocateExternalStringFromTwoByte(
2111 ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00002112 size_t length = resource->length();
2113 if (length > static_cast<size_t>(String::kMaxLength)) {
2114 Top::context()->mark_out_of_memory();
2115 return Failure::OutOfMemoryException();
2116 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002117
Steve Blockd0582a62009-12-15 09:54:21 +00002118 Map* map = Heap::external_string_map();
Leon Clarkee46be812010-01-19 14:06:41 +00002119 Object* result = Allocate(map, NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002120 if (result->IsFailure()) return result;
2121
2122 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002123 external_string->set_length(static_cast<int>(length));
2124 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002125 external_string->set_resource(resource);
2126
2127 return result;
2128}
2129
2130
2131Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
2132 if (code <= String::kMaxAsciiCharCode) {
2133 Object* value = Heap::single_character_string_cache()->get(code);
2134 if (value != Heap::undefined_value()) return value;
2135
2136 char buffer[1];
2137 buffer[0] = static_cast<char>(code);
2138 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
2139
2140 if (result->IsFailure()) return result;
2141 Heap::single_character_string_cache()->set(code, result);
2142 return result;
2143 }
2144
2145 Object* result = Heap::AllocateRawTwoByteString(1);
2146 if (result->IsFailure()) return result;
2147 String* answer = String::cast(result);
2148 answer->Set(0, code);
2149 return answer;
2150}
2151
2152
2153Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00002154 if (length < 0 || length > ByteArray::kMaxLength) {
2155 return Failure::OutOfMemoryException();
2156 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002157 if (pretenure == NOT_TENURED) {
2158 return AllocateByteArray(length);
2159 }
2160 int size = ByteArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00002161 Object* result = (size <= MaxObjectSizeInPagedSpace())
2162 ? old_data_space_->AllocateRaw(size)
2163 : lo_space_->AllocateRaw(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002164 if (result->IsFailure()) return result;
2165
2166 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2167 reinterpret_cast<Array*>(result)->set_length(length);
2168 return result;
2169}
2170
2171
2172Object* Heap::AllocateByteArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00002173 if (length < 0 || length > ByteArray::kMaxLength) {
2174 return Failure::OutOfMemoryException();
2175 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002176 int size = ByteArray::SizeFor(length);
2177 AllocationSpace space =
Leon Clarkee46be812010-01-19 14:06:41 +00002178 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00002179 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002180 if (result->IsFailure()) return result;
2181
2182 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2183 reinterpret_cast<Array*>(result)->set_length(length);
2184 return result;
2185}
2186
2187
2188void Heap::CreateFillerObjectAt(Address addr, int size) {
2189 if (size == 0) return;
2190 HeapObject* filler = HeapObject::FromAddress(addr);
2191 if (size == kPointerSize) {
Steve Block6ded16b2010-05-10 14:33:55 +01002192 filler->set_map(one_pointer_filler_map());
2193 } else if (size == 2 * kPointerSize) {
2194 filler->set_map(two_pointer_filler_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002195 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002196 filler->set_map(byte_array_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002197 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2198 }
2199}
2200
2201
2202Object* Heap::AllocatePixelArray(int length,
2203 uint8_t* external_pointer,
2204 PretenureFlag pretenure) {
2205 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00002206 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002207 if (result->IsFailure()) return result;
2208
2209 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
2210 reinterpret_cast<PixelArray*>(result)->set_length(length);
2211 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
2212
2213 return result;
2214}
2215
2216
Steve Block3ce2e202009-11-05 08:53:23 +00002217Object* Heap::AllocateExternalArray(int length,
2218 ExternalArrayType array_type,
2219 void* external_pointer,
2220 PretenureFlag pretenure) {
2221 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Steve Block3ce2e202009-11-05 08:53:23 +00002222 Object* result = AllocateRaw(ExternalArray::kAlignedSize,
2223 space,
2224 OLD_DATA_SPACE);
Steve Block3ce2e202009-11-05 08:53:23 +00002225 if (result->IsFailure()) return result;
2226
2227 reinterpret_cast<ExternalArray*>(result)->set_map(
2228 MapForExternalArrayType(array_type));
2229 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2230 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2231 external_pointer);
2232
2233 return result;
2234}
2235
2236
Steve Blocka7e24c12009-10-30 11:49:00 +00002237Object* Heap::CreateCode(const CodeDesc& desc,
2238 ZoneScopeInfo* sinfo,
2239 Code::Flags flags,
2240 Handle<Object> self_reference) {
2241 // Compute size
2242 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
2243 int sinfo_size = 0;
2244 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
2245 int obj_size = Code::SizeFor(body_size, sinfo_size);
2246 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
2247 Object* result;
2248 if (obj_size > MaxObjectSizeInPagedSpace()) {
2249 result = lo_space_->AllocateRawCode(obj_size);
2250 } else {
2251 result = code_space_->AllocateRaw(obj_size);
2252 }
2253
2254 if (result->IsFailure()) return result;
2255
2256 // Initialize the object
2257 HeapObject::cast(result)->set_map(code_map());
2258 Code* code = Code::cast(result);
2259 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2260 code->set_instruction_size(desc.instr_size);
2261 code->set_relocation_size(desc.reloc_size);
2262 code->set_sinfo_size(sinfo_size);
2263 code->set_flags(flags);
2264 // Allow self references to created code object by patching the handle to
2265 // point to the newly allocated Code object.
2266 if (!self_reference.is_null()) {
2267 *(self_reference.location()) = code;
2268 }
2269 // Migrate generated code.
2270 // The generated code can contain Object** values (typically from handles)
2271 // that are dereferenced during the copy to point directly to the actual heap
2272 // objects. These pointers can include references to the code object itself,
2273 // through the self_reference parameter.
2274 code->CopyFrom(desc);
2275 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
2276
2277#ifdef DEBUG
2278 code->Verify();
2279#endif
2280 return code;
2281}
2282
2283
2284Object* Heap::CopyCode(Code* code) {
2285 // Allocate an object the same size as the code object.
2286 int obj_size = code->Size();
2287 Object* result;
2288 if (obj_size > MaxObjectSizeInPagedSpace()) {
2289 result = lo_space_->AllocateRawCode(obj_size);
2290 } else {
2291 result = code_space_->AllocateRaw(obj_size);
2292 }
2293
2294 if (result->IsFailure()) return result;
2295
2296 // Copy code object.
2297 Address old_addr = code->address();
2298 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
2299 CopyBlock(reinterpret_cast<Object**>(new_addr),
2300 reinterpret_cast<Object**>(old_addr),
2301 obj_size);
2302 // Relocate the copy.
2303 Code* new_code = Code::cast(result);
2304 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2305 new_code->Relocate(new_addr - old_addr);
2306 return new_code;
2307}
2308
2309
Steve Block6ded16b2010-05-10 14:33:55 +01002310Object* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
2311 int new_body_size = RoundUp(code->instruction_size() + reloc_info.length(),
2312 kObjectAlignment);
2313
2314 int sinfo_size = code->sinfo_size();
2315
2316 int new_obj_size = Code::SizeFor(new_body_size, sinfo_size);
2317
2318 Address old_addr = code->address();
2319
2320 size_t relocation_offset =
2321 static_cast<size_t>(code->relocation_start() - old_addr);
2322
2323 Object* result;
2324 if (new_obj_size > MaxObjectSizeInPagedSpace()) {
2325 result = lo_space_->AllocateRawCode(new_obj_size);
2326 } else {
2327 result = code_space_->AllocateRaw(new_obj_size);
2328 }
2329
2330 if (result->IsFailure()) return result;
2331
2332 // Copy code object.
2333 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
2334
2335 // Copy header and instructions.
2336 memcpy(new_addr, old_addr, relocation_offset);
2337
2338 // Copy patched rinfo.
2339 memcpy(new_addr + relocation_offset,
2340 reloc_info.start(),
2341 reloc_info.length());
2342
2343 Code* new_code = Code::cast(result);
2344 new_code->set_relocation_size(reloc_info.length());
2345
2346 // Copy sinfo.
2347 memcpy(new_code->sinfo_start(), code->sinfo_start(), code->sinfo_size());
2348
2349 // Relocate the copy.
2350 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2351 new_code->Relocate(new_addr - old_addr);
2352
2353#ifdef DEBUG
2354 code->Verify();
2355#endif
2356 return new_code;
2357}
2358
2359
Steve Blocka7e24c12009-10-30 11:49:00 +00002360Object* Heap::Allocate(Map* map, AllocationSpace space) {
2361 ASSERT(gc_state_ == NOT_IN_GC);
2362 ASSERT(map->instance_type() != MAP_TYPE);
Leon Clarkee46be812010-01-19 14:06:41 +00002363 // If allocation failures are disallowed, we may allocate in a different
2364 // space when new space is full and the object is not a large object.
2365 AllocationSpace retry_space =
2366 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
2367 Object* result =
2368 AllocateRaw(map->instance_size(), space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00002369 if (result->IsFailure()) return result;
2370 HeapObject::cast(result)->set_map(map);
Steve Block3ce2e202009-11-05 08:53:23 +00002371#ifdef ENABLE_LOGGING_AND_PROFILING
2372 ProducerHeapProfile::RecordJSObjectAllocation(result);
2373#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00002374 return result;
2375}
2376
2377
2378Object* Heap::InitializeFunction(JSFunction* function,
2379 SharedFunctionInfo* shared,
2380 Object* prototype) {
2381 ASSERT(!prototype->IsMap());
2382 function->initialize_properties();
2383 function->initialize_elements();
2384 function->set_shared(shared);
2385 function->set_prototype_or_initial_map(prototype);
2386 function->set_context(undefined_value());
Leon Clarke4515c472010-02-03 11:58:03 +00002387 function->set_literals(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002388 return function;
2389}
2390
2391
2392Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
2393 // Allocate the prototype. Make sure to use the object function
2394 // from the function's context, since the function can be from a
2395 // different context.
2396 JSFunction* object_function =
2397 function->context()->global_context()->object_function();
2398 Object* prototype = AllocateJSObject(object_function);
2399 if (prototype->IsFailure()) return prototype;
2400 // When creating the prototype for the function we must set its
2401 // constructor to the function.
2402 Object* result =
2403 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2404 function,
2405 DONT_ENUM);
2406 if (result->IsFailure()) return result;
2407 return prototype;
2408}
2409
2410
2411Object* Heap::AllocateFunction(Map* function_map,
2412 SharedFunctionInfo* shared,
Leon Clarkee46be812010-01-19 14:06:41 +00002413 Object* prototype,
2414 PretenureFlag pretenure) {
2415 AllocationSpace space =
2416 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2417 Object* result = Allocate(function_map, space);
Steve Blocka7e24c12009-10-30 11:49:00 +00002418 if (result->IsFailure()) return result;
2419 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2420}
2421
2422
2423Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
2424 // To get fast allocation and map sharing for arguments objects we
2425 // allocate them based on an arguments boilerplate.
2426
2427 // This calls Copy directly rather than using Heap::AllocateRaw so we
2428 // duplicate the check here.
2429 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2430
2431 JSObject* boilerplate =
2432 Top::context()->global_context()->arguments_boilerplate();
2433
Leon Clarkee46be812010-01-19 14:06:41 +00002434 // Check that the size of the boilerplate matches our
2435 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
2436 // on the size being a known constant.
2437 ASSERT(kArgumentsObjectSize == boilerplate->map()->instance_size());
2438
2439 // Do the allocation.
2440 Object* result =
2441 AllocateRaw(kArgumentsObjectSize, NEW_SPACE, OLD_POINTER_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00002442 if (result->IsFailure()) return result;
2443
2444 // Copy the content. The arguments boilerplate doesn't have any
2445 // fields that point to new space so it's safe to skip the write
2446 // barrier here.
2447 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2448 reinterpret_cast<Object**>(boilerplate->address()),
Leon Clarkee46be812010-01-19 14:06:41 +00002449 kArgumentsObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002450
2451 // Set the two properties.
2452 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
2453 callee);
2454 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2455 Smi::FromInt(length),
2456 SKIP_WRITE_BARRIER);
2457
2458 // Check the state of the object
2459 ASSERT(JSObject::cast(result)->HasFastProperties());
2460 ASSERT(JSObject::cast(result)->HasFastElements());
2461
2462 return result;
2463}
2464
2465
2466Object* Heap::AllocateInitialMap(JSFunction* fun) {
2467 ASSERT(!fun->has_initial_map());
2468
2469 // First create a new map with the size and number of in-object properties
2470 // suggested by the function.
2471 int instance_size = fun->shared()->CalculateInstanceSize();
2472 int in_object_properties = fun->shared()->CalculateInObjectProperties();
2473 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
2474 if (map_obj->IsFailure()) return map_obj;
2475
2476 // Fetch or allocate prototype.
2477 Object* prototype;
2478 if (fun->has_instance_prototype()) {
2479 prototype = fun->instance_prototype();
2480 } else {
2481 prototype = AllocateFunctionPrototype(fun);
2482 if (prototype->IsFailure()) return prototype;
2483 }
2484 Map* map = Map::cast(map_obj);
2485 map->set_inobject_properties(in_object_properties);
2486 map->set_unused_property_fields(in_object_properties);
2487 map->set_prototype(prototype);
2488
Andrei Popescu402d9372010-02-26 13:31:12 +00002489 // If the function has only simple this property assignments add
2490 // field descriptors for these to the initial map as the object
2491 // cannot be constructed without having these properties. Guard by
2492 // the inline_new flag so we only change the map if we generate a
2493 // specialized construct stub.
Steve Blocka7e24c12009-10-30 11:49:00 +00002494 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Andrei Popescu402d9372010-02-26 13:31:12 +00002495 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002496 int count = fun->shared()->this_property_assignments_count();
2497 if (count > in_object_properties) {
2498 count = in_object_properties;
2499 }
2500 Object* descriptors_obj = DescriptorArray::Allocate(count);
2501 if (descriptors_obj->IsFailure()) return descriptors_obj;
2502 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
2503 for (int i = 0; i < count; i++) {
2504 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2505 ASSERT(name->IsSymbol());
2506 FieldDescriptor field(name, i, NONE);
Leon Clarke4515c472010-02-03 11:58:03 +00002507 field.SetEnumerationIndex(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00002508 descriptors->Set(i, &field);
2509 }
Leon Clarke4515c472010-02-03 11:58:03 +00002510 descriptors->SetNextEnumerationIndex(count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002511 descriptors->Sort();
2512 map->set_instance_descriptors(descriptors);
2513 map->set_pre_allocated_property_fields(count);
2514 map->set_unused_property_fields(in_object_properties - count);
2515 }
2516 return map;
2517}
2518
2519
2520void Heap::InitializeJSObjectFromMap(JSObject* obj,
2521 FixedArray* properties,
2522 Map* map) {
2523 obj->set_properties(properties);
2524 obj->initialize_elements();
2525 // TODO(1240798): Initialize the object's body using valid initial values
2526 // according to the object's initial map. For example, if the map's
2527 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2528 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2529 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2530 // verification code has to cope with (temporarily) invalid objects. See
2531 // for example, JSArray::JSArrayVerify).
2532 obj->InitializeBody(map->instance_size());
2533}
2534
2535
2536Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2537 // JSFunctions should be allocated using AllocateFunction to be
2538 // properly initialized.
2539 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2540
2541 // Both types of globla objects should be allocated using
2542 // AllocateGloblaObject to be properly initialized.
2543 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2544 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2545
2546 // Allocate the backing storage for the properties.
2547 int prop_size =
2548 map->pre_allocated_property_fields() +
2549 map->unused_property_fields() -
2550 map->inobject_properties();
2551 ASSERT(prop_size >= 0);
2552 Object* properties = AllocateFixedArray(prop_size, pretenure);
2553 if (properties->IsFailure()) return properties;
2554
2555 // Allocate the JSObject.
2556 AllocationSpace space =
2557 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2558 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2559 Object* obj = Allocate(map, space);
2560 if (obj->IsFailure()) return obj;
2561
2562 // Initialize the JSObject.
2563 InitializeJSObjectFromMap(JSObject::cast(obj),
2564 FixedArray::cast(properties),
2565 map);
2566 return obj;
2567}
2568
2569
2570Object* Heap::AllocateJSObject(JSFunction* constructor,
2571 PretenureFlag pretenure) {
2572 // Allocate the initial map if absent.
2573 if (!constructor->has_initial_map()) {
2574 Object* initial_map = AllocateInitialMap(constructor);
2575 if (initial_map->IsFailure()) return initial_map;
2576 constructor->set_initial_map(Map::cast(initial_map));
2577 Map::cast(initial_map)->set_constructor(constructor);
2578 }
2579 // Allocate the object based on the constructors initial map.
2580 Object* result =
2581 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2582 // Make sure result is NOT a global object if valid.
2583 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2584 return result;
2585}
2586
2587
2588Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2589 ASSERT(constructor->has_initial_map());
2590 Map* map = constructor->initial_map();
2591
2592 // Make sure no field properties are described in the initial map.
2593 // This guarantees us that normalizing the properties does not
2594 // require us to change property values to JSGlobalPropertyCells.
2595 ASSERT(map->NextFreePropertyIndex() == 0);
2596
2597 // Make sure we don't have a ton of pre-allocated slots in the
2598 // global objects. They will be unused once we normalize the object.
2599 ASSERT(map->unused_property_fields() == 0);
2600 ASSERT(map->inobject_properties() == 0);
2601
2602 // Initial size of the backing store to avoid resize of the storage during
2603 // bootstrapping. The size differs between the JS global object ad the
2604 // builtins object.
2605 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
2606
2607 // Allocate a dictionary object for backing storage.
2608 Object* obj =
2609 StringDictionary::Allocate(
2610 map->NumberOfDescribedProperties() * 2 + initial_size);
2611 if (obj->IsFailure()) return obj;
2612 StringDictionary* dictionary = StringDictionary::cast(obj);
2613
2614 // The global object might be created from an object template with accessors.
2615 // Fill these accessors into the dictionary.
2616 DescriptorArray* descs = map->instance_descriptors();
2617 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2618 PropertyDetails details = descs->GetDetails(i);
2619 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2620 PropertyDetails d =
2621 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2622 Object* value = descs->GetCallbacksObject(i);
2623 value = Heap::AllocateJSGlobalPropertyCell(value);
2624 if (value->IsFailure()) return value;
2625
2626 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2627 if (result->IsFailure()) return result;
2628 dictionary = StringDictionary::cast(result);
2629 }
2630
2631 // Allocate the global object and initialize it with the backing store.
2632 obj = Allocate(map, OLD_POINTER_SPACE);
2633 if (obj->IsFailure()) return obj;
2634 JSObject* global = JSObject::cast(obj);
2635 InitializeJSObjectFromMap(global, dictionary, map);
2636
2637 // Create a new map for the global object.
2638 obj = map->CopyDropDescriptors();
2639 if (obj->IsFailure()) return obj;
2640 Map* new_map = Map::cast(obj);
2641
2642 // Setup the global object as a normalized object.
2643 global->set_map(new_map);
2644 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2645 global->set_properties(dictionary);
2646
2647 // Make sure result is a global object with properties in dictionary.
2648 ASSERT(global->IsGlobalObject());
2649 ASSERT(!global->HasFastProperties());
2650 return global;
2651}
2652
2653
2654Object* Heap::CopyJSObject(JSObject* source) {
2655 // Never used to copy functions. If functions need to be copied we
2656 // have to be careful to clear the literals array.
2657 ASSERT(!source->IsJSFunction());
2658
2659 // Make the clone.
2660 Map* map = source->map();
2661 int object_size = map->instance_size();
2662 Object* clone;
2663
2664 // If we're forced to always allocate, we use the general allocation
2665 // functions which may leave us with an object in old space.
2666 if (always_allocate()) {
2667 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2668 if (clone->IsFailure()) return clone;
2669 Address clone_address = HeapObject::cast(clone)->address();
2670 CopyBlock(reinterpret_cast<Object**>(clone_address),
2671 reinterpret_cast<Object**>(source->address()),
2672 object_size);
2673 // Update write barrier for all fields that lie beyond the header.
Steve Block6ded16b2010-05-10 14:33:55 +01002674 RecordWrites(clone_address,
2675 JSObject::kHeaderSize,
2676 (object_size - JSObject::kHeaderSize) / kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002677 } else {
2678 clone = new_space_.AllocateRaw(object_size);
2679 if (clone->IsFailure()) return clone;
2680 ASSERT(Heap::InNewSpace(clone));
2681 // Since we know the clone is allocated in new space, we can copy
2682 // the contents without worrying about updating the write barrier.
2683 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2684 reinterpret_cast<Object**>(source->address()),
2685 object_size);
2686 }
2687
2688 FixedArray* elements = FixedArray::cast(source->elements());
2689 FixedArray* properties = FixedArray::cast(source->properties());
2690 // Update elements if necessary.
Steve Block6ded16b2010-05-10 14:33:55 +01002691 if (elements->length() > 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002692 Object* elem = CopyFixedArray(elements);
2693 if (elem->IsFailure()) return elem;
2694 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2695 }
2696 // Update properties if necessary.
2697 if (properties->length() > 0) {
2698 Object* prop = CopyFixedArray(properties);
2699 if (prop->IsFailure()) return prop;
2700 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2701 }
2702 // Return the new clone.
Steve Block3ce2e202009-11-05 08:53:23 +00002703#ifdef ENABLE_LOGGING_AND_PROFILING
2704 ProducerHeapProfile::RecordJSObjectAllocation(clone);
2705#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00002706 return clone;
2707}
2708
2709
2710Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2711 JSGlobalProxy* object) {
2712 // Allocate initial map if absent.
2713 if (!constructor->has_initial_map()) {
2714 Object* initial_map = AllocateInitialMap(constructor);
2715 if (initial_map->IsFailure()) return initial_map;
2716 constructor->set_initial_map(Map::cast(initial_map));
2717 Map::cast(initial_map)->set_constructor(constructor);
2718 }
2719
2720 Map* map = constructor->initial_map();
2721
2722 // Check that the already allocated object has the same size as
2723 // objects allocated using the constructor.
2724 ASSERT(map->instance_size() == object->map()->instance_size());
2725
2726 // Allocate the backing storage for the properties.
2727 int prop_size = map->unused_property_fields() - map->inobject_properties();
2728 Object* properties = AllocateFixedArray(prop_size, TENURED);
2729 if (properties->IsFailure()) return properties;
2730
2731 // Reset the map for the object.
2732 object->set_map(constructor->initial_map());
2733
2734 // Reinitialize the object from the constructor map.
2735 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2736 return object;
2737}
2738
2739
2740Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2741 PretenureFlag pretenure) {
2742 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2743 if (result->IsFailure()) return result;
2744
2745 // Copy the characters into the new object.
2746 SeqAsciiString* string_result = SeqAsciiString::cast(result);
2747 for (int i = 0; i < string.length(); i++) {
2748 string_result->SeqAsciiStringSet(i, string[i]);
2749 }
2750 return result;
2751}
2752
2753
2754Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2755 PretenureFlag pretenure) {
2756 // Count the number of characters in the UTF-8 string and check if
2757 // it is an ASCII string.
2758 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2759 decoder->Reset(string.start(), string.length());
2760 int chars = 0;
2761 bool is_ascii = true;
2762 while (decoder->has_more()) {
2763 uc32 r = decoder->GetNext();
2764 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2765 chars++;
2766 }
2767
2768 // If the string is ascii, we do not need to convert the characters
2769 // since UTF8 is backwards compatible with ascii.
2770 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2771
2772 Object* result = AllocateRawTwoByteString(chars, pretenure);
2773 if (result->IsFailure()) return result;
2774
2775 // Convert and copy the characters into the new object.
2776 String* string_result = String::cast(result);
2777 decoder->Reset(string.start(), string.length());
2778 for (int i = 0; i < chars; i++) {
2779 uc32 r = decoder->GetNext();
2780 string_result->Set(i, r);
2781 }
2782 return result;
2783}
2784
2785
2786Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2787 PretenureFlag pretenure) {
2788 // Check if the string is an ASCII string.
2789 int i = 0;
2790 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2791
2792 Object* result;
2793 if (i == string.length()) { // It's an ASCII string.
2794 result = AllocateRawAsciiString(string.length(), pretenure);
2795 } else { // It's not an ASCII string.
2796 result = AllocateRawTwoByteString(string.length(), pretenure);
2797 }
2798 if (result->IsFailure()) return result;
2799
2800 // Copy the characters into the new object, which may be either ASCII or
2801 // UTF-16.
2802 String* string_result = String::cast(result);
2803 for (int i = 0; i < string.length(); i++) {
2804 string_result->Set(i, string[i]);
2805 }
2806 return result;
2807}
2808
2809
2810Map* Heap::SymbolMapForString(String* string) {
2811 // If the string is in new space it cannot be used as a symbol.
2812 if (InNewSpace(string)) return NULL;
2813
2814 // Find the corresponding symbol map for strings.
2815 Map* map = string->map();
Steve Blockd0582a62009-12-15 09:54:21 +00002816 if (map == ascii_string_map()) return ascii_symbol_map();
2817 if (map == string_map()) return symbol_map();
2818 if (map == cons_string_map()) return cons_symbol_map();
2819 if (map == cons_ascii_string_map()) return cons_ascii_symbol_map();
2820 if (map == external_string_map()) return external_symbol_map();
2821 if (map == external_ascii_string_map()) return external_ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002822
2823 // No match found.
2824 return NULL;
2825}
2826
2827
2828Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2829 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +00002830 uint32_t hash_field) {
Leon Clarkee46be812010-01-19 14:06:41 +00002831 ASSERT(chars >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002832 // Ensure the chars matches the number of characters in the buffer.
2833 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2834 // Determine whether the string is ascii.
2835 bool is_ascii = true;
Leon Clarkee46be812010-01-19 14:06:41 +00002836 while (buffer->has_more()) {
2837 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
2838 is_ascii = false;
2839 break;
2840 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002841 }
2842 buffer->Rewind();
2843
2844 // Compute map and object size.
2845 int size;
2846 Map* map;
2847
2848 if (is_ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +00002849 if (chars > SeqAsciiString::kMaxLength) {
2850 return Failure::OutOfMemoryException();
2851 }
Steve Blockd0582a62009-12-15 09:54:21 +00002852 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002853 size = SeqAsciiString::SizeFor(chars);
2854 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002855 if (chars > SeqTwoByteString::kMaxLength) {
2856 return Failure::OutOfMemoryException();
2857 }
Steve Blockd0582a62009-12-15 09:54:21 +00002858 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002859 size = SeqTwoByteString::SizeFor(chars);
2860 }
2861
2862 // Allocate string.
Leon Clarkee46be812010-01-19 14:06:41 +00002863 Object* result = (size > MaxObjectSizeInPagedSpace())
2864 ? lo_space_->AllocateRaw(size)
2865 : old_data_space_->AllocateRaw(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002866 if (result->IsFailure()) return result;
2867
2868 reinterpret_cast<HeapObject*>(result)->set_map(map);
Steve Blockd0582a62009-12-15 09:54:21 +00002869 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00002870 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002871 answer->set_length(chars);
2872 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00002873
2874 ASSERT_EQ(size, answer->Size());
2875
2876 // Fill in the characters.
2877 for (int i = 0; i < chars; i++) {
2878 answer->Set(i, buffer->GetNext());
2879 }
2880 return answer;
2881}
2882
2883
2884Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00002885 if (length < 0 || length > SeqAsciiString::kMaxLength) {
2886 return Failure::OutOfMemoryException();
2887 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002888
2889 int size = SeqAsciiString::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00002890 ASSERT(size <= SeqAsciiString::kMaxSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002891
Leon Clarkee46be812010-01-19 14:06:41 +00002892 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2893 AllocationSpace retry_space = OLD_DATA_SPACE;
2894
Steve Blocka7e24c12009-10-30 11:49:00 +00002895 if (space == NEW_SPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00002896 if (size > kMaxObjectSizeInNewSpace) {
2897 // Allocate in large object space, retry space will be ignored.
2898 space = LO_SPACE;
2899 } else if (size > MaxObjectSizeInPagedSpace()) {
2900 // Allocate in new space, retry in large object space.
2901 retry_space = LO_SPACE;
2902 }
2903 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2904 space = LO_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00002905 }
Leon Clarkee46be812010-01-19 14:06:41 +00002906 Object* result = AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00002907 if (result->IsFailure()) return result;
2908
Steve Blocka7e24c12009-10-30 11:49:00 +00002909 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00002910 HeapObject::cast(result)->set_map(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002911 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002912 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002913 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2914 return result;
2915}
2916
2917
2918Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00002919 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
2920 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00002921 }
Leon Clarkee46be812010-01-19 14:06:41 +00002922 int size = SeqTwoByteString::SizeFor(length);
2923 ASSERT(size <= SeqTwoByteString::kMaxSize);
2924 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2925 AllocationSpace retry_space = OLD_DATA_SPACE;
2926
2927 if (space == NEW_SPACE) {
2928 if (size > kMaxObjectSizeInNewSpace) {
2929 // Allocate in large object space, retry space will be ignored.
2930 space = LO_SPACE;
2931 } else if (size > MaxObjectSizeInPagedSpace()) {
2932 // Allocate in new space, retry in large object space.
2933 retry_space = LO_SPACE;
2934 }
2935 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2936 space = LO_SPACE;
2937 }
2938 Object* result = AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00002939 if (result->IsFailure()) return result;
2940
Steve Blocka7e24c12009-10-30 11:49:00 +00002941 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00002942 HeapObject::cast(result)->set_map(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002943 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002944 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002945 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2946 return result;
2947}
2948
2949
2950Object* Heap::AllocateEmptyFixedArray() {
2951 int size = FixedArray::SizeFor(0);
2952 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
2953 if (result->IsFailure()) return result;
2954 // Initialize the object.
2955 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2956 reinterpret_cast<Array*>(result)->set_length(0);
2957 return result;
2958}
2959
2960
2961Object* Heap::AllocateRawFixedArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00002962 if (length < 0 || length > FixedArray::kMaxLength) {
2963 return Failure::OutOfMemoryException();
2964 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002965 // Use the general function if we're forced to always allocate.
2966 if (always_allocate()) return AllocateFixedArray(length, TENURED);
2967 // Allocate the raw data for a fixed array.
2968 int size = FixedArray::SizeFor(length);
2969 return size <= kMaxObjectSizeInNewSpace
2970 ? new_space_.AllocateRaw(size)
2971 : lo_space_->AllocateRawFixedArray(size);
2972}
2973
2974
2975Object* Heap::CopyFixedArray(FixedArray* src) {
2976 int len = src->length();
2977 Object* obj = AllocateRawFixedArray(len);
2978 if (obj->IsFailure()) return obj;
2979 if (Heap::InNewSpace(obj)) {
2980 HeapObject* dst = HeapObject::cast(obj);
2981 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2982 reinterpret_cast<Object**>(src->address()),
2983 FixedArray::SizeFor(len));
2984 return obj;
2985 }
2986 HeapObject::cast(obj)->set_map(src->map());
2987 FixedArray* result = FixedArray::cast(obj);
2988 result->set_length(len);
Leon Clarke4515c472010-02-03 11:58:03 +00002989
Steve Blocka7e24c12009-10-30 11:49:00 +00002990 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00002991 AssertNoAllocation no_gc;
2992 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002993 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2994 return result;
2995}
2996
2997
2998Object* Heap::AllocateFixedArray(int length) {
2999 ASSERT(length >= 0);
3000 if (length == 0) return empty_fixed_array();
3001 Object* result = AllocateRawFixedArray(length);
3002 if (!result->IsFailure()) {
3003 // Initialize header.
3004 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
3005 FixedArray* array = FixedArray::cast(result);
3006 array->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003007 // Initialize body.
Steve Block6ded16b2010-05-10 14:33:55 +01003008 ASSERT(!Heap::InNewSpace(undefined_value()));
3009 MemsetPointer(array->data_start(), undefined_value(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003010 }
3011 return result;
3012}
3013
3014
Steve Block6ded16b2010-05-10 14:33:55 +01003015Object* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003016 if (length < 0 || length > FixedArray::kMaxLength) {
3017 return Failure::OutOfMemoryException();
3018 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003019
Leon Clarkee46be812010-01-19 14:06:41 +00003020 AllocationSpace space =
3021 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00003022 int size = FixedArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00003023 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
3024 // Too big for new space.
3025 space = LO_SPACE;
3026 } else if (space == OLD_POINTER_SPACE &&
3027 size > MaxObjectSizeInPagedSpace()) {
3028 // Too big for old pointer space.
3029 space = LO_SPACE;
3030 }
3031
3032 // Specialize allocation for the space.
Steve Blocka7e24c12009-10-30 11:49:00 +00003033 Object* result = Failure::OutOfMemoryException();
Leon Clarkee46be812010-01-19 14:06:41 +00003034 if (space == NEW_SPACE) {
3035 // We cannot use Heap::AllocateRaw() because it will not properly
3036 // allocate extra remembered set bits if always_allocate() is true and
3037 // new space allocation fails.
3038 result = new_space_.AllocateRaw(size);
3039 if (result->IsFailure() && always_allocate()) {
3040 if (size <= MaxObjectSizeInPagedSpace()) {
3041 result = old_pointer_space_->AllocateRaw(size);
3042 } else {
3043 result = lo_space_->AllocateRawFixedArray(size);
3044 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003045 }
Leon Clarkee46be812010-01-19 14:06:41 +00003046 } else if (space == OLD_POINTER_SPACE) {
3047 result = old_pointer_space_->AllocateRaw(size);
3048 } else {
3049 ASSERT(space == LO_SPACE);
3050 result = lo_space_->AllocateRawFixedArray(size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003051 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003052 return result;
3053}
3054
3055
Steve Block6ded16b2010-05-10 14:33:55 +01003056static Object* AllocateFixedArrayWithFiller(int length,
3057 PretenureFlag pretenure,
3058 Object* filler) {
3059 ASSERT(length >= 0);
3060 ASSERT(Heap::empty_fixed_array()->IsFixedArray());
3061 if (length == 0) return Heap::empty_fixed_array();
3062
3063 ASSERT(!Heap::InNewSpace(filler));
3064 Object* result = Heap::AllocateRawFixedArray(length, pretenure);
3065 if (result->IsFailure()) return result;
3066
3067 HeapObject::cast(result)->set_map(Heap::fixed_array_map());
3068 FixedArray* array = FixedArray::cast(result);
3069 array->set_length(length);
3070 MemsetPointer(array->data_start(), filler, length);
3071 return array;
3072}
3073
3074
3075Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
3076 return AllocateFixedArrayWithFiller(length, pretenure, undefined_value());
3077}
3078
3079
3080Object* Heap::AllocateFixedArrayWithHoles(int length, PretenureFlag pretenure) {
3081 return AllocateFixedArrayWithFiller(length, pretenure, the_hole_value());
3082}
3083
3084
3085Object* Heap::AllocateUninitializedFixedArray(int length) {
3086 if (length == 0) return empty_fixed_array();
3087
3088 Object* obj = AllocateRawFixedArray(length);
3089 if (obj->IsFailure()) return obj;
3090
3091 reinterpret_cast<FixedArray*>(obj)->set_map(fixed_array_map());
3092 FixedArray::cast(obj)->set_length(length);
3093 return obj;
3094}
3095
3096
3097Object* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
3098 Object* result = Heap::AllocateFixedArray(length, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00003099 if (result->IsFailure()) return result;
3100 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
3101 ASSERT(result->IsHashTable());
3102 return result;
3103}
3104
3105
3106Object* Heap::AllocateGlobalContext() {
3107 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
3108 if (result->IsFailure()) return result;
3109 Context* context = reinterpret_cast<Context*>(result);
3110 context->set_map(global_context_map());
3111 ASSERT(context->IsGlobalContext());
3112 ASSERT(result->IsContext());
3113 return result;
3114}
3115
3116
3117Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
3118 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
3119 Object* result = Heap::AllocateFixedArray(length);
3120 if (result->IsFailure()) return result;
3121 Context* context = reinterpret_cast<Context*>(result);
3122 context->set_map(context_map());
3123 context->set_closure(function);
3124 context->set_fcontext(context);
3125 context->set_previous(NULL);
3126 context->set_extension(NULL);
3127 context->set_global(function->context()->global());
3128 ASSERT(!context->IsGlobalContext());
3129 ASSERT(context->is_function_context());
3130 ASSERT(result->IsContext());
3131 return result;
3132}
3133
3134
3135Object* Heap::AllocateWithContext(Context* previous,
3136 JSObject* extension,
3137 bool is_catch_context) {
3138 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
3139 if (result->IsFailure()) return result;
3140 Context* context = reinterpret_cast<Context*>(result);
3141 context->set_map(is_catch_context ? catch_context_map() : context_map());
3142 context->set_closure(previous->closure());
3143 context->set_fcontext(previous->fcontext());
3144 context->set_previous(previous);
3145 context->set_extension(extension);
3146 context->set_global(previous->global());
3147 ASSERT(!context->IsGlobalContext());
3148 ASSERT(!context->is_function_context());
3149 ASSERT(result->IsContext());
3150 return result;
3151}
3152
3153
3154Object* Heap::AllocateStruct(InstanceType type) {
3155 Map* map;
3156 switch (type) {
3157#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
3158STRUCT_LIST(MAKE_CASE)
3159#undef MAKE_CASE
3160 default:
3161 UNREACHABLE();
3162 return Failure::InternalError();
3163 }
3164 int size = map->instance_size();
3165 AllocationSpace space =
3166 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
3167 Object* result = Heap::Allocate(map, space);
3168 if (result->IsFailure()) return result;
3169 Struct::cast(result)->InitializeBody(size);
3170 return result;
3171}
3172
3173
3174bool Heap::IdleNotification() {
3175 static const int kIdlesBeforeScavenge = 4;
3176 static const int kIdlesBeforeMarkSweep = 7;
3177 static const int kIdlesBeforeMarkCompact = 8;
3178 static int number_idle_notifications = 0;
3179 static int last_gc_count = gc_count_;
3180
Steve Block6ded16b2010-05-10 14:33:55 +01003181 bool uncommit = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00003182 bool finished = false;
3183
3184 if (last_gc_count == gc_count_) {
3185 number_idle_notifications++;
3186 } else {
3187 number_idle_notifications = 0;
3188 last_gc_count = gc_count_;
3189 }
3190
3191 if (number_idle_notifications == kIdlesBeforeScavenge) {
Steve Block6ded16b2010-05-10 14:33:55 +01003192 if (contexts_disposed_ > 0) {
3193 HistogramTimerScope scope(&Counters::gc_context);
3194 CollectAllGarbage(false);
3195 } else {
3196 CollectGarbage(0, NEW_SPACE);
3197 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003198 new_space_.Shrink();
3199 last_gc_count = gc_count_;
3200
3201 } else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00003202 // Before doing the mark-sweep collections we clear the
3203 // compilation cache to avoid hanging on to source code and
3204 // generated code for cached functions.
3205 CompilationCache::Clear();
3206
Steve Blocka7e24c12009-10-30 11:49:00 +00003207 CollectAllGarbage(false);
3208 new_space_.Shrink();
3209 last_gc_count = gc_count_;
3210
3211 } else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
3212 CollectAllGarbage(true);
3213 new_space_.Shrink();
3214 last_gc_count = gc_count_;
3215 number_idle_notifications = 0;
3216 finished = true;
Steve Block6ded16b2010-05-10 14:33:55 +01003217
3218 } else if (contexts_disposed_ > 0) {
3219 if (FLAG_expose_gc) {
3220 contexts_disposed_ = 0;
3221 } else {
3222 HistogramTimerScope scope(&Counters::gc_context);
3223 CollectAllGarbage(false);
3224 last_gc_count = gc_count_;
3225 }
3226 // If this is the first idle notification, we reset the
3227 // notification count to avoid letting idle notifications for
3228 // context disposal garbage collections start a potentially too
3229 // aggressive idle GC cycle.
3230 if (number_idle_notifications <= 1) {
3231 number_idle_notifications = 0;
3232 uncommit = false;
3233 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003234 }
3235
Steve Block6ded16b2010-05-10 14:33:55 +01003236 // Make sure that we have no pending context disposals and
3237 // conditionally uncommit from space.
3238 ASSERT(contexts_disposed_ == 0);
3239 if (uncommit) Heap::UncommitFromSpace();
Steve Blocka7e24c12009-10-30 11:49:00 +00003240 return finished;
3241}
3242
3243
3244#ifdef DEBUG
3245
3246void Heap::Print() {
3247 if (!HasBeenSetup()) return;
3248 Top::PrintStack();
3249 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00003250 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3251 space->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +00003252}
3253
3254
3255void Heap::ReportCodeStatistics(const char* title) {
3256 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
3257 PagedSpace::ResetCodeStatistics();
3258 // We do not look for code in new space, map space, or old space. If code
3259 // somehow ends up in those spaces, we would miss it here.
3260 code_space_->CollectCodeStatistics();
3261 lo_space_->CollectCodeStatistics();
3262 PagedSpace::ReportCodeStatistics();
3263}
3264
3265
3266// This function expects that NewSpace's allocated objects histogram is
3267// populated (via a call to CollectStatistics or else as a side effect of a
3268// just-completed scavenge collection).
3269void Heap::ReportHeapStatistics(const char* title) {
3270 USE(title);
3271 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
3272 title, gc_count_);
3273 PrintF("mark-compact GC : %d\n", mc_count_);
3274 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
3275 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
3276
3277 PrintF("\n");
3278 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
3279 GlobalHandles::PrintStats();
3280 PrintF("\n");
3281
3282 PrintF("Heap statistics : ");
3283 MemoryAllocator::ReportStatistics();
3284 PrintF("To space : ");
3285 new_space_.ReportStatistics();
3286 PrintF("Old pointer space : ");
3287 old_pointer_space_->ReportStatistics();
3288 PrintF("Old data space : ");
3289 old_data_space_->ReportStatistics();
3290 PrintF("Code space : ");
3291 code_space_->ReportStatistics();
3292 PrintF("Map space : ");
3293 map_space_->ReportStatistics();
3294 PrintF("Cell space : ");
3295 cell_space_->ReportStatistics();
3296 PrintF("Large object space : ");
3297 lo_space_->ReportStatistics();
3298 PrintF(">>>>>> ========================================= >>>>>>\n");
3299}
3300
3301#endif // DEBUG
3302
3303bool Heap::Contains(HeapObject* value) {
3304 return Contains(value->address());
3305}
3306
3307
3308bool Heap::Contains(Address addr) {
3309 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3310 return HasBeenSetup() &&
3311 (new_space_.ToSpaceContains(addr) ||
3312 old_pointer_space_->Contains(addr) ||
3313 old_data_space_->Contains(addr) ||
3314 code_space_->Contains(addr) ||
3315 map_space_->Contains(addr) ||
3316 cell_space_->Contains(addr) ||
3317 lo_space_->SlowContains(addr));
3318}
3319
3320
3321bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
3322 return InSpace(value->address(), space);
3323}
3324
3325
3326bool Heap::InSpace(Address addr, AllocationSpace space) {
3327 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3328 if (!HasBeenSetup()) return false;
3329
3330 switch (space) {
3331 case NEW_SPACE:
3332 return new_space_.ToSpaceContains(addr);
3333 case OLD_POINTER_SPACE:
3334 return old_pointer_space_->Contains(addr);
3335 case OLD_DATA_SPACE:
3336 return old_data_space_->Contains(addr);
3337 case CODE_SPACE:
3338 return code_space_->Contains(addr);
3339 case MAP_SPACE:
3340 return map_space_->Contains(addr);
3341 case CELL_SPACE:
3342 return cell_space_->Contains(addr);
3343 case LO_SPACE:
3344 return lo_space_->SlowContains(addr);
3345 }
3346
3347 return false;
3348}
3349
3350
3351#ifdef DEBUG
3352void Heap::Verify() {
3353 ASSERT(HasBeenSetup());
3354
3355 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00003356 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00003357
3358 new_space_.Verify();
3359
3360 VerifyPointersAndRSetVisitor rset_visitor;
3361 old_pointer_space_->Verify(&rset_visitor);
3362 map_space_->Verify(&rset_visitor);
3363
3364 VerifyPointersVisitor no_rset_visitor;
3365 old_data_space_->Verify(&no_rset_visitor);
3366 code_space_->Verify(&no_rset_visitor);
3367 cell_space_->Verify(&no_rset_visitor);
3368
3369 lo_space_->Verify();
3370}
3371#endif // DEBUG
3372
3373
3374Object* Heap::LookupSymbol(Vector<const char> string) {
3375 Object* symbol = NULL;
3376 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
3377 if (new_table->IsFailure()) return new_table;
3378 // Can't use set_symbol_table because SymbolTable::cast knows that
3379 // SymbolTable is a singleton and checks for identity.
3380 roots_[kSymbolTableRootIndex] = new_table;
3381 ASSERT(symbol != NULL);
3382 return symbol;
3383}
3384
3385
3386Object* Heap::LookupSymbol(String* string) {
3387 if (string->IsSymbol()) return string;
3388 Object* symbol = NULL;
3389 Object* new_table = symbol_table()->LookupString(string, &symbol);
3390 if (new_table->IsFailure()) return new_table;
3391 // Can't use set_symbol_table because SymbolTable::cast knows that
3392 // SymbolTable is a singleton and checks for identity.
3393 roots_[kSymbolTableRootIndex] = new_table;
3394 ASSERT(symbol != NULL);
3395 return symbol;
3396}
3397
3398
3399bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
3400 if (string->IsSymbol()) {
3401 *symbol = string;
3402 return true;
3403 }
3404 return symbol_table()->LookupSymbolIfExists(string, symbol);
3405}
3406
3407
3408#ifdef DEBUG
3409void Heap::ZapFromSpace() {
3410 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
3411 for (Address a = new_space_.FromSpaceLow();
3412 a < new_space_.FromSpaceHigh();
3413 a += kPointerSize) {
3414 Memory::Address_at(a) = kFromSpaceZapValue;
3415 }
3416}
3417#endif // DEBUG
3418
3419
3420int Heap::IterateRSetRange(Address object_start,
3421 Address object_end,
3422 Address rset_start,
3423 ObjectSlotCallback copy_object_func) {
3424 Address object_address = object_start;
3425 Address rset_address = rset_start;
3426 int set_bits_count = 0;
3427
3428 // Loop over all the pointers in [object_start, object_end).
3429 while (object_address < object_end) {
3430 uint32_t rset_word = Memory::uint32_at(rset_address);
3431 if (rset_word != 0) {
3432 uint32_t result_rset = rset_word;
3433 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
3434 // Do not dereference pointers at or past object_end.
3435 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3436 Object** object_p = reinterpret_cast<Object**>(object_address);
3437 if (Heap::InNewSpace(*object_p)) {
3438 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3439 }
3440 // If this pointer does not need to be remembered anymore, clear
3441 // the remembered set bit.
3442 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
3443 set_bits_count++;
3444 }
3445 object_address += kPointerSize;
3446 }
3447 // Update the remembered set if it has changed.
3448 if (result_rset != rset_word) {
3449 Memory::uint32_at(rset_address) = result_rset;
3450 }
3451 } else {
3452 // No bits in the word were set. This is the common case.
3453 object_address += kPointerSize * kBitsPerInt;
3454 }
3455 rset_address += kIntSize;
3456 }
3457 return set_bits_count;
3458}
3459
3460
3461void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3462 ASSERT(Page::is_rset_in_use());
3463 ASSERT(space == old_pointer_space_ || space == map_space_);
3464
3465 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3466 "V8.RSetPaged",
3467 0,
3468 Page::kObjectAreaSize / kPointerSize,
3469 30);
3470
3471 PageIterator it(space, PageIterator::PAGES_IN_USE);
3472 while (it.has_next()) {
3473 Page* page = it.next();
3474 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3475 page->RSetStart(), copy_object_func);
3476 if (paged_rset_histogram != NULL) {
3477 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3478 }
3479 }
3480}
3481
3482
Steve Blockd0582a62009-12-15 09:54:21 +00003483void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
3484 IterateStrongRoots(v, mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00003485 IterateWeakRoots(v, mode);
3486}
3487
3488
3489void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003490 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Steve Blockd0582a62009-12-15 09:54:21 +00003491 v->Synchronize("symbol_table");
Leon Clarkee46be812010-01-19 14:06:41 +00003492 if (mode != VISIT_ALL_IN_SCAVENGE) {
3493 // Scavenge collections have special processing for this.
3494 ExternalStringTable::Iterate(v);
3495 }
3496 v->Synchronize("external_string_table");
Steve Blocka7e24c12009-10-30 11:49:00 +00003497}
3498
3499
Steve Blockd0582a62009-12-15 09:54:21 +00003500void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003501 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Steve Blockd0582a62009-12-15 09:54:21 +00003502 v->Synchronize("strong_root_list");
Steve Blocka7e24c12009-10-30 11:49:00 +00003503
Steve Block6ded16b2010-05-10 14:33:55 +01003504 v->VisitPointer(BitCast<Object**, String**>(&hidden_symbol_));
Steve Blockd0582a62009-12-15 09:54:21 +00003505 v->Synchronize("symbol");
Steve Blocka7e24c12009-10-30 11:49:00 +00003506
3507 Bootstrapper::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003508 v->Synchronize("bootstrapper");
Steve Blocka7e24c12009-10-30 11:49:00 +00003509 Top::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003510 v->Synchronize("top");
Steve Blocka7e24c12009-10-30 11:49:00 +00003511 Relocatable::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003512 v->Synchronize("relocatable");
Steve Blocka7e24c12009-10-30 11:49:00 +00003513
3514#ifdef ENABLE_DEBUGGER_SUPPORT
3515 Debug::Iterate(v);
3516#endif
Steve Blockd0582a62009-12-15 09:54:21 +00003517 v->Synchronize("debug");
Steve Blocka7e24c12009-10-30 11:49:00 +00003518 CompilationCache::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003519 v->Synchronize("compilationcache");
Steve Blocka7e24c12009-10-30 11:49:00 +00003520
3521 // Iterate over local handles in handle scopes.
3522 HandleScopeImplementer::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003523 v->Synchronize("handlescope");
Steve Blocka7e24c12009-10-30 11:49:00 +00003524
Leon Clarkee46be812010-01-19 14:06:41 +00003525 // Iterate over the builtin code objects and code stubs in the
3526 // heap. Note that it is not necessary to iterate over code objects
3527 // on scavenge collections.
3528 if (mode != VISIT_ALL_IN_SCAVENGE) {
3529 Builtins::IterateBuiltins(v);
3530 }
Steve Blockd0582a62009-12-15 09:54:21 +00003531 v->Synchronize("builtins");
Steve Blocka7e24c12009-10-30 11:49:00 +00003532
3533 // Iterate over global handles.
Steve Blockd0582a62009-12-15 09:54:21 +00003534 if (mode == VISIT_ONLY_STRONG) {
3535 GlobalHandles::IterateStrongRoots(v);
3536 } else {
3537 GlobalHandles::IterateAllRoots(v);
3538 }
3539 v->Synchronize("globalhandles");
Steve Blocka7e24c12009-10-30 11:49:00 +00003540
3541 // Iterate over pointers being held by inactive threads.
3542 ThreadManager::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003543 v->Synchronize("threadmanager");
Leon Clarked91b9f72010-01-27 17:25:45 +00003544
3545 // Iterate over the pointers the Serialization/Deserialization code is
3546 // holding.
3547 // During garbage collection this keeps the partial snapshot cache alive.
3548 // During deserialization of the startup snapshot this creates the partial
3549 // snapshot cache and deserializes the objects it refers to. During
3550 // serialization this does nothing, since the partial snapshot cache is
3551 // empty. However the next thing we do is create the partial snapshot,
3552 // filling up the partial snapshot cache with objects it needs as we go.
3553 SerializerDeserializer::Iterate(v);
3554 // We don't do a v->Synchronize call here, because in debug mode that will
3555 // output a flag to the snapshot. However at this point the serializer and
3556 // deserializer are deliberately a little unsynchronized (see above) so the
3557 // checking of the sync flag in the snapshot would fail.
Steve Blocka7e24c12009-10-30 11:49:00 +00003558}
Steve Blocka7e24c12009-10-30 11:49:00 +00003559
3560
3561// Flag is set when the heap has been configured. The heap can be repeatedly
3562// configured through the API until it is setup.
3563static bool heap_configured = false;
3564
3565// TODO(1236194): Since the heap size is configurable on the command line
3566// and through the API, we should gracefully handle the case that the heap
3567// size is not big enough to fit all the initial objects.
Steve Block3ce2e202009-11-05 08:53:23 +00003568bool Heap::ConfigureHeap(int max_semispace_size, int max_old_gen_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003569 if (HasBeenSetup()) return false;
3570
Steve Block3ce2e202009-11-05 08:53:23 +00003571 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
3572
3573 if (Snapshot::IsEnabled()) {
3574 // If we are using a snapshot we always reserve the default amount
3575 // of memory for each semispace because code in the snapshot has
3576 // write-barrier code that relies on the size and alignment of new
3577 // space. We therefore cannot use a larger max semispace size
3578 // than the default reserved semispace size.
3579 if (max_semispace_size_ > reserved_semispace_size_) {
3580 max_semispace_size_ = reserved_semispace_size_;
3581 }
3582 } else {
3583 // If we are not using snapshots we reserve space for the actual
3584 // max semispace size.
3585 reserved_semispace_size_ = max_semispace_size_;
3586 }
3587
3588 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00003589
3590 // The new space size must be a power of two to support single-bit testing
3591 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00003592 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
3593 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
3594 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
3595 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003596
3597 // The old generation is paged.
Steve Block3ce2e202009-11-05 08:53:23 +00003598 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003599
3600 heap_configured = true;
3601 return true;
3602}
3603
3604
3605bool Heap::ConfigureHeapDefault() {
Steve Block3ce2e202009-11-05 08:53:23 +00003606 return ConfigureHeap(FLAG_max_new_space_size / 2, FLAG_max_old_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003607}
3608
3609
Steve Blockd0582a62009-12-15 09:54:21 +00003610void Heap::RecordStats(HeapStats* stats) {
3611 *stats->start_marker = 0xDECADE00;
3612 *stats->end_marker = 0xDECADE01;
3613 *stats->new_space_size = new_space_.Size();
3614 *stats->new_space_capacity = new_space_.Capacity();
3615 *stats->old_pointer_space_size = old_pointer_space_->Size();
3616 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
3617 *stats->old_data_space_size = old_data_space_->Size();
3618 *stats->old_data_space_capacity = old_data_space_->Capacity();
3619 *stats->code_space_size = code_space_->Size();
3620 *stats->code_space_capacity = code_space_->Capacity();
3621 *stats->map_space_size = map_space_->Size();
3622 *stats->map_space_capacity = map_space_->Capacity();
3623 *stats->cell_space_size = cell_space_->Size();
3624 *stats->cell_space_capacity = cell_space_->Capacity();
3625 *stats->lo_space_size = lo_space_->Size();
3626 GlobalHandles::RecordStats(stats);
3627}
3628
3629
Steve Blocka7e24c12009-10-30 11:49:00 +00003630int Heap::PromotedSpaceSize() {
3631 return old_pointer_space_->Size()
3632 + old_data_space_->Size()
3633 + code_space_->Size()
3634 + map_space_->Size()
3635 + cell_space_->Size()
3636 + lo_space_->Size();
3637}
3638
3639
3640int Heap::PromotedExternalMemorySize() {
3641 if (amount_of_external_allocated_memory_
3642 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3643 return amount_of_external_allocated_memory_
3644 - amount_of_external_allocated_memory_at_last_global_gc_;
3645}
3646
3647
3648bool Heap::Setup(bool create_heap_objects) {
3649 // Initialize heap spaces and initial maps and objects. Whenever something
3650 // goes wrong, just return false. The caller should check the results and
3651 // call Heap::TearDown() to release allocated memory.
3652 //
3653 // If the heap is not yet configured (eg, through the API), configure it.
3654 // Configuration is based on the flags new-space-size (really the semispace
3655 // size) and old-space-size if set or the initial values of semispace_size_
3656 // and old_generation_size_ otherwise.
3657 if (!heap_configured) {
3658 if (!ConfigureHeapDefault()) return false;
3659 }
3660
3661 // Setup memory allocator and reserve a chunk of memory for new
Steve Block3ce2e202009-11-05 08:53:23 +00003662 // space. The chunk is double the size of the requested reserved
3663 // new space size to ensure that we can find a pair of semispaces that
3664 // are contiguous and aligned to their size.
3665 if (!MemoryAllocator::Setup(MaxReserved())) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00003666 void* chunk =
Steve Block3ce2e202009-11-05 08:53:23 +00003667 MemoryAllocator::ReserveInitialChunk(4 * reserved_semispace_size_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003668 if (chunk == NULL) return false;
3669
3670 // Align the pair of semispaces to their size, which must be a power
3671 // of 2.
Steve Blocka7e24c12009-10-30 11:49:00 +00003672 Address new_space_start =
Steve Block3ce2e202009-11-05 08:53:23 +00003673 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
3674 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
3675 return false;
3676 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003677
3678 // Initialize old pointer space.
3679 old_pointer_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003680 new OldSpace(max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003681 if (old_pointer_space_ == NULL) return false;
3682 if (!old_pointer_space_->Setup(NULL, 0)) return false;
3683
3684 // Initialize old data space.
3685 old_data_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003686 new OldSpace(max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003687 if (old_data_space_ == NULL) return false;
3688 if (!old_data_space_->Setup(NULL, 0)) return false;
3689
3690 // Initialize the code space, set its maximum capacity to the old
3691 // generation size. It needs executable memory.
3692 // On 64-bit platform(s), we put all code objects in a 2 GB range of
3693 // virtual address space, so that they can call each other with near calls.
3694 if (code_range_size_ > 0) {
3695 if (!CodeRange::Setup(code_range_size_)) {
3696 return false;
3697 }
3698 }
3699
3700 code_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003701 new OldSpace(max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003702 if (code_space_ == NULL) return false;
3703 if (!code_space_->Setup(NULL, 0)) return false;
3704
3705 // Initialize map space.
Leon Clarkee46be812010-01-19 14:06:41 +00003706 map_space_ = new MapSpace(FLAG_use_big_map_space
3707 ? max_old_generation_size_
Leon Clarked91b9f72010-01-27 17:25:45 +00003708 : MapSpace::kMaxMapPageIndex * Page::kPageSize,
3709 FLAG_max_map_space_pages,
Leon Clarkee46be812010-01-19 14:06:41 +00003710 MAP_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003711 if (map_space_ == NULL) return false;
3712 if (!map_space_->Setup(NULL, 0)) return false;
3713
3714 // Initialize global property cell space.
Steve Block3ce2e202009-11-05 08:53:23 +00003715 cell_space_ = new CellSpace(max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003716 if (cell_space_ == NULL) return false;
3717 if (!cell_space_->Setup(NULL, 0)) return false;
3718
3719 // The large object code space may contain code or data. We set the memory
3720 // to be non-executable here for safety, but this means we need to enable it
3721 // explicitly when allocating large code objects.
3722 lo_space_ = new LargeObjectSpace(LO_SPACE);
3723 if (lo_space_ == NULL) return false;
3724 if (!lo_space_->Setup()) return false;
3725
3726 if (create_heap_objects) {
3727 // Create initial maps.
3728 if (!CreateInitialMaps()) return false;
3729 if (!CreateApiObjects()) return false;
3730
3731 // Create initial objects
3732 if (!CreateInitialObjects()) return false;
3733 }
3734
3735 LOG(IntEvent("heap-capacity", Capacity()));
3736 LOG(IntEvent("heap-available", Available()));
3737
Steve Block3ce2e202009-11-05 08:53:23 +00003738#ifdef ENABLE_LOGGING_AND_PROFILING
3739 // This should be called only after initial objects have been created.
3740 ProducerHeapProfile::Setup();
3741#endif
3742
Steve Blocka7e24c12009-10-30 11:49:00 +00003743 return true;
3744}
3745
3746
Steve Blockd0582a62009-12-15 09:54:21 +00003747void Heap::SetStackLimits() {
Steve Blocka7e24c12009-10-30 11:49:00 +00003748 // On 64 bit machines, pointers are generally out of range of Smis. We write
3749 // something that looks like an out of range Smi to the GC.
3750
Steve Blockd0582a62009-12-15 09:54:21 +00003751 // Set up the special root array entries containing the stack limits.
3752 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00003753 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00003754 reinterpret_cast<Object*>(
3755 (StackGuard::jslimit() & ~kSmiTagMask) | kSmiTag);
3756 roots_[kRealStackLimitRootIndex] =
3757 reinterpret_cast<Object*>(
3758 (StackGuard::real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00003759}
3760
3761
3762void Heap::TearDown() {
3763 GlobalHandles::TearDown();
3764
Leon Clarkee46be812010-01-19 14:06:41 +00003765 ExternalStringTable::TearDown();
3766
Steve Blocka7e24c12009-10-30 11:49:00 +00003767 new_space_.TearDown();
3768
3769 if (old_pointer_space_ != NULL) {
3770 old_pointer_space_->TearDown();
3771 delete old_pointer_space_;
3772 old_pointer_space_ = NULL;
3773 }
3774
3775 if (old_data_space_ != NULL) {
3776 old_data_space_->TearDown();
3777 delete old_data_space_;
3778 old_data_space_ = NULL;
3779 }
3780
3781 if (code_space_ != NULL) {
3782 code_space_->TearDown();
3783 delete code_space_;
3784 code_space_ = NULL;
3785 }
3786
3787 if (map_space_ != NULL) {
3788 map_space_->TearDown();
3789 delete map_space_;
3790 map_space_ = NULL;
3791 }
3792
3793 if (cell_space_ != NULL) {
3794 cell_space_->TearDown();
3795 delete cell_space_;
3796 cell_space_ = NULL;
3797 }
3798
3799 if (lo_space_ != NULL) {
3800 lo_space_->TearDown();
3801 delete lo_space_;
3802 lo_space_ = NULL;
3803 }
3804
3805 MemoryAllocator::TearDown();
3806}
3807
3808
3809void Heap::Shrink() {
3810 // Try to shrink all paged spaces.
3811 PagedSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00003812 for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next())
3813 space->Shrink();
Steve Blocka7e24c12009-10-30 11:49:00 +00003814}
3815
3816
3817#ifdef ENABLE_HEAP_PROTECTION
3818
3819void Heap::Protect() {
3820 if (HasBeenSetup()) {
3821 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00003822 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3823 space->Protect();
Steve Blocka7e24c12009-10-30 11:49:00 +00003824 }
3825}
3826
3827
3828void Heap::Unprotect() {
3829 if (HasBeenSetup()) {
3830 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00003831 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3832 space->Unprotect();
Steve Blocka7e24c12009-10-30 11:49:00 +00003833 }
3834}
3835
3836#endif
3837
3838
Steve Block6ded16b2010-05-10 14:33:55 +01003839void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
3840 ASSERT(callback != NULL);
3841 GCPrologueCallbackPair pair(callback, gc_type);
3842 ASSERT(!gc_prologue_callbacks_.Contains(pair));
3843 return gc_prologue_callbacks_.Add(pair);
3844}
3845
3846
3847void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
3848 ASSERT(callback != NULL);
3849 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
3850 if (gc_prologue_callbacks_[i].callback == callback) {
3851 gc_prologue_callbacks_.Remove(i);
3852 return;
3853 }
3854 }
3855 UNREACHABLE();
3856}
3857
3858
3859void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
3860 ASSERT(callback != NULL);
3861 GCEpilogueCallbackPair pair(callback, gc_type);
3862 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
3863 return gc_epilogue_callbacks_.Add(pair);
3864}
3865
3866
3867void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
3868 ASSERT(callback != NULL);
3869 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
3870 if (gc_epilogue_callbacks_[i].callback == callback) {
3871 gc_epilogue_callbacks_.Remove(i);
3872 return;
3873 }
3874 }
3875 UNREACHABLE();
3876}
3877
3878
Steve Blocka7e24c12009-10-30 11:49:00 +00003879#ifdef DEBUG
3880
3881class PrintHandleVisitor: public ObjectVisitor {
3882 public:
3883 void VisitPointers(Object** start, Object** end) {
3884 for (Object** p = start; p < end; p++)
3885 PrintF(" handle %p to %p\n", p, *p);
3886 }
3887};
3888
3889void Heap::PrintHandles() {
3890 PrintF("Handles:\n");
3891 PrintHandleVisitor v;
3892 HandleScopeImplementer::Iterate(&v);
3893}
3894
3895#endif
3896
3897
3898Space* AllSpaces::next() {
3899 switch (counter_++) {
3900 case NEW_SPACE:
3901 return Heap::new_space();
3902 case OLD_POINTER_SPACE:
3903 return Heap::old_pointer_space();
3904 case OLD_DATA_SPACE:
3905 return Heap::old_data_space();
3906 case CODE_SPACE:
3907 return Heap::code_space();
3908 case MAP_SPACE:
3909 return Heap::map_space();
3910 case CELL_SPACE:
3911 return Heap::cell_space();
3912 case LO_SPACE:
3913 return Heap::lo_space();
3914 default:
3915 return NULL;
3916 }
3917}
3918
3919
3920PagedSpace* PagedSpaces::next() {
3921 switch (counter_++) {
3922 case OLD_POINTER_SPACE:
3923 return Heap::old_pointer_space();
3924 case OLD_DATA_SPACE:
3925 return Heap::old_data_space();
3926 case CODE_SPACE:
3927 return Heap::code_space();
3928 case MAP_SPACE:
3929 return Heap::map_space();
3930 case CELL_SPACE:
3931 return Heap::cell_space();
3932 default:
3933 return NULL;
3934 }
3935}
3936
3937
3938
3939OldSpace* OldSpaces::next() {
3940 switch (counter_++) {
3941 case OLD_POINTER_SPACE:
3942 return Heap::old_pointer_space();
3943 case OLD_DATA_SPACE:
3944 return Heap::old_data_space();
3945 case CODE_SPACE:
3946 return Heap::code_space();
3947 default:
3948 return NULL;
3949 }
3950}
3951
3952
3953SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3954}
3955
3956
3957SpaceIterator::~SpaceIterator() {
3958 // Delete active iterator if any.
3959 delete iterator_;
3960}
3961
3962
3963bool SpaceIterator::has_next() {
3964 // Iterate until no more spaces.
3965 return current_space_ != LAST_SPACE;
3966}
3967
3968
3969ObjectIterator* SpaceIterator::next() {
3970 if (iterator_ != NULL) {
3971 delete iterator_;
3972 iterator_ = NULL;
3973 // Move to the next space
3974 current_space_++;
3975 if (current_space_ > LAST_SPACE) {
3976 return NULL;
3977 }
3978 }
3979
3980 // Return iterator for the new current space.
3981 return CreateIterator();
3982}
3983
3984
3985// Create an iterator for the space to iterate.
3986ObjectIterator* SpaceIterator::CreateIterator() {
3987 ASSERT(iterator_ == NULL);
3988
3989 switch (current_space_) {
3990 case NEW_SPACE:
3991 iterator_ = new SemiSpaceIterator(Heap::new_space());
3992 break;
3993 case OLD_POINTER_SPACE:
3994 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3995 break;
3996 case OLD_DATA_SPACE:
3997 iterator_ = new HeapObjectIterator(Heap::old_data_space());
3998 break;
3999 case CODE_SPACE:
4000 iterator_ = new HeapObjectIterator(Heap::code_space());
4001 break;
4002 case MAP_SPACE:
4003 iterator_ = new HeapObjectIterator(Heap::map_space());
4004 break;
4005 case CELL_SPACE:
4006 iterator_ = new HeapObjectIterator(Heap::cell_space());
4007 break;
4008 case LO_SPACE:
4009 iterator_ = new LargeObjectIterator(Heap::lo_space());
4010 break;
4011 }
4012
4013 // Return the newly allocated iterator;
4014 ASSERT(iterator_ != NULL);
4015 return iterator_;
4016}
4017
4018
4019HeapIterator::HeapIterator() {
4020 Init();
4021}
4022
4023
4024HeapIterator::~HeapIterator() {
4025 Shutdown();
4026}
4027
4028
4029void HeapIterator::Init() {
4030 // Start the iteration.
4031 space_iterator_ = new SpaceIterator();
4032 object_iterator_ = space_iterator_->next();
4033}
4034
4035
4036void HeapIterator::Shutdown() {
4037 // Make sure the last iterator is deallocated.
4038 delete space_iterator_;
4039 space_iterator_ = NULL;
4040 object_iterator_ = NULL;
4041}
4042
4043
Leon Clarked91b9f72010-01-27 17:25:45 +00004044HeapObject* HeapIterator::next() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004045 // No iterator means we are done.
Leon Clarked91b9f72010-01-27 17:25:45 +00004046 if (object_iterator_ == NULL) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00004047
Leon Clarked91b9f72010-01-27 17:25:45 +00004048 if (HeapObject* obj = object_iterator_->next_object()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004049 // If the current iterator has more objects we are fine.
Leon Clarked91b9f72010-01-27 17:25:45 +00004050 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00004051 } else {
4052 // Go though the spaces looking for one that has objects.
4053 while (space_iterator_->has_next()) {
4054 object_iterator_ = space_iterator_->next();
Leon Clarked91b9f72010-01-27 17:25:45 +00004055 if (HeapObject* obj = object_iterator_->next_object()) {
4056 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00004057 }
4058 }
4059 }
4060 // Done with the last space.
4061 object_iterator_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00004062 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00004063}
4064
4065
4066void HeapIterator::reset() {
4067 // Restart the iterator.
4068 Shutdown();
4069 Init();
4070}
4071
4072
4073#ifdef DEBUG
4074
4075static bool search_for_any_global;
4076static Object* search_target;
4077static bool found_target;
4078static List<Object*> object_stack(20);
4079
4080
4081// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
4082static const int kMarkTag = 2;
4083
4084static void MarkObjectRecursively(Object** p);
4085class MarkObjectVisitor : public ObjectVisitor {
4086 public:
4087 void VisitPointers(Object** start, Object** end) {
4088 // Copy all HeapObject pointers in [start, end)
4089 for (Object** p = start; p < end; p++) {
4090 if ((*p)->IsHeapObject())
4091 MarkObjectRecursively(p);
4092 }
4093 }
4094};
4095
4096static MarkObjectVisitor mark_visitor;
4097
4098static void MarkObjectRecursively(Object** p) {
4099 if (!(*p)->IsHeapObject()) return;
4100
4101 HeapObject* obj = HeapObject::cast(*p);
4102
4103 Object* map = obj->map();
4104
4105 if (!map->IsHeapObject()) return; // visited before
4106
4107 if (found_target) return; // stop if target found
4108 object_stack.Add(obj);
4109 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
4110 (!search_for_any_global && (obj == search_target))) {
4111 found_target = true;
4112 return;
4113 }
4114
4115 // not visited yet
4116 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
4117
4118 Address map_addr = map_p->address();
4119
4120 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
4121
4122 MarkObjectRecursively(&map);
4123
4124 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
4125 &mark_visitor);
4126
4127 if (!found_target) // don't pop if found the target
4128 object_stack.RemoveLast();
4129}
4130
4131
4132static void UnmarkObjectRecursively(Object** p);
4133class UnmarkObjectVisitor : public ObjectVisitor {
4134 public:
4135 void VisitPointers(Object** start, Object** end) {
4136 // Copy all HeapObject pointers in [start, end)
4137 for (Object** p = start; p < end; p++) {
4138 if ((*p)->IsHeapObject())
4139 UnmarkObjectRecursively(p);
4140 }
4141 }
4142};
4143
4144static UnmarkObjectVisitor unmark_visitor;
4145
4146static void UnmarkObjectRecursively(Object** p) {
4147 if (!(*p)->IsHeapObject()) return;
4148
4149 HeapObject* obj = HeapObject::cast(*p);
4150
4151 Object* map = obj->map();
4152
4153 if (map->IsHeapObject()) return; // unmarked already
4154
4155 Address map_addr = reinterpret_cast<Address>(map);
4156
4157 map_addr -= kMarkTag;
4158
4159 ASSERT_TAG_ALIGNED(map_addr);
4160
4161 HeapObject* map_p = HeapObject::FromAddress(map_addr);
4162
4163 obj->set_map(reinterpret_cast<Map*>(map_p));
4164
4165 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
4166
4167 obj->IterateBody(Map::cast(map_p)->instance_type(),
4168 obj->SizeFromMap(Map::cast(map_p)),
4169 &unmark_visitor);
4170}
4171
4172
4173static void MarkRootObjectRecursively(Object** root) {
4174 if (search_for_any_global) {
4175 ASSERT(search_target == NULL);
4176 } else {
4177 ASSERT(search_target->IsHeapObject());
4178 }
4179 found_target = false;
4180 object_stack.Clear();
4181
4182 MarkObjectRecursively(root);
4183 UnmarkObjectRecursively(root);
4184
4185 if (found_target) {
4186 PrintF("=====================================\n");
4187 PrintF("==== Path to object ====\n");
4188 PrintF("=====================================\n\n");
4189
4190 ASSERT(!object_stack.is_empty());
4191 for (int i = 0; i < object_stack.length(); i++) {
4192 if (i > 0) PrintF("\n |\n |\n V\n\n");
4193 Object* obj = object_stack[i];
4194 obj->Print();
4195 }
4196 PrintF("=====================================\n");
4197 }
4198}
4199
4200
4201// Helper class for visiting HeapObjects recursively.
4202class MarkRootVisitor: public ObjectVisitor {
4203 public:
4204 void VisitPointers(Object** start, Object** end) {
4205 // Visit all HeapObject pointers in [start, end)
4206 for (Object** p = start; p < end; p++) {
4207 if ((*p)->IsHeapObject())
4208 MarkRootObjectRecursively(p);
4209 }
4210 }
4211};
4212
4213
4214// Triggers a depth-first traversal of reachable objects from roots
4215// and finds a path to a specific heap object and prints it.
Leon Clarkee46be812010-01-19 14:06:41 +00004216void Heap::TracePathToObject(Object* target) {
4217 search_target = target;
Steve Blocka7e24c12009-10-30 11:49:00 +00004218 search_for_any_global = false;
4219
4220 MarkRootVisitor root_visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00004221 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00004222}
4223
4224
4225// Triggers a depth-first traversal of reachable objects from roots
4226// and finds a path to any global object and prints it. Useful for
4227// determining the source for leaks of global objects.
4228void Heap::TracePathToGlobal() {
4229 search_target = NULL;
4230 search_for_any_global = true;
4231
4232 MarkRootVisitor root_visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00004233 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00004234}
4235#endif
4236
4237
4238GCTracer::GCTracer()
4239 : start_time_(0.0),
4240 start_size_(0.0),
Steve Block6ded16b2010-05-10 14:33:55 +01004241 external_time_(0.0),
Steve Blocka7e24c12009-10-30 11:49:00 +00004242 gc_count_(0),
4243 full_gc_count_(0),
4244 is_compacting_(false),
4245 marked_count_(0) {
4246 // These two fields reflect the state of the previous full collection.
4247 // Set them before they are changed by the collector.
4248 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
4249 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
4250 if (!FLAG_trace_gc) return;
4251 start_time_ = OS::TimeCurrentMillis();
4252 start_size_ = SizeOfHeapObjects();
4253}
4254
4255
4256GCTracer::~GCTracer() {
4257 if (!FLAG_trace_gc) return;
4258 // Printf ONE line iff flag is set.
Steve Block6ded16b2010-05-10 14:33:55 +01004259 int time = static_cast<int>(OS::TimeCurrentMillis() - start_time_);
4260 int external_time = static_cast<int>(external_time_);
4261 PrintF("%s %.1f -> %.1f MB, ",
4262 CollectorString(), start_size_, SizeOfHeapObjects());
4263 if (external_time > 0) PrintF("%d / ", external_time);
4264 PrintF("%d ms.\n", time);
Steve Blocka7e24c12009-10-30 11:49:00 +00004265
4266#if defined(ENABLE_LOGGING_AND_PROFILING)
4267 Heap::PrintShortHeapStatistics();
4268#endif
4269}
4270
4271
4272const char* GCTracer::CollectorString() {
4273 switch (collector_) {
4274 case SCAVENGER:
4275 return "Scavenge";
4276 case MARK_COMPACTOR:
4277 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
4278 : "Mark-sweep";
4279 }
4280 return "Unknown GC";
4281}
4282
4283
4284int KeyedLookupCache::Hash(Map* map, String* name) {
4285 // Uses only lower 32 bits if pointers are larger.
4286 uintptr_t addr_hash =
Leon Clarkee46be812010-01-19 14:06:41 +00004287 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
Andrei Popescu402d9372010-02-26 13:31:12 +00004288 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
Steve Blocka7e24c12009-10-30 11:49:00 +00004289}
4290
4291
4292int KeyedLookupCache::Lookup(Map* map, String* name) {
4293 int index = Hash(map, name);
4294 Key& key = keys_[index];
4295 if ((key.map == map) && key.name->Equals(name)) {
4296 return field_offsets_[index];
4297 }
4298 return -1;
4299}
4300
4301
4302void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
4303 String* symbol;
4304 if (Heap::LookupSymbolIfExists(name, &symbol)) {
4305 int index = Hash(map, symbol);
4306 Key& key = keys_[index];
4307 key.map = map;
4308 key.name = symbol;
4309 field_offsets_[index] = field_offset;
4310 }
4311}
4312
4313
4314void KeyedLookupCache::Clear() {
4315 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
4316}
4317
4318
4319KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
4320
4321
4322int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
4323
4324
4325void DescriptorLookupCache::Clear() {
4326 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
4327}
4328
4329
4330DescriptorLookupCache::Key
4331DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
4332
4333int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
4334
4335
4336#ifdef DEBUG
4337bool Heap::GarbageCollectionGreedyCheck() {
4338 ASSERT(FLAG_gc_greedy);
4339 if (Bootstrapper::IsActive()) return true;
4340 if (disallow_allocation_failure()) return true;
4341 return CollectGarbage(0, NEW_SPACE);
4342}
4343#endif
4344
4345
4346TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
4347 : type_(t) {
4348 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
4349 uint32_t in1 = 0xffffffffu; // generated by the FPU.
4350 for (int i = 0; i < kCacheSize; i++) {
4351 elements_[i].in[0] = in0;
4352 elements_[i].in[1] = in1;
4353 elements_[i].output = NULL;
4354 }
4355}
4356
4357
4358TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
4359
4360
4361void TranscendentalCache::Clear() {
4362 for (int i = 0; i < kNumberOfCaches; i++) {
4363 if (caches_[i] != NULL) {
4364 delete caches_[i];
4365 caches_[i] = NULL;
4366 }
4367 }
4368}
4369
4370
Leon Clarkee46be812010-01-19 14:06:41 +00004371void ExternalStringTable::CleanUp() {
4372 int last = 0;
4373 for (int i = 0; i < new_space_strings_.length(); ++i) {
4374 if (new_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4375 if (Heap::InNewSpace(new_space_strings_[i])) {
4376 new_space_strings_[last++] = new_space_strings_[i];
4377 } else {
4378 old_space_strings_.Add(new_space_strings_[i]);
4379 }
4380 }
4381 new_space_strings_.Rewind(last);
4382 last = 0;
4383 for (int i = 0; i < old_space_strings_.length(); ++i) {
4384 if (old_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4385 ASSERT(!Heap::InNewSpace(old_space_strings_[i]));
4386 old_space_strings_[last++] = old_space_strings_[i];
4387 }
4388 old_space_strings_.Rewind(last);
4389 Verify();
4390}
4391
4392
4393void ExternalStringTable::TearDown() {
4394 new_space_strings_.Free();
4395 old_space_strings_.Free();
4396}
4397
4398
4399List<Object*> ExternalStringTable::new_space_strings_;
4400List<Object*> ExternalStringTable::old_space_strings_;
4401
Steve Blocka7e24c12009-10-30 11:49:00 +00004402} } // namespace v8::internal