Merge remote-tracking branch 'ry/v0.8' into master
[platform/upstream/nodejs.git] / deps / v8 / src / heap.cc
1 // Copyright 2012 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.h"
34 #include "compilation-cache.h"
35 #include "debug.h"
36 #include "deoptimizer.h"
37 #include "global-handles.h"
38 #include "heap-profiler.h"
39 #include "incremental-marking.h"
40 #include "liveobjectlist-inl.h"
41 #include "mark-compact.h"
42 #include "natives.h"
43 #include "objects-visiting.h"
44 #include "objects-visiting-inl.h"
45 #include "once.h"
46 #include "runtime-profiler.h"
47 #include "scopeinfo.h"
48 #include "snapshot.h"
49 #include "store-buffer.h"
50 #include "v8threads.h"
51 #include "vm-state-inl.h"
52 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
53 #include "regexp-macro-assembler.h"
54 #include "arm/regexp-macro-assembler-arm.h"
55 #endif
56 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
57 #include "regexp-macro-assembler.h"
58 #include "mips/regexp-macro-assembler-mips.h"
59 #endif
60
61 namespace v8 {
62 namespace internal {
63
64
65 Heap::Heap()
66     : isolate_(NULL),
67 // semispace_size_ should be a power of 2 and old_generation_size_ should be
68 // a multiple of Page::kPageSize.
69 #if defined(V8_TARGET_ARCH_X64)
70 #define LUMP_OF_MEMORY (2 * MB)
71       code_range_size_(512*MB),
72 #else
73 #define LUMP_OF_MEMORY MB
74       code_range_size_(0),
75 #endif
76 #if defined(ANDROID)
77       reserved_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
78       max_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
79       initial_semispace_size_(Page::kPageSize),
80       max_old_generation_size_(192*MB),
81       max_executable_size_(max_old_generation_size_),
82 #else
83       reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
84       max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
85       initial_semispace_size_(Page::kPageSize),
86       max_old_generation_size_(700ul * LUMP_OF_MEMORY),
87       max_executable_size_(256l * LUMP_OF_MEMORY),
88 #endif
89
90 // Variables set based on semispace_size_ and old_generation_size_ in
91 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
92 // Will be 4 * reserved_semispace_size_ to ensure that young
93 // generation can be aligned to its size.
94       survived_since_last_expansion_(0),
95       sweep_generation_(0),
96       always_allocate_scope_depth_(0),
97       linear_allocation_scope_depth_(0),
98       contexts_disposed_(0),
99       global_ic_age_(0),
100       scan_on_scavenge_pages_(0),
101       new_space_(this),
102       old_pointer_space_(NULL),
103       old_data_space_(NULL),
104       code_space_(NULL),
105       map_space_(NULL),
106       cell_space_(NULL),
107       lo_space_(NULL),
108       gc_state_(NOT_IN_GC),
109       gc_post_processing_depth_(0),
110       ms_count_(0),
111       gc_count_(0),
112       remembered_unmapped_pages_index_(0),
113       unflattened_strings_length_(0),
114 #ifdef DEBUG
115       allocation_allowed_(true),
116       allocation_timeout_(0),
117       disallow_allocation_failure_(false),
118       debug_utils_(NULL),
119 #endif  // DEBUG
120       new_space_high_promotion_mode_active_(false),
121       old_gen_promotion_limit_(kMinimumPromotionLimit),
122       old_gen_allocation_limit_(kMinimumAllocationLimit),
123       old_gen_limit_factor_(1),
124       size_of_old_gen_at_last_old_space_gc_(0),
125       external_allocation_limit_(0),
126       amount_of_external_allocated_memory_(0),
127       amount_of_external_allocated_memory_at_last_global_gc_(0),
128       old_gen_exhausted_(false),
129       store_buffer_rebuilder_(store_buffer()),
130       hidden_symbol_(NULL),
131       global_gc_prologue_callback_(NULL),
132       global_gc_epilogue_callback_(NULL),
133       gc_safe_size_of_old_object_(NULL),
134       total_regexp_code_generated_(0),
135       tracer_(NULL),
136       young_survivors_after_last_gc_(0),
137       high_survival_rate_period_length_(0),
138       survival_rate_(0),
139       previous_survival_rate_trend_(Heap::STABLE),
140       survival_rate_trend_(Heap::STABLE),
141       max_gc_pause_(0),
142       total_gc_time_ms_(0),
143       max_alive_after_gc_(0),
144       min_in_mutator_(kMaxInt),
145       alive_after_last_gc_(0),
146       last_gc_end_timestamp_(0.0),
147       store_buffer_(this),
148       marking_(this),
149       incremental_marking_(this),
150       number_idle_notifications_(0),
151       last_idle_notification_gc_count_(0),
152       last_idle_notification_gc_count_init_(false),
153       mark_sweeps_since_idle_round_started_(0),
154       ms_count_at_last_idle_notification_(0),
155       gc_count_at_last_idle_gc_(0),
156       scavenges_since_last_idle_round_(kIdleScavengeThreshold),
157       promotion_queue_(this),
158       configured_(false),
159       chunks_queued_for_free_(NULL),
160       relocation_mutex_(NULL) {
161   // Allow build-time customization of the max semispace size. Building
162   // V8 with snapshots and a non-default max semispace size is much
163   // easier if you can define it as part of the build environment.
164 #if defined(V8_MAX_SEMISPACE_SIZE)
165   max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
166 #endif
167
168   intptr_t max_virtual = OS::MaxVirtualMemory();
169
170   if (max_virtual > 0) {
171     if (code_range_size_ > 0) {
172       // Reserve no more than 1/8 of the memory for the code range.
173       code_range_size_ = Min(code_range_size_, max_virtual >> 3);
174     }
175   }
176
177   memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
178   native_contexts_list_ = NULL;
179   mark_compact_collector_.heap_ = this;
180   external_string_table_.heap_ = this;
181   // Put a dummy entry in the remembered pages so we can find the list the
182   // minidump even if there are no real unmapped pages.
183   RememberUnmappedPage(NULL, false);
184
185   ClearObjectStats(true);
186 }
187
188
189 intptr_t Heap::Capacity() {
190   if (!HasBeenSetUp()) return 0;
191
192   return new_space_.Capacity() +
193       old_pointer_space_->Capacity() +
194       old_data_space_->Capacity() +
195       code_space_->Capacity() +
196       map_space_->Capacity() +
197       cell_space_->Capacity();
198 }
199
200
201 intptr_t Heap::CommittedMemory() {
202   if (!HasBeenSetUp()) return 0;
203
204   return new_space_.CommittedMemory() +
205       old_pointer_space_->CommittedMemory() +
206       old_data_space_->CommittedMemory() +
207       code_space_->CommittedMemory() +
208       map_space_->CommittedMemory() +
209       cell_space_->CommittedMemory() +
210       lo_space_->Size();
211 }
212
213 intptr_t Heap::CommittedMemoryExecutable() {
214   if (!HasBeenSetUp()) return 0;
215
216   return isolate()->memory_allocator()->SizeExecutable();
217 }
218
219
220 intptr_t Heap::Available() {
221   if (!HasBeenSetUp()) return 0;
222
223   return new_space_.Available() +
224       old_pointer_space_->Available() +
225       old_data_space_->Available() +
226       code_space_->Available() +
227       map_space_->Available() +
228       cell_space_->Available();
229 }
230
231
232 bool Heap::HasBeenSetUp() {
233   return old_pointer_space_ != NULL &&
234          old_data_space_ != NULL &&
235          code_space_ != NULL &&
236          map_space_ != NULL &&
237          cell_space_ != NULL &&
238          lo_space_ != NULL;
239 }
240
241
242 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
243   if (IntrusiveMarking::IsMarked(object)) {
244     return IntrusiveMarking::SizeOfMarkedObject(object);
245   }
246   return object->SizeFromMap(object->map());
247 }
248
249
250 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
251                                               const char** reason) {
252   // Is global GC requested?
253   if (space != NEW_SPACE) {
254     isolate_->counters()->gc_compactor_caused_by_request()->Increment();
255     *reason = "GC in old space requested";
256     return MARK_COMPACTOR;
257   }
258
259   if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
260     *reason = "GC in old space forced by flags";
261     return MARK_COMPACTOR;
262   }
263
264   // Is enough data promoted to justify a global GC?
265   if (OldGenerationPromotionLimitReached()) {
266     isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
267     *reason = "promotion limit reached";
268     return MARK_COMPACTOR;
269   }
270
271   // Have allocation in OLD and LO failed?
272   if (old_gen_exhausted_) {
273     isolate_->counters()->
274         gc_compactor_caused_by_oldspace_exhaustion()->Increment();
275     *reason = "old generations exhausted";
276     return MARK_COMPACTOR;
277   }
278
279   // Is there enough space left in OLD to guarantee that a scavenge can
280   // succeed?
281   //
282   // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
283   // for object promotion. It counts only the bytes that the memory
284   // allocator has not yet allocated from the OS and assigned to any space,
285   // and does not count available bytes already in the old space or code
286   // space.  Undercounting is safe---we may get an unrequested full GC when
287   // a scavenge would have succeeded.
288   if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
289     isolate_->counters()->
290         gc_compactor_caused_by_oldspace_exhaustion()->Increment();
291     *reason = "scavenge might not succeed";
292     return MARK_COMPACTOR;
293   }
294
295   // Default
296   *reason = NULL;
297   return SCAVENGER;
298 }
299
300
301 // TODO(1238405): Combine the infrastructure for --heap-stats and
302 // --log-gc to avoid the complicated preprocessor and flag testing.
303 void Heap::ReportStatisticsBeforeGC() {
304   // Heap::ReportHeapStatistics will also log NewSpace statistics when
305   // compiled --log-gc is set.  The following logic is used to avoid
306   // double logging.
307 #ifdef DEBUG
308   if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
309   if (FLAG_heap_stats) {
310     ReportHeapStatistics("Before GC");
311   } else if (FLAG_log_gc) {
312     new_space_.ReportStatistics();
313   }
314   if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
315 #else
316   if (FLAG_log_gc) {
317     new_space_.CollectStatistics();
318     new_space_.ReportStatistics();
319     new_space_.ClearHistograms();
320   }
321 #endif  // DEBUG
322 }
323
324
325 void Heap::PrintShortHeapStatistics() {
326   if (!FLAG_trace_gc_verbose) return;
327   PrintPID("Memory allocator,   used: %6" V8_PTR_PREFIX "d KB"
328                ", available: %6" V8_PTR_PREFIX "d KB\n",
329            isolate_->memory_allocator()->Size() / KB,
330            isolate_->memory_allocator()->Available() / KB);
331   PrintPID("New space,          used: %6" V8_PTR_PREFIX "d KB"
332                ", available: %6" V8_PTR_PREFIX "d KB"
333                ", committed: %6" V8_PTR_PREFIX "d KB\n",
334            new_space_.Size() / KB,
335            new_space_.Available() / KB,
336            new_space_.CommittedMemory() / KB);
337   PrintPID("Old pointers,       used: %6" V8_PTR_PREFIX "d KB"
338                ", available: %6" V8_PTR_PREFIX "d KB"
339                ", committed: %6" V8_PTR_PREFIX "d KB\n",
340            old_pointer_space_->SizeOfObjects() / KB,
341            old_pointer_space_->Available() / KB,
342            old_pointer_space_->CommittedMemory() / KB);
343   PrintPID("Old data space,     used: %6" V8_PTR_PREFIX "d KB"
344                ", available: %6" V8_PTR_PREFIX "d KB"
345                ", committed: %6" V8_PTR_PREFIX "d KB\n",
346            old_data_space_->SizeOfObjects() / KB,
347            old_data_space_->Available() / KB,
348            old_data_space_->CommittedMemory() / KB);
349   PrintPID("Code space,         used: %6" V8_PTR_PREFIX "d KB"
350                ", available: %6" V8_PTR_PREFIX "d KB"
351                ", committed: %6" V8_PTR_PREFIX "d KB\n",
352            code_space_->SizeOfObjects() / KB,
353            code_space_->Available() / KB,
354            code_space_->CommittedMemory() / KB);
355   PrintPID("Map space,          used: %6" V8_PTR_PREFIX "d KB"
356                ", available: %6" V8_PTR_PREFIX "d KB"
357                ", committed: %6" V8_PTR_PREFIX "d KB\n",
358            map_space_->SizeOfObjects() / KB,
359            map_space_->Available() / KB,
360            map_space_->CommittedMemory() / KB);
361   PrintPID("Cell space,         used: %6" V8_PTR_PREFIX "d KB"
362                ", available: %6" V8_PTR_PREFIX "d KB"
363                ", committed: %6" V8_PTR_PREFIX "d KB\n",
364            cell_space_->SizeOfObjects() / KB,
365            cell_space_->Available() / KB,
366            cell_space_->CommittedMemory() / KB);
367   PrintPID("Large object space, used: %6" V8_PTR_PREFIX "d KB"
368                ", available: %6" V8_PTR_PREFIX "d KB"
369                ", committed: %6" V8_PTR_PREFIX "d KB\n",
370            lo_space_->SizeOfObjects() / KB,
371            lo_space_->Available() / KB,
372            lo_space_->CommittedMemory() / KB);
373   PrintPID("Total time spent in GC  : %d ms\n", total_gc_time_ms_);
374 }
375
376
377 // TODO(1238405): Combine the infrastructure for --heap-stats and
378 // --log-gc to avoid the complicated preprocessor and flag testing.
379 void Heap::ReportStatisticsAfterGC() {
380   // Similar to the before GC, we use some complicated logic to ensure that
381   // NewSpace statistics are logged exactly once when --log-gc is turned on.
382 #if defined(DEBUG)
383   if (FLAG_heap_stats) {
384     new_space_.CollectStatistics();
385     ReportHeapStatistics("After GC");
386   } else if (FLAG_log_gc) {
387     new_space_.ReportStatistics();
388   }
389 #else
390   if (FLAG_log_gc) new_space_.ReportStatistics();
391 #endif  // DEBUG
392 }
393
394
395 void Heap::GarbageCollectionPrologue() {
396   isolate_->transcendental_cache()->Clear();
397   ClearJSFunctionResultCaches();
398   gc_count_++;
399   unflattened_strings_length_ = 0;
400 #ifdef DEBUG
401   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
402   allow_allocation(false);
403
404   if (FLAG_verify_heap) {
405     Verify();
406   }
407
408   if (FLAG_gc_verbose) Print();
409 #endif  // DEBUG
410
411 #if defined(DEBUG)
412   ReportStatisticsBeforeGC();
413 #endif  // DEBUG
414
415   LiveObjectList::GCPrologue();
416   store_buffer()->GCPrologue();
417 }
418
419 intptr_t Heap::SizeOfObjects() {
420   intptr_t total = 0;
421   AllSpaces spaces;
422   for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
423     total += space->SizeOfObjects();
424   }
425   return total;
426 }
427
428 void Heap::GarbageCollectionEpilogue() {
429   store_buffer()->GCEpilogue();
430   LiveObjectList::GCEpilogue();
431 #ifdef DEBUG
432   allow_allocation(true);
433   ZapFromSpace();
434
435   if (FLAG_verify_heap) {
436     Verify();
437   }
438
439   if (FLAG_print_global_handles) isolate_->global_handles()->Print();
440   if (FLAG_print_handles) PrintHandles();
441   if (FLAG_gc_verbose) Print();
442   if (FLAG_code_stats) ReportCodeStatistics("After GC");
443 #endif
444
445   isolate_->counters()->alive_after_last_gc()->Set(
446       static_cast<int>(SizeOfObjects()));
447
448   isolate_->counters()->symbol_table_capacity()->Set(
449       symbol_table()->Capacity());
450   isolate_->counters()->number_of_symbols()->Set(
451       symbol_table()->NumberOfElements());
452
453   if (CommittedMemory() > 0) {
454     isolate_->counters()->external_fragmentation_total()->AddSample(
455         static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory()));
456
457     isolate_->counters()->heap_fraction_map_space()->AddSample(
458         static_cast<int>(
459             (map_space()->CommittedMemory() * 100.0) / CommittedMemory()));
460     isolate_->counters()->heap_fraction_cell_space()->AddSample(
461         static_cast<int>(
462             (cell_space()->CommittedMemory() * 100.0) / CommittedMemory()));
463
464     isolate_->counters()->heap_sample_total_committed()->AddSample(
465         static_cast<int>(CommittedMemory() / KB));
466     isolate_->counters()->heap_sample_total_used()->AddSample(
467         static_cast<int>(SizeOfObjects() / KB));
468     isolate_->counters()->heap_sample_map_space_committed()->AddSample(
469         static_cast<int>(map_space()->CommittedMemory() / KB));
470     isolate_->counters()->heap_sample_cell_space_committed()->AddSample(
471         static_cast<int>(cell_space()->CommittedMemory() / KB));
472   }
473
474 #define UPDATE_COUNTERS_FOR_SPACE(space)                                       \
475   isolate_->counters()->space##_bytes_available()->Set(                        \
476       static_cast<int>(space()->Available()));                                 \
477   isolate_->counters()->space##_bytes_committed()->Set(                        \
478       static_cast<int>(space()->CommittedMemory()));                           \
479   isolate_->counters()->space##_bytes_used()->Set(                             \
480       static_cast<int>(space()->SizeOfObjects()));
481 #define UPDATE_FRAGMENTATION_FOR_SPACE(space)                                  \
482   if (space()->CommittedMemory() > 0) {                                        \
483     isolate_->counters()->external_fragmentation_##space()->AddSample(         \
484         static_cast<int>(100 -                                                 \
485             (space()->SizeOfObjects() * 100.0) / space()->CommittedMemory())); \
486   }
487 #define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space)                     \
488   UPDATE_COUNTERS_FOR_SPACE(space)                                             \
489   UPDATE_FRAGMENTATION_FOR_SPACE(space)
490
491   UPDATE_COUNTERS_FOR_SPACE(new_space)
492   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_pointer_space)
493   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_data_space)
494   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space)
495   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space)
496   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(cell_space)
497   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space)
498 #undef UPDATE_COUNTERS_FOR_SPACE
499 #undef UPDATE_FRAGMENTATION_FOR_SPACE
500 #undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE
501
502 #if defined(DEBUG)
503   ReportStatisticsAfterGC();
504 #endif  // DEBUG
505 #ifdef ENABLE_DEBUGGER_SUPPORT
506   isolate_->debug()->AfterGarbageCollection();
507 #endif  // ENABLE_DEBUGGER_SUPPORT
508 }
509
510
511 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
512   // Since we are ignoring the return value, the exact choice of space does
513   // not matter, so long as we do not specify NEW_SPACE, which would not
514   // cause a full GC.
515   mark_compact_collector_.SetFlags(flags);
516   CollectGarbage(OLD_POINTER_SPACE, gc_reason);
517   mark_compact_collector_.SetFlags(kNoGCFlags);
518 }
519
520
521 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
522   // Since we are ignoring the return value, the exact choice of space does
523   // not matter, so long as we do not specify NEW_SPACE, which would not
524   // cause a full GC.
525   // Major GC would invoke weak handle callbacks on weakly reachable
526   // handles, but won't collect weakly reachable objects until next
527   // major GC.  Therefore if we collect aggressively and weak handle callback
528   // has been invoked, we rerun major GC to release objects which become
529   // garbage.
530   // Note: as weak callbacks can execute arbitrary code, we cannot
531   // hope that eventually there will be no weak callbacks invocations.
532   // Therefore stop recollecting after several attempts.
533   mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
534                                      kReduceMemoryFootprintMask);
535   isolate_->compilation_cache()->Clear();
536   const int kMaxNumberOfAttempts = 7;
537   for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
538     if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
539       break;
540     }
541   }
542   mark_compact_collector()->SetFlags(kNoGCFlags);
543   new_space_.Shrink();
544   UncommitFromSpace();
545   Shrink();
546   incremental_marking()->UncommitMarkingDeque();
547 }
548
549
550 bool Heap::CollectGarbage(AllocationSpace space,
551                           GarbageCollector collector,
552                           const char* gc_reason,
553                           const char* collector_reason) {
554   // The VM is in the GC state until exiting this function.
555   VMState state(isolate_, GC);
556
557 #ifdef DEBUG
558   // Reset the allocation timeout to the GC interval, but make sure to
559   // allow at least a few allocations after a collection. The reason
560   // for this is that we have a lot of allocation sequences and we
561   // assume that a garbage collection will allow the subsequent
562   // allocation attempts to go through.
563   allocation_timeout_ = Max(6, FLAG_gc_interval);
564 #endif
565
566   if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
567     if (FLAG_trace_incremental_marking) {
568       PrintF("[IncrementalMarking] Scavenge during marking.\n");
569     }
570   }
571
572   if (collector == MARK_COMPACTOR &&
573       !mark_compact_collector()->abort_incremental_marking_ &&
574       !incremental_marking()->IsStopped() &&
575       !incremental_marking()->should_hurry() &&
576       FLAG_incremental_marking_steps) {
577     // Make progress in incremental marking.
578     const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
579     incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
580                                 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
581     if (!incremental_marking()->IsComplete()) {
582       if (FLAG_trace_incremental_marking) {
583         PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
584       }
585       collector = SCAVENGER;
586       collector_reason = "incremental marking delaying mark-sweep";
587     }
588   }
589
590   bool next_gc_likely_to_collect_more = false;
591
592   { GCTracer tracer(this, gc_reason, collector_reason);
593     GarbageCollectionPrologue();
594     // The GC count was incremented in the prologue.  Tell the tracer about
595     // it.
596     tracer.set_gc_count(gc_count_);
597
598     // Tell the tracer which collector we've selected.
599     tracer.set_collector(collector);
600
601     HistogramTimer* rate = (collector == SCAVENGER)
602         ? isolate_->counters()->gc_scavenger()
603         : isolate_->counters()->gc_compactor();
604     rate->Start();
605     next_gc_likely_to_collect_more =
606         PerformGarbageCollection(collector, &tracer);
607     rate->Stop();
608
609     GarbageCollectionEpilogue();
610   }
611
612   ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
613   if (incremental_marking()->IsStopped()) {
614     if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
615       incremental_marking()->Start();
616     }
617   }
618
619   return next_gc_likely_to_collect_more;
620 }
621
622
623 void Heap::PerformScavenge() {
624   GCTracer tracer(this, NULL, NULL);
625   if (incremental_marking()->IsStopped()) {
626     PerformGarbageCollection(SCAVENGER, &tracer);
627   } else {
628     PerformGarbageCollection(MARK_COMPACTOR, &tracer);
629   }
630 }
631
632
633 #ifdef DEBUG
634 // Helper class for verifying the symbol table.
635 class SymbolTableVerifier : public ObjectVisitor {
636  public:
637   void VisitPointers(Object** start, Object** end) {
638     // Visit all HeapObject pointers in [start, end).
639     for (Object** p = start; p < end; p++) {
640       if ((*p)->IsHeapObject()) {
641         // Check that the symbol is actually a symbol.
642         ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
643       }
644     }
645   }
646 };
647 #endif  // DEBUG
648
649
650 static void VerifySymbolTable() {
651 #ifdef DEBUG
652   SymbolTableVerifier verifier;
653   HEAP->symbol_table()->IterateElements(&verifier);
654 #endif  // DEBUG
655 }
656
657
658 static bool AbortIncrementalMarkingAndCollectGarbage(
659     Heap* heap,
660     AllocationSpace space,
661     const char* gc_reason = NULL) {
662   heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
663   bool result = heap->CollectGarbage(space, gc_reason);
664   heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
665   return result;
666 }
667
668
669 void Heap::ReserveSpace(
670     int new_space_size,
671     int pointer_space_size,
672     int data_space_size,
673     int code_space_size,
674     int map_space_size,
675     int cell_space_size,
676     int large_object_size) {
677   NewSpace* new_space = Heap::new_space();
678   PagedSpace* old_pointer_space = Heap::old_pointer_space();
679   PagedSpace* old_data_space = Heap::old_data_space();
680   PagedSpace* code_space = Heap::code_space();
681   PagedSpace* map_space = Heap::map_space();
682   PagedSpace* cell_space = Heap::cell_space();
683   LargeObjectSpace* lo_space = Heap::lo_space();
684   bool gc_performed = true;
685   int counter = 0;
686   static const int kThreshold = 20;
687   while (gc_performed && counter++ < kThreshold) {
688     gc_performed = false;
689     if (!new_space->ReserveSpace(new_space_size)) {
690       Heap::CollectGarbage(NEW_SPACE,
691                            "failed to reserve space in the new space");
692       gc_performed = true;
693     }
694     if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
695       AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
696           "failed to reserve space in the old pointer space");
697       gc_performed = true;
698     }
699     if (!(old_data_space->ReserveSpace(data_space_size))) {
700       AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
701           "failed to reserve space in the old data space");
702       gc_performed = true;
703     }
704     if (!(code_space->ReserveSpace(code_space_size))) {
705       AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
706           "failed to reserve space in the code space");
707       gc_performed = true;
708     }
709     if (!(map_space->ReserveSpace(map_space_size))) {
710       AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
711           "failed to reserve space in the map space");
712       gc_performed = true;
713     }
714     if (!(cell_space->ReserveSpace(cell_space_size))) {
715       AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
716           "failed to reserve space in the cell space");
717       gc_performed = true;
718     }
719     // We add a slack-factor of 2 in order to have space for a series of
720     // large-object allocations that are only just larger than the page size.
721     large_object_size *= 2;
722     // The ReserveSpace method on the large object space checks how much
723     // we can expand the old generation.  This includes expansion caused by
724     // allocation in the other spaces.
725     large_object_size += cell_space_size + map_space_size + code_space_size +
726         data_space_size + pointer_space_size;
727     if (!(lo_space->ReserveSpace(large_object_size))) {
728       AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
729           "failed to reserve space in the large object space");
730       gc_performed = true;
731     }
732   }
733
734   if (gc_performed) {
735     // Failed to reserve the space after several attempts.
736     V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
737   }
738 }
739
740
741 void Heap::EnsureFromSpaceIsCommitted() {
742   if (new_space_.CommitFromSpaceIfNeeded()) return;
743
744   // Committing memory to from space failed.
745   // Try shrinking and try again.
746   Shrink();
747   if (new_space_.CommitFromSpaceIfNeeded()) return;
748
749   // Committing memory to from space failed again.
750   // Memory is exhausted and we will die.
751   V8::FatalProcessOutOfMemory("Committing semi space failed.");
752 }
753
754
755 void Heap::ClearJSFunctionResultCaches() {
756   if (isolate_->bootstrapper()->IsActive()) return;
757
758   Object* context = native_contexts_list_;
759   while (!context->IsUndefined()) {
760     // Get the caches for this context. GC can happen when the context
761     // is not fully initialized, so the caches can be undefined.
762     Object* caches_or_undefined =
763         Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
764     if (!caches_or_undefined->IsUndefined()) {
765       FixedArray* caches = FixedArray::cast(caches_or_undefined);
766       // Clear the caches:
767       int length = caches->length();
768       for (int i = 0; i < length; i++) {
769         JSFunctionResultCache::cast(caches->get(i))->Clear();
770       }
771     }
772     // Get the next context:
773     context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
774   }
775 }
776
777
778
779 void Heap::ClearNormalizedMapCaches() {
780   if (isolate_->bootstrapper()->IsActive() &&
781       !incremental_marking()->IsMarking()) {
782     return;
783   }
784
785   Object* context = native_contexts_list_;
786   while (!context->IsUndefined()) {
787     // GC can happen when the context is not fully initialized,
788     // so the cache can be undefined.
789     Object* cache =
790         Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
791     if (!cache->IsUndefined()) {
792       NormalizedMapCache::cast(cache)->Clear();
793     }
794     context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
795   }
796 }
797
798
799 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
800   double survival_rate =
801       (static_cast<double>(young_survivors_after_last_gc_) * 100) /
802       start_new_space_size;
803
804   if (survival_rate > kYoungSurvivalRateHighThreshold) {
805     high_survival_rate_period_length_++;
806   } else {
807     high_survival_rate_period_length_ = 0;
808   }
809
810   if (survival_rate < kYoungSurvivalRateLowThreshold) {
811     low_survival_rate_period_length_++;
812   } else {
813     low_survival_rate_period_length_ = 0;
814   }
815
816   double survival_rate_diff = survival_rate_ - survival_rate;
817
818   if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
819     set_survival_rate_trend(DECREASING);
820   } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
821     set_survival_rate_trend(INCREASING);
822   } else {
823     set_survival_rate_trend(STABLE);
824   }
825
826   survival_rate_ = survival_rate;
827 }
828
829 bool Heap::PerformGarbageCollection(GarbageCollector collector,
830                                     GCTracer* tracer) {
831   bool next_gc_likely_to_collect_more = false;
832
833   if (collector != SCAVENGER) {
834     PROFILE(isolate_, CodeMovingGCEvent());
835   }
836
837   if (FLAG_verify_heap) {
838     VerifySymbolTable();
839   }
840   if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
841     ASSERT(!allocation_allowed_);
842     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
843     global_gc_prologue_callback_();
844   }
845
846   GCType gc_type =
847       collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
848
849   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
850     if (gc_type & gc_prologue_callbacks_[i].gc_type) {
851       gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
852     }
853   }
854
855   EnsureFromSpaceIsCommitted();
856
857   int start_new_space_size = Heap::new_space()->SizeAsInt();
858
859   if (IsHighSurvivalRate()) {
860     // We speed up the incremental marker if it is running so that it
861     // does not fall behind the rate of promotion, which would cause a
862     // constantly growing old space.
863     incremental_marking()->NotifyOfHighPromotionRate();
864   }
865
866   if (collector == MARK_COMPACTOR) {
867     // Perform mark-sweep with optional compaction.
868     MarkCompact(tracer);
869     sweep_generation_++;
870     bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
871         IsStableOrIncreasingSurvivalTrend();
872
873     UpdateSurvivalRateTrend(start_new_space_size);
874
875     size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
876
877     if (high_survival_rate_during_scavenges &&
878         IsStableOrIncreasingSurvivalTrend()) {
879       // Stable high survival rates of young objects both during partial and
880       // full collection indicate that mutator is either building or modifying
881       // a structure with a long lifetime.
882       // In this case we aggressively raise old generation memory limits to
883       // postpone subsequent mark-sweep collection and thus trade memory
884       // space for the mutation speed.
885       old_gen_limit_factor_ = 2;
886     } else {
887       old_gen_limit_factor_ = 1;
888     }
889
890     old_gen_promotion_limit_ =
891         OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
892     old_gen_allocation_limit_ =
893         OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
894
895     old_gen_exhausted_ = false;
896   } else {
897     tracer_ = tracer;
898     Scavenge();
899     tracer_ = NULL;
900
901     UpdateSurvivalRateTrend(start_new_space_size);
902   }
903
904   if (!new_space_high_promotion_mode_active_ &&
905       new_space_.Capacity() == new_space_.MaximumCapacity() &&
906       IsStableOrIncreasingSurvivalTrend() &&
907       IsHighSurvivalRate()) {
908     // Stable high survival rates even though young generation is at
909     // maximum capacity indicates that most objects will be promoted.
910     // To decrease scavenger pauses and final mark-sweep pauses, we
911     // have to limit maximal capacity of the young generation.
912     new_space_high_promotion_mode_active_ = true;
913     if (FLAG_trace_gc) {
914       PrintPID("Limited new space size due to high promotion rate: %d MB\n",
915                new_space_.InitialCapacity() / MB);
916     }
917   } else if (new_space_high_promotion_mode_active_ &&
918       IsStableOrDecreasingSurvivalTrend() &&
919       IsLowSurvivalRate()) {
920     // Decreasing low survival rates might indicate that the above high
921     // promotion mode is over and we should allow the young generation
922     // to grow again.
923     new_space_high_promotion_mode_active_ = false;
924     if (FLAG_trace_gc) {
925       PrintPID("Unlimited new space size due to low promotion rate: %d MB\n",
926                new_space_.MaximumCapacity() / MB);
927     }
928   }
929
930   if (new_space_high_promotion_mode_active_ &&
931       new_space_.Capacity() > new_space_.InitialCapacity()) {
932     new_space_.Shrink();
933   }
934
935   isolate_->counters()->objs_since_last_young()->Set(0);
936
937   gc_post_processing_depth_++;
938   { DisableAssertNoAllocation allow_allocation;
939     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
940     next_gc_likely_to_collect_more =
941         isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
942   }
943   gc_post_processing_depth_--;
944
945   // Update relocatables.
946   Relocatable::PostGarbageCollectionProcessing();
947
948   if (collector == MARK_COMPACTOR) {
949     // Register the amount of external allocated memory.
950     amount_of_external_allocated_memory_at_last_global_gc_ =
951         amount_of_external_allocated_memory_;
952   }
953
954   GCCallbackFlags callback_flags = kNoGCCallbackFlags;
955   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
956     if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
957       gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
958     }
959   }
960
961   if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
962     ASSERT(!allocation_allowed_);
963     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
964     global_gc_epilogue_callback_();
965   }
966   if (FLAG_verify_heap) {
967     VerifySymbolTable();
968   }
969
970   return next_gc_likely_to_collect_more;
971 }
972
973
974 void Heap::MarkCompact(GCTracer* tracer) {
975   gc_state_ = MARK_COMPACT;
976   LOG(isolate_, ResourceEvent("markcompact", "begin"));
977
978   mark_compact_collector_.Prepare(tracer);
979
980   ms_count_++;
981   tracer->set_full_gc_count(ms_count_);
982
983   MarkCompactPrologue();
984
985   mark_compact_collector_.CollectGarbage();
986
987   LOG(isolate_, ResourceEvent("markcompact", "end"));
988
989   gc_state_ = NOT_IN_GC;
990
991   isolate_->counters()->objs_since_last_full()->Set(0);
992
993   contexts_disposed_ = 0;
994
995   isolate_->set_context_exit_happened(false);
996 }
997
998
999 void Heap::MarkCompactPrologue() {
1000   // At any old GC clear the keyed lookup cache to enable collection of unused
1001   // maps.
1002   isolate_->keyed_lookup_cache()->Clear();
1003   isolate_->context_slot_cache()->Clear();
1004   isolate_->descriptor_lookup_cache()->Clear();
1005   RegExpResultsCache::Clear(string_split_cache());
1006   RegExpResultsCache::Clear(regexp_multiple_cache());
1007
1008   isolate_->compilation_cache()->MarkCompactPrologue();
1009
1010   CompletelyClearInstanceofCache();
1011
1012   FlushNumberStringCache();
1013   if (FLAG_cleanup_code_caches_at_gc) {
1014     polymorphic_code_cache()->set_cache(undefined_value());
1015   }
1016
1017   ClearNormalizedMapCaches();
1018 }
1019
1020
1021 Object* Heap::FindCodeObject(Address a) {
1022   return isolate()->inner_pointer_to_code_cache()->
1023       GcSafeFindCodeForInnerPointer(a);
1024 }
1025
1026
1027 // Helper class for copying HeapObjects
1028 class ScavengeVisitor: public ObjectVisitor {
1029  public:
1030   explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
1031
1032   void VisitPointer(Object** p) { ScavengePointer(p); }
1033
1034   void VisitPointers(Object** start, Object** end) {
1035     // Copy all HeapObject pointers in [start, end)
1036     for (Object** p = start; p < end; p++) ScavengePointer(p);
1037   }
1038
1039  private:
1040   void ScavengePointer(Object** p) {
1041     Object* object = *p;
1042     if (!heap_->InNewSpace(object)) return;
1043     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1044                          reinterpret_cast<HeapObject*>(object));
1045   }
1046
1047   Heap* heap_;
1048 };
1049
1050
1051 #ifdef DEBUG
1052 // Visitor class to verify pointers in code or data space do not point into
1053 // new space.
1054 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
1055  public:
1056   void VisitPointers(Object** start, Object**end) {
1057     for (Object** current = start; current < end; current++) {
1058       if ((*current)->IsHeapObject()) {
1059         ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
1060       }
1061     }
1062   }
1063 };
1064
1065
1066 static void VerifyNonPointerSpacePointers() {
1067   // Verify that there are no pointers to new space in spaces where we
1068   // do not expect them.
1069   VerifyNonPointerSpacePointersVisitor v;
1070   HeapObjectIterator code_it(HEAP->code_space());
1071   for (HeapObject* object = code_it.Next();
1072        object != NULL; object = code_it.Next())
1073     object->Iterate(&v);
1074
1075   // The old data space was normally swept conservatively so that the iterator
1076   // doesn't work, so we normally skip the next bit.
1077   if (!HEAP->old_data_space()->was_swept_conservatively()) {
1078     HeapObjectIterator data_it(HEAP->old_data_space());
1079     for (HeapObject* object = data_it.Next();
1080          object != NULL; object = data_it.Next())
1081       object->Iterate(&v);
1082   }
1083 }
1084 #endif
1085
1086
1087 void Heap::CheckNewSpaceExpansionCriteria() {
1088   if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1089       survived_since_last_expansion_ > new_space_.Capacity() &&
1090       !new_space_high_promotion_mode_active_) {
1091     // Grow the size of new space if there is room to grow, enough data
1092     // has survived scavenge since the last expansion and we are not in
1093     // high promotion mode.
1094     new_space_.Grow();
1095     survived_since_last_expansion_ = 0;
1096   }
1097 }
1098
1099
1100 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1101   return heap->InNewSpace(*p) &&
1102       !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1103 }
1104
1105
1106 void Heap::ScavengeStoreBufferCallback(
1107     Heap* heap,
1108     MemoryChunk* page,
1109     StoreBufferEvent event) {
1110   heap->store_buffer_rebuilder_.Callback(page, event);
1111 }
1112
1113
1114 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1115   if (event == kStoreBufferStartScanningPagesEvent) {
1116     start_of_current_page_ = NULL;
1117     current_page_ = NULL;
1118   } else if (event == kStoreBufferScanningPageEvent) {
1119     if (current_page_ != NULL) {
1120       // If this page already overflowed the store buffer during this iteration.
1121       if (current_page_->scan_on_scavenge()) {
1122         // Then we should wipe out the entries that have been added for it.
1123         store_buffer_->SetTop(start_of_current_page_);
1124       } else if (store_buffer_->Top() - start_of_current_page_ >=
1125                  (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1126         // Did we find too many pointers in the previous page?  The heuristic is
1127         // that no page can take more then 1/5 the remaining slots in the store
1128         // buffer.
1129         current_page_->set_scan_on_scavenge(true);
1130         store_buffer_->SetTop(start_of_current_page_);
1131       } else {
1132         // In this case the page we scanned took a reasonable number of slots in
1133         // the store buffer.  It has now been rehabilitated and is no longer
1134         // marked scan_on_scavenge.
1135         ASSERT(!current_page_->scan_on_scavenge());
1136       }
1137     }
1138     start_of_current_page_ = store_buffer_->Top();
1139     current_page_ = page;
1140   } else if (event == kStoreBufferFullEvent) {
1141     // The current page overflowed the store buffer again.  Wipe out its entries
1142     // in the store buffer and mark it scan-on-scavenge again.  This may happen
1143     // several times while scanning.
1144     if (current_page_ == NULL) {
1145       // Store Buffer overflowed while scanning promoted objects.  These are not
1146       // in any particular page, though they are likely to be clustered by the
1147       // allocation routines.
1148       store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1149     } else {
1150       // Store Buffer overflowed while scanning a particular old space page for
1151       // pointers to new space.
1152       ASSERT(current_page_ == page);
1153       ASSERT(page != NULL);
1154       current_page_->set_scan_on_scavenge(true);
1155       ASSERT(start_of_current_page_ != store_buffer_->Top());
1156       store_buffer_->SetTop(start_of_current_page_);
1157     }
1158   } else {
1159     UNREACHABLE();
1160   }
1161 }
1162
1163
1164 void PromotionQueue::Initialize() {
1165   // Assumes that a NewSpacePage exactly fits a number of promotion queue
1166   // entries (where each is a pair of intptr_t). This allows us to simplify
1167   // the test fpr when to switch pages.
1168   ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1169          == 0);
1170   limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1171   front_ = rear_ =
1172       reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1173   emergency_stack_ = NULL;
1174   guard_ = false;
1175 }
1176
1177
1178 void PromotionQueue::RelocateQueueHead() {
1179   ASSERT(emergency_stack_ == NULL);
1180
1181   Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1182   intptr_t* head_start = rear_;
1183   intptr_t* head_end =
1184       Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1185
1186   int entries_count =
1187       static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1188
1189   emergency_stack_ = new List<Entry>(2 * entries_count);
1190
1191   while (head_start != head_end) {
1192     int size = static_cast<int>(*(head_start++));
1193     HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1194     emergency_stack_->Add(Entry(obj, size));
1195   }
1196   rear_ = head_end;
1197 }
1198
1199
1200 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1201  public:
1202   explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
1203
1204   virtual Object* RetainAs(Object* object) {
1205     if (!heap_->InFromSpace(object)) {
1206       return object;
1207     }
1208
1209     MapWord map_word = HeapObject::cast(object)->map_word();
1210     if (map_word.IsForwardingAddress()) {
1211       return map_word.ToForwardingAddress();
1212     }
1213     return NULL;
1214   }
1215
1216  private:
1217   Heap* heap_;
1218 };
1219
1220
1221 void Heap::Scavenge() {
1222   RelocationLock relocation_lock(this);
1223 #ifdef DEBUG
1224   if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1225 #endif
1226
1227   gc_state_ = SCAVENGE;
1228
1229   // Implements Cheney's copying algorithm
1230   LOG(isolate_, ResourceEvent("scavenge", "begin"));
1231
1232   // Clear descriptor cache.
1233   isolate_->descriptor_lookup_cache()->Clear();
1234
1235   // Used for updating survived_since_last_expansion_ at function end.
1236   intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1237
1238   CheckNewSpaceExpansionCriteria();
1239
1240   SelectScavengingVisitorsTable();
1241
1242   incremental_marking()->PrepareForScavenge();
1243
1244   AdvanceSweepers(static_cast<int>(new_space_.Size()));
1245
1246   // Flip the semispaces.  After flipping, to space is empty, from space has
1247   // live objects.
1248   new_space_.Flip();
1249   new_space_.ResetAllocationInfo();
1250
1251   // We need to sweep newly copied objects which can be either in the
1252   // to space or promoted to the old generation.  For to-space
1253   // objects, we treat the bottom of the to space as a queue.  Newly
1254   // copied and unswept objects lie between a 'front' mark and the
1255   // allocation pointer.
1256   //
1257   // Promoted objects can go into various old-generation spaces, and
1258   // can be allocated internally in the spaces (from the free list).
1259   // We treat the top of the to space as a queue of addresses of
1260   // promoted objects.  The addresses of newly promoted and unswept
1261   // objects lie between a 'front' mark and a 'rear' mark that is
1262   // updated as a side effect of promoting an object.
1263   //
1264   // There is guaranteed to be enough room at the top of the to space
1265   // for the addresses of promoted objects: every object promoted
1266   // frees up its size in bytes from the top of the new space, and
1267   // objects are at least one pointer in size.
1268   Address new_space_front = new_space_.ToSpaceStart();
1269   promotion_queue_.Initialize();
1270
1271 #ifdef DEBUG
1272   store_buffer()->Clean();
1273 #endif
1274
1275   ScavengeVisitor scavenge_visitor(this);
1276   // Copy roots.
1277   IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1278
1279   // Copy objects reachable from the old generation.
1280   {
1281     StoreBufferRebuildScope scope(this,
1282                                   store_buffer(),
1283                                   &ScavengeStoreBufferCallback);
1284     store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1285   }
1286
1287   // Copy objects reachable from cells by scavenging cell values directly.
1288   HeapObjectIterator cell_iterator(cell_space_);
1289   for (HeapObject* heap_object = cell_iterator.Next();
1290        heap_object != NULL;
1291        heap_object = cell_iterator.Next()) {
1292     if (heap_object->IsJSGlobalPropertyCell()) {
1293       JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(heap_object);
1294       Address value_address = cell->ValueAddress();
1295       scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1296     }
1297   }
1298
1299   // Scavenge object reachable from the native contexts list directly.
1300   scavenge_visitor.VisitPointer(BitCast<Object**>(&native_contexts_list_));
1301
1302   new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1303   isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1304       &IsUnscavengedHeapObject);
1305   isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1306       &scavenge_visitor);
1307   new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1308
1309   UpdateNewSpaceReferencesInExternalStringTable(
1310       &UpdateNewSpaceReferenceInExternalStringTableEntry);
1311
1312   promotion_queue_.Destroy();
1313
1314   LiveObjectList::UpdateReferencesForScavengeGC();
1315   if (!FLAG_watch_ic_patching) {
1316     isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1317   }
1318   incremental_marking()->UpdateMarkingDequeAfterScavenge();
1319
1320   ScavengeWeakObjectRetainer weak_object_retainer(this);
1321   ProcessWeakReferences(&weak_object_retainer);
1322
1323   ASSERT(new_space_front == new_space_.top());
1324
1325   // Set age mark.
1326   new_space_.set_age_mark(new_space_.top());
1327
1328   new_space_.LowerInlineAllocationLimit(
1329       new_space_.inline_allocation_limit_step());
1330
1331   // Update how much has survived scavenge.
1332   IncrementYoungSurvivorsCounter(static_cast<int>(
1333       (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1334
1335   LOG(isolate_, ResourceEvent("scavenge", "end"));
1336
1337   gc_state_ = NOT_IN_GC;
1338
1339   scavenges_since_last_idle_round_++;
1340 }
1341
1342
1343 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1344                                                                 Object** p) {
1345   MapWord first_word = HeapObject::cast(*p)->map_word();
1346
1347   if (!first_word.IsForwardingAddress()) {
1348     // Unreachable external string can be finalized.
1349     heap->FinalizeExternalString(String::cast(*p));
1350     return NULL;
1351   }
1352
1353   // String is still reachable.
1354   return String::cast(first_word.ToForwardingAddress());
1355 }
1356
1357
1358 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1359     ExternalStringTableUpdaterCallback updater_func) {
1360   if (FLAG_verify_heap) {
1361     external_string_table_.Verify();
1362   }
1363
1364   if (external_string_table_.new_space_strings_.is_empty()) return;
1365
1366   Object** start = &external_string_table_.new_space_strings_[0];
1367   Object** end = start + external_string_table_.new_space_strings_.length();
1368   Object** last = start;
1369
1370   for (Object** p = start; p < end; ++p) {
1371     ASSERT(InFromSpace(*p));
1372     String* target = updater_func(this, p);
1373
1374     if (target == NULL) continue;
1375
1376     ASSERT(target->IsExternalString());
1377
1378     if (InNewSpace(target)) {
1379       // String is still in new space.  Update the table entry.
1380       *last = target;
1381       ++last;
1382     } else {
1383       // String got promoted.  Move it to the old string list.
1384       external_string_table_.AddOldString(target);
1385     }
1386   }
1387
1388   ASSERT(last <= end);
1389   external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1390 }
1391
1392
1393 void Heap::UpdateReferencesInExternalStringTable(
1394     ExternalStringTableUpdaterCallback updater_func) {
1395
1396   // Update old space string references.
1397   if (external_string_table_.old_space_strings_.length() > 0) {
1398     Object** start = &external_string_table_.old_space_strings_[0];
1399     Object** end = start + external_string_table_.old_space_strings_.length();
1400     for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1401   }
1402
1403   UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1404 }
1405
1406
1407 static Object* ProcessFunctionWeakReferences(Heap* heap,
1408                                              Object* function,
1409                                              WeakObjectRetainer* retainer,
1410                                              bool record_slots) {
1411   Object* undefined = heap->undefined_value();
1412   Object* head = undefined;
1413   JSFunction* tail = NULL;
1414   Object* candidate = function;
1415   while (candidate != undefined) {
1416     // Check whether to keep the candidate in the list.
1417     JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1418     Object* retain = retainer->RetainAs(candidate);
1419     if (retain != NULL) {
1420       if (head == undefined) {
1421         // First element in the list.
1422         head = retain;
1423       } else {
1424         // Subsequent elements in the list.
1425         ASSERT(tail != NULL);
1426         tail->set_next_function_link(retain);
1427         if (record_slots) {
1428           Object** next_function =
1429               HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
1430           heap->mark_compact_collector()->RecordSlot(
1431               next_function, next_function, retain);
1432         }
1433       }
1434       // Retained function is new tail.
1435       candidate_function = reinterpret_cast<JSFunction*>(retain);
1436       tail = candidate_function;
1437
1438       ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1439
1440       if (retain == undefined) break;
1441     }
1442
1443     // Move to next element in the list.
1444     candidate = candidate_function->next_function_link();
1445   }
1446
1447   // Terminate the list if there is one or more elements.
1448   if (tail != NULL) {
1449     tail->set_next_function_link(undefined);
1450   }
1451
1452   return head;
1453 }
1454
1455
1456 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1457   Object* undefined = undefined_value();
1458   Object* head = undefined;
1459   Context* tail = NULL;
1460   Object* candidate = native_contexts_list_;
1461
1462   // We don't record weak slots during marking or scavenges.
1463   // Instead we do it once when we complete mark-compact cycle.
1464   // Note that write barrier has no effect if we are already in the middle of
1465   // compacting mark-sweep cycle and we have to record slots manually.
1466   bool record_slots =
1467       gc_state() == MARK_COMPACT &&
1468       mark_compact_collector()->is_compacting();
1469
1470   while (candidate != undefined) {
1471     // Check whether to keep the candidate in the list.
1472     Context* candidate_context = reinterpret_cast<Context*>(candidate);
1473     Object* retain = retainer->RetainAs(candidate);
1474     if (retain != NULL) {
1475       if (head == undefined) {
1476         // First element in the list.
1477         head = retain;
1478       } else {
1479         // Subsequent elements in the list.
1480         ASSERT(tail != NULL);
1481         tail->set_unchecked(this,
1482                             Context::NEXT_CONTEXT_LINK,
1483                             retain,
1484                             UPDATE_WRITE_BARRIER);
1485
1486         if (record_slots) {
1487           Object** next_context =
1488               HeapObject::RawField(
1489                   tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
1490           mark_compact_collector()->RecordSlot(
1491               next_context, next_context, retain);
1492         }
1493       }
1494       // Retained context is new tail.
1495       candidate_context = reinterpret_cast<Context*>(retain);
1496       tail = candidate_context;
1497
1498       if (retain == undefined) break;
1499
1500       // Process the weak list of optimized functions for the context.
1501       Object* function_list_head =
1502           ProcessFunctionWeakReferences(
1503               this,
1504               candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1505               retainer,
1506               record_slots);
1507       candidate_context->set_unchecked(this,
1508                                        Context::OPTIMIZED_FUNCTIONS_LIST,
1509                                        function_list_head,
1510                                        UPDATE_WRITE_BARRIER);
1511       if (record_slots) {
1512         Object** optimized_functions =
1513             HeapObject::RawField(
1514                 tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
1515         mark_compact_collector()->RecordSlot(
1516             optimized_functions, optimized_functions, function_list_head);
1517       }
1518     }
1519
1520     // Move to next element in the list.
1521     candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1522   }
1523
1524   // Terminate the list if there is one or more elements.
1525   if (tail != NULL) {
1526     tail->set_unchecked(this,
1527                         Context::NEXT_CONTEXT_LINK,
1528                         Heap::undefined_value(),
1529                         UPDATE_WRITE_BARRIER);
1530   }
1531
1532   // Update the head of the list of contexts.
1533   native_contexts_list_ = head;
1534 }
1535
1536
1537 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1538   AssertNoAllocation no_allocation;
1539
1540   class VisitorAdapter : public ObjectVisitor {
1541    public:
1542     explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1543         : visitor_(visitor) {}
1544     virtual void VisitPointers(Object** start, Object** end) {
1545       for (Object** p = start; p < end; p++) {
1546         if ((*p)->IsExternalString()) {
1547           visitor_->VisitExternalString(Utils::ToLocal(
1548               Handle<String>(String::cast(*p))));
1549         }
1550       }
1551     }
1552    private:
1553     v8::ExternalResourceVisitor* visitor_;
1554   } visitor_adapter(visitor);
1555   external_string_table_.Iterate(&visitor_adapter);
1556 }
1557
1558
1559 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1560  public:
1561   static inline void VisitPointer(Heap* heap, Object** p) {
1562     Object* object = *p;
1563     if (!heap->InNewSpace(object)) return;
1564     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1565                          reinterpret_cast<HeapObject*>(object));
1566   }
1567 };
1568
1569
1570 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1571                          Address new_space_front) {
1572   do {
1573     SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1574     // The addresses new_space_front and new_space_.top() define a
1575     // queue of unprocessed copied objects.  Process them until the
1576     // queue is empty.
1577     while (new_space_front != new_space_.top()) {
1578       if (!NewSpacePage::IsAtEnd(new_space_front)) {
1579         HeapObject* object = HeapObject::FromAddress(new_space_front);
1580         new_space_front +=
1581           NewSpaceScavenger::IterateBody(object->map(), object);
1582       } else {
1583         new_space_front =
1584             NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1585       }
1586     }
1587
1588     // Promote and process all the to-be-promoted objects.
1589     {
1590       StoreBufferRebuildScope scope(this,
1591                                     store_buffer(),
1592                                     &ScavengeStoreBufferCallback);
1593       while (!promotion_queue()->is_empty()) {
1594         HeapObject* target;
1595         int size;
1596         promotion_queue()->remove(&target, &size);
1597
1598         // Promoted object might be already partially visited
1599         // during old space pointer iteration. Thus we search specificly
1600         // for pointers to from semispace instead of looking for pointers
1601         // to new space.
1602         ASSERT(!target->IsMap());
1603         IterateAndMarkPointersToFromSpace(target->address(),
1604                                           target->address() + size,
1605                                           &ScavengeObject);
1606       }
1607     }
1608
1609     // Take another spin if there are now unswept objects in new space
1610     // (there are currently no more unswept promoted objects).
1611   } while (new_space_front != new_space_.top());
1612
1613   return new_space_front;
1614 }
1615
1616
1617 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
1618
1619
1620 INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
1621                                               HeapObject* object,
1622                                               int size));
1623
1624 static HeapObject* EnsureDoubleAligned(Heap* heap,
1625                                        HeapObject* object,
1626                                        int size) {
1627   if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
1628     heap->CreateFillerObjectAt(object->address(), kPointerSize);
1629     return HeapObject::FromAddress(object->address() + kPointerSize);
1630   } else {
1631     heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
1632                                kPointerSize);
1633     return object;
1634   }
1635 }
1636
1637
1638 enum LoggingAndProfiling {
1639   LOGGING_AND_PROFILING_ENABLED,
1640   LOGGING_AND_PROFILING_DISABLED
1641 };
1642
1643
1644 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1645
1646
1647 template<MarksHandling marks_handling,
1648          LoggingAndProfiling logging_and_profiling_mode>
1649 class ScavengingVisitor : public StaticVisitorBase {
1650  public:
1651   static void Initialize() {
1652     table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1653     table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1654     table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1655     table_.Register(kVisitByteArray, &EvacuateByteArray);
1656     table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1657     table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1658
1659     table_.Register(kVisitNativeContext,
1660                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1661                         template VisitSpecialized<Context::kSize>);
1662
1663     table_.Register(kVisitConsString,
1664                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1665                         template VisitSpecialized<ConsString::kSize>);
1666
1667     table_.Register(kVisitSlicedString,
1668                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1669                         template VisitSpecialized<SlicedString::kSize>);
1670
1671     table_.Register(kVisitSharedFunctionInfo,
1672                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1673                         template VisitSpecialized<SharedFunctionInfo::kSize>);
1674
1675     table_.Register(kVisitJSWeakMap,
1676                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1677                     Visit);
1678
1679     table_.Register(kVisitJSRegExp,
1680                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1681                     Visit);
1682
1683     if (marks_handling == IGNORE_MARKS) {
1684       table_.Register(kVisitJSFunction,
1685                       &ObjectEvacuationStrategy<POINTER_OBJECT>::
1686                           template VisitSpecialized<JSFunction::kSize>);
1687     } else {
1688       table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1689     }
1690
1691     table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1692                                    kVisitDataObject,
1693                                    kVisitDataObjectGeneric>();
1694
1695     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1696                                    kVisitJSObject,
1697                                    kVisitJSObjectGeneric>();
1698
1699     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1700                                    kVisitStruct,
1701                                    kVisitStructGeneric>();
1702   }
1703
1704   static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1705     return &table_;
1706   }
1707
1708  private:
1709   enum ObjectContents  { DATA_OBJECT, POINTER_OBJECT };
1710   enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1711
1712   static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1713     bool should_record = false;
1714 #ifdef DEBUG
1715     should_record = FLAG_heap_stats;
1716 #endif
1717     should_record = should_record || FLAG_log_gc;
1718     if (should_record) {
1719       if (heap->new_space()->Contains(obj)) {
1720         heap->new_space()->RecordAllocation(obj);
1721       } else {
1722         heap->new_space()->RecordPromotion(obj);
1723       }
1724     }
1725   }
1726
1727   // Helper function used by CopyObject to copy a source object to an
1728   // allocated target object and update the forwarding pointer in the source
1729   // object.  Returns the target object.
1730   INLINE(static void MigrateObject(Heap* heap,
1731                                    HeapObject* source,
1732                                    HeapObject* target,
1733                                    int size)) {
1734     // Copy the content of source to target.
1735     heap->CopyBlock(target->address(), source->address(), size);
1736
1737     // Set the forwarding address.
1738     source->set_map_word(MapWord::FromForwardingAddress(target));
1739
1740     if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1741       // Update NewSpace stats if necessary.
1742       RecordCopiedObject(heap, target);
1743       HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1744       Isolate* isolate = heap->isolate();
1745       if (isolate->logger()->is_logging_code_events() ||
1746           CpuProfiler::is_profiling(isolate)) {
1747         if (target->IsSharedFunctionInfo()) {
1748           PROFILE(isolate, SharedFunctionInfoMoveEvent(
1749               source->address(), target->address()));
1750         }
1751       }
1752     }
1753
1754     if (marks_handling == TRANSFER_MARKS) {
1755       if (Marking::TransferColor(source, target)) {
1756         MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1757       }
1758     }
1759   }
1760
1761
1762   template<ObjectContents object_contents,
1763            SizeRestriction size_restriction,
1764            int alignment>
1765   static inline void EvacuateObject(Map* map,
1766                                     HeapObject** slot,
1767                                     HeapObject* object,
1768                                     int object_size) {
1769     SLOW_ASSERT((size_restriction != SMALL) ||
1770                 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1771     SLOW_ASSERT(object->Size() == object_size);
1772
1773     int allocation_size = object_size;
1774     if (alignment != kObjectAlignment) {
1775       ASSERT(alignment == kDoubleAlignment);
1776       allocation_size += kPointerSize;
1777     }
1778
1779     Heap* heap = map->GetHeap();
1780     if (heap->ShouldBePromoted(object->address(), object_size)) {
1781       MaybeObject* maybe_result;
1782
1783       if ((size_restriction != SMALL) &&
1784           (allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
1785         maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
1786                                                      NOT_EXECUTABLE);
1787       } else {
1788         if (object_contents == DATA_OBJECT) {
1789           maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
1790         } else {
1791           maybe_result =
1792               heap->old_pointer_space()->AllocateRaw(allocation_size);
1793         }
1794       }
1795
1796       Object* result = NULL;  // Initialization to please compiler.
1797       if (maybe_result->ToObject(&result)) {
1798         HeapObject* target = HeapObject::cast(result);
1799
1800         if (alignment != kObjectAlignment) {
1801           target = EnsureDoubleAligned(heap, target, allocation_size);
1802         }
1803
1804         // Order is important: slot might be inside of the target if target
1805         // was allocated over a dead object and slot comes from the store
1806         // buffer.
1807         *slot = target;
1808         MigrateObject(heap, object, target, object_size);
1809
1810         if (object_contents == POINTER_OBJECT) {
1811           if (map->instance_type() == JS_FUNCTION_TYPE) {
1812             heap->promotion_queue()->insert(
1813                 target, JSFunction::kNonWeakFieldsEndOffset);
1814           } else {
1815             heap->promotion_queue()->insert(target, object_size);
1816           }
1817         }
1818
1819         heap->tracer()->increment_promoted_objects_size(object_size);
1820         return;
1821       }
1822     }
1823     MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
1824     heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1825     Object* result = allocation->ToObjectUnchecked();
1826     HeapObject* target = HeapObject::cast(result);
1827
1828     if (alignment != kObjectAlignment) {
1829       target = EnsureDoubleAligned(heap, target, allocation_size);
1830     }
1831
1832     // Order is important: slot might be inside of the target if target
1833     // was allocated over a dead object and slot comes from the store
1834     // buffer.
1835     *slot = target;
1836     MigrateObject(heap, object, target, object_size);
1837     return;
1838   }
1839
1840
1841   static inline void EvacuateJSFunction(Map* map,
1842                                         HeapObject** slot,
1843                                         HeapObject* object) {
1844     ObjectEvacuationStrategy<POINTER_OBJECT>::
1845         template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1846
1847     HeapObject* target = *slot;
1848     MarkBit mark_bit = Marking::MarkBitFrom(target);
1849     if (Marking::IsBlack(mark_bit)) {
1850       // This object is black and it might not be rescanned by marker.
1851       // We should explicitly record code entry slot for compaction because
1852       // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1853       // miss it as it is not HeapObject-tagged.
1854       Address code_entry_slot =
1855           target->address() + JSFunction::kCodeEntryOffset;
1856       Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1857       map->GetHeap()->mark_compact_collector()->
1858           RecordCodeEntrySlot(code_entry_slot, code);
1859     }
1860   }
1861
1862
1863   static inline void EvacuateFixedArray(Map* map,
1864                                         HeapObject** slot,
1865                                         HeapObject* object) {
1866     int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1867     EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
1868                                                  slot,
1869                                                  object,
1870                                                  object_size);
1871   }
1872
1873
1874   static inline void EvacuateFixedDoubleArray(Map* map,
1875                                               HeapObject** slot,
1876                                               HeapObject* object) {
1877     int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1878     int object_size = FixedDoubleArray::SizeFor(length);
1879     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
1880         map,
1881         slot,
1882         object,
1883         object_size);
1884   }
1885
1886
1887   static inline void EvacuateByteArray(Map* map,
1888                                        HeapObject** slot,
1889                                        HeapObject* object) {
1890     int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1891     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1892         map, slot, object, object_size);
1893   }
1894
1895
1896   static inline void EvacuateSeqAsciiString(Map* map,
1897                                             HeapObject** slot,
1898                                             HeapObject* object) {
1899     int object_size = SeqAsciiString::cast(object)->
1900         SeqAsciiStringSize(map->instance_type());
1901     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1902         map, slot, object, object_size);
1903   }
1904
1905
1906   static inline void EvacuateSeqTwoByteString(Map* map,
1907                                               HeapObject** slot,
1908                                               HeapObject* object) {
1909     int object_size = SeqTwoByteString::cast(object)->
1910         SeqTwoByteStringSize(map->instance_type());
1911     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1912         map, slot, object, object_size);
1913   }
1914
1915
1916   static inline bool IsShortcutCandidate(int type) {
1917     return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1918   }
1919
1920   static inline void EvacuateShortcutCandidate(Map* map,
1921                                                HeapObject** slot,
1922                                                HeapObject* object) {
1923     ASSERT(IsShortcutCandidate(map->instance_type()));
1924
1925     Heap* heap = map->GetHeap();
1926
1927     if (marks_handling == IGNORE_MARKS &&
1928         ConsString::cast(object)->unchecked_second() ==
1929         heap->empty_string()) {
1930       HeapObject* first =
1931           HeapObject::cast(ConsString::cast(object)->unchecked_first());
1932
1933       *slot = first;
1934
1935       if (!heap->InNewSpace(first)) {
1936         object->set_map_word(MapWord::FromForwardingAddress(first));
1937         return;
1938       }
1939
1940       MapWord first_word = first->map_word();
1941       if (first_word.IsForwardingAddress()) {
1942         HeapObject* target = first_word.ToForwardingAddress();
1943
1944         *slot = target;
1945         object->set_map_word(MapWord::FromForwardingAddress(target));
1946         return;
1947       }
1948
1949       heap->DoScavengeObject(first->map(), slot, first);
1950       object->set_map_word(MapWord::FromForwardingAddress(*slot));
1951       return;
1952     }
1953
1954     int object_size = ConsString::kSize;
1955     EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
1956         map, slot, object, object_size);
1957   }
1958
1959   template<ObjectContents object_contents>
1960   class ObjectEvacuationStrategy {
1961    public:
1962     template<int object_size>
1963     static inline void VisitSpecialized(Map* map,
1964                                         HeapObject** slot,
1965                                         HeapObject* object) {
1966       EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1967           map, slot, object, object_size);
1968     }
1969
1970     static inline void Visit(Map* map,
1971                              HeapObject** slot,
1972                              HeapObject* object) {
1973       int object_size = map->instance_size();
1974       EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1975           map, slot, object, object_size);
1976     }
1977   };
1978
1979   static VisitorDispatchTable<ScavengingCallback> table_;
1980 };
1981
1982
1983 template<MarksHandling marks_handling,
1984          LoggingAndProfiling logging_and_profiling_mode>
1985 VisitorDispatchTable<ScavengingCallback>
1986     ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1987
1988
1989 static void InitializeScavengingVisitorsTables() {
1990   ScavengingVisitor<TRANSFER_MARKS,
1991                     LOGGING_AND_PROFILING_DISABLED>::Initialize();
1992   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1993   ScavengingVisitor<TRANSFER_MARKS,
1994                     LOGGING_AND_PROFILING_ENABLED>::Initialize();
1995   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1996 }
1997
1998
1999 void Heap::SelectScavengingVisitorsTable() {
2000   bool logging_and_profiling =
2001       isolate()->logger()->is_logging() ||
2002       CpuProfiler::is_profiling(isolate()) ||
2003       (isolate()->heap_profiler() != NULL &&
2004        isolate()->heap_profiler()->is_profiling());
2005
2006   if (!incremental_marking()->IsMarking()) {
2007     if (!logging_and_profiling) {
2008       scavenging_visitors_table_.CopyFrom(
2009           ScavengingVisitor<IGNORE_MARKS,
2010                             LOGGING_AND_PROFILING_DISABLED>::GetTable());
2011     } else {
2012       scavenging_visitors_table_.CopyFrom(
2013           ScavengingVisitor<IGNORE_MARKS,
2014                             LOGGING_AND_PROFILING_ENABLED>::GetTable());
2015     }
2016   } else {
2017     if (!logging_and_profiling) {
2018       scavenging_visitors_table_.CopyFrom(
2019           ScavengingVisitor<TRANSFER_MARKS,
2020                             LOGGING_AND_PROFILING_DISABLED>::GetTable());
2021     } else {
2022       scavenging_visitors_table_.CopyFrom(
2023           ScavengingVisitor<TRANSFER_MARKS,
2024                             LOGGING_AND_PROFILING_ENABLED>::GetTable());
2025     }
2026
2027     if (incremental_marking()->IsCompacting()) {
2028       // When compacting forbid short-circuiting of cons-strings.
2029       // Scavenging code relies on the fact that new space object
2030       // can't be evacuated into evacuation candidate but
2031       // short-circuiting violates this assumption.
2032       scavenging_visitors_table_.Register(
2033           StaticVisitorBase::kVisitShortcutCandidate,
2034           scavenging_visitors_table_.GetVisitorById(
2035               StaticVisitorBase::kVisitConsString));
2036     }
2037   }
2038 }
2039
2040
2041 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
2042   SLOW_ASSERT(HEAP->InFromSpace(object));
2043   MapWord first_word = object->map_word();
2044   SLOW_ASSERT(!first_word.IsForwardingAddress());
2045   Map* map = first_word.ToMap();
2046   map->GetHeap()->DoScavengeObject(map, p, object);
2047 }
2048
2049
2050 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
2051                                       int instance_size) {
2052   Object* result;
2053   MaybeObject* maybe_result = AllocateRawMap();
2054   if (!maybe_result->ToObject(&result)) return maybe_result;
2055
2056   // Map::cast cannot be used due to uninitialized map field.
2057   reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
2058   reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
2059   reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2060   reinterpret_cast<Map*>(result)->set_visitor_id(
2061         StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2062   reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2063   reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
2064   reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2065   reinterpret_cast<Map*>(result)->set_bit_field(0);
2066   reinterpret_cast<Map*>(result)->set_bit_field2(0);
2067   reinterpret_cast<Map*>(result)->set_bit_field3(0);
2068   return result;
2069 }
2070
2071
2072 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
2073                                int instance_size,
2074                                ElementsKind elements_kind) {
2075   Object* result;
2076   MaybeObject* maybe_result = AllocateRawMap();
2077   if (!maybe_result->To(&result)) return maybe_result;
2078
2079   Map* map = reinterpret_cast<Map*>(result);
2080   map->set_map_no_write_barrier(meta_map());
2081   map->set_instance_type(instance_type);
2082   map->set_visitor_id(
2083       StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2084   map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2085   map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
2086   map->set_instance_size(instance_size);
2087   map->set_inobject_properties(0);
2088   map->set_pre_allocated_property_fields(0);
2089   map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2090   map->init_back_pointer(undefined_value());
2091   map->set_unused_property_fields(0);
2092   map->set_bit_field(0);
2093   map->set_bit_field2(1 << Map::kIsExtensible);
2094   int bit_field3 = Map::EnumLengthBits::encode(Map::kInvalidEnumCache);
2095   map->set_bit_field3(bit_field3);
2096   map->set_elements_kind(elements_kind);
2097
2098   // If the map object is aligned fill the padding area with Smi 0 objects.
2099   if (Map::kPadStart < Map::kSize) {
2100     memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
2101            0,
2102            Map::kSize - Map::kPadStart);
2103   }
2104   return map;
2105 }
2106
2107
2108 MaybeObject* Heap::AllocateCodeCache() {
2109   CodeCache* code_cache;
2110   { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
2111     if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
2112   }
2113   code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2114   code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
2115   return code_cache;
2116 }
2117
2118
2119 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
2120   return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
2121 }
2122
2123
2124 MaybeObject* Heap::AllocateAccessorPair() {
2125   AccessorPair* accessors;
2126   { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
2127     if (!maybe_accessors->To(&accessors)) return maybe_accessors;
2128   }
2129   accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
2130   accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
2131   return accessors;
2132 }
2133
2134
2135 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
2136   TypeFeedbackInfo* info;
2137   { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
2138     if (!maybe_info->To(&info)) return maybe_info;
2139   }
2140   info->initialize_storage();
2141   info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
2142                                 SKIP_WRITE_BARRIER);
2143   return info;
2144 }
2145
2146
2147 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
2148   AliasedArgumentsEntry* entry;
2149   { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
2150     if (!maybe_entry->To(&entry)) return maybe_entry;
2151   }
2152   entry->set_aliased_context_slot(aliased_context_slot);
2153   return entry;
2154 }
2155
2156
2157 const Heap::StringTypeTable Heap::string_type_table[] = {
2158 #define STRING_TYPE_ELEMENT(type, size, name, camel_name)                      \
2159   {type, size, k##camel_name##MapRootIndex},
2160   STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2161 #undef STRING_TYPE_ELEMENT
2162 };
2163
2164
2165 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
2166 #define CONSTANT_SYMBOL_ELEMENT(name, contents)                                \
2167   {contents, k##name##RootIndex},
2168   SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
2169 #undef CONSTANT_SYMBOL_ELEMENT
2170 };
2171
2172
2173 const Heap::StructTable Heap::struct_table[] = {
2174 #define STRUCT_TABLE_ELEMENT(NAME, Name, name)                                 \
2175   { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
2176   STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2177 #undef STRUCT_TABLE_ELEMENT
2178 };
2179
2180
2181 bool Heap::CreateInitialMaps() {
2182   Object* obj;
2183   { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2184     if (!maybe_obj->ToObject(&obj)) return false;
2185   }
2186   // Map::cast cannot be used due to uninitialized map field.
2187   Map* new_meta_map = reinterpret_cast<Map*>(obj);
2188   set_meta_map(new_meta_map);
2189   new_meta_map->set_map(new_meta_map);
2190
2191   { MaybeObject* maybe_obj =
2192         AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2193     if (!maybe_obj->ToObject(&obj)) return false;
2194   }
2195   set_fixed_array_map(Map::cast(obj));
2196
2197   { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2198     if (!maybe_obj->ToObject(&obj)) return false;
2199   }
2200   set_oddball_map(Map::cast(obj));
2201
2202   // Allocate the empty array.
2203   { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2204     if (!maybe_obj->ToObject(&obj)) return false;
2205   }
2206   set_empty_fixed_array(FixedArray::cast(obj));
2207
2208   { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2209     if (!maybe_obj->ToObject(&obj)) return false;
2210   }
2211   set_null_value(Oddball::cast(obj));
2212   Oddball::cast(obj)->set_kind(Oddball::kNull);
2213
2214   { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2215     if (!maybe_obj->ToObject(&obj)) return false;
2216   }
2217   set_undefined_value(Oddball::cast(obj));
2218   Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2219   ASSERT(!InNewSpace(undefined_value()));
2220
2221   // Allocate the empty descriptor array.
2222   { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2223     if (!maybe_obj->ToObject(&obj)) return false;
2224   }
2225   set_empty_descriptor_array(DescriptorArray::cast(obj));
2226
2227   // Fix the instance_descriptors for the existing maps.
2228   meta_map()->set_code_cache(empty_fixed_array());
2229   meta_map()->init_back_pointer(undefined_value());
2230
2231   fixed_array_map()->set_code_cache(empty_fixed_array());
2232   fixed_array_map()->init_back_pointer(undefined_value());
2233
2234   oddball_map()->set_code_cache(empty_fixed_array());
2235   oddball_map()->init_back_pointer(undefined_value());
2236
2237   // Fix prototype object for existing maps.
2238   meta_map()->set_prototype(null_value());
2239   meta_map()->set_constructor(null_value());
2240
2241   fixed_array_map()->set_prototype(null_value());
2242   fixed_array_map()->set_constructor(null_value());
2243
2244   oddball_map()->set_prototype(null_value());
2245   oddball_map()->set_constructor(null_value());
2246
2247   { MaybeObject* maybe_obj =
2248         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2249     if (!maybe_obj->ToObject(&obj)) return false;
2250   }
2251   set_fixed_cow_array_map(Map::cast(obj));
2252   ASSERT(fixed_array_map() != fixed_cow_array_map());
2253
2254   { MaybeObject* maybe_obj =
2255         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2256     if (!maybe_obj->ToObject(&obj)) return false;
2257   }
2258   set_scope_info_map(Map::cast(obj));
2259
2260   { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2261     if (!maybe_obj->ToObject(&obj)) return false;
2262   }
2263   set_heap_number_map(Map::cast(obj));
2264
2265   { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2266     if (!maybe_obj->ToObject(&obj)) return false;
2267   }
2268   set_foreign_map(Map::cast(obj));
2269
2270   for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2271     const StringTypeTable& entry = string_type_table[i];
2272     { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2273       if (!maybe_obj->ToObject(&obj)) return false;
2274     }
2275     roots_[entry.index] = Map::cast(obj);
2276   }
2277
2278   { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2279     if (!maybe_obj->ToObject(&obj)) return false;
2280   }
2281   set_undetectable_string_map(Map::cast(obj));
2282   Map::cast(obj)->set_is_undetectable();
2283
2284   { MaybeObject* maybe_obj =
2285         AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2286     if (!maybe_obj->ToObject(&obj)) return false;
2287   }
2288   set_undetectable_ascii_string_map(Map::cast(obj));
2289   Map::cast(obj)->set_is_undetectable();
2290
2291   { MaybeObject* maybe_obj =
2292         AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2293     if (!maybe_obj->ToObject(&obj)) return false;
2294   }
2295   set_fixed_double_array_map(Map::cast(obj));
2296
2297   { MaybeObject* maybe_obj =
2298         AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2299     if (!maybe_obj->ToObject(&obj)) return false;
2300   }
2301   set_byte_array_map(Map::cast(obj));
2302
2303   { MaybeObject* maybe_obj =
2304         AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2305     if (!maybe_obj->ToObject(&obj)) return false;
2306   }
2307   set_free_space_map(Map::cast(obj));
2308
2309   { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2310     if (!maybe_obj->ToObject(&obj)) return false;
2311   }
2312   set_empty_byte_array(ByteArray::cast(obj));
2313
2314   { MaybeObject* maybe_obj =
2315         AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2316     if (!maybe_obj->ToObject(&obj)) return false;
2317   }
2318   set_external_pixel_array_map(Map::cast(obj));
2319
2320   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2321                                          ExternalArray::kAlignedSize);
2322     if (!maybe_obj->ToObject(&obj)) return false;
2323   }
2324   set_external_byte_array_map(Map::cast(obj));
2325
2326   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2327                                          ExternalArray::kAlignedSize);
2328     if (!maybe_obj->ToObject(&obj)) return false;
2329   }
2330   set_external_unsigned_byte_array_map(Map::cast(obj));
2331
2332   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2333                                          ExternalArray::kAlignedSize);
2334     if (!maybe_obj->ToObject(&obj)) return false;
2335   }
2336   set_external_short_array_map(Map::cast(obj));
2337
2338   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2339                                          ExternalArray::kAlignedSize);
2340     if (!maybe_obj->ToObject(&obj)) return false;
2341   }
2342   set_external_unsigned_short_array_map(Map::cast(obj));
2343
2344   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2345                                          ExternalArray::kAlignedSize);
2346     if (!maybe_obj->ToObject(&obj)) return false;
2347   }
2348   set_external_int_array_map(Map::cast(obj));
2349
2350   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2351                                          ExternalArray::kAlignedSize);
2352     if (!maybe_obj->ToObject(&obj)) return false;
2353   }
2354   set_external_unsigned_int_array_map(Map::cast(obj));
2355
2356   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2357                                          ExternalArray::kAlignedSize);
2358     if (!maybe_obj->ToObject(&obj)) return false;
2359   }
2360   set_external_float_array_map(Map::cast(obj));
2361
2362   { MaybeObject* maybe_obj =
2363         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2364     if (!maybe_obj->ToObject(&obj)) return false;
2365   }
2366   set_non_strict_arguments_elements_map(Map::cast(obj));
2367
2368   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2369                                          ExternalArray::kAlignedSize);
2370     if (!maybe_obj->ToObject(&obj)) return false;
2371   }
2372   set_external_double_array_map(Map::cast(obj));
2373
2374   { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2375     if (!maybe_obj->ToObject(&obj)) return false;
2376   }
2377   set_code_map(Map::cast(obj));
2378
2379   { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2380                                          JSGlobalPropertyCell::kSize);
2381     if (!maybe_obj->ToObject(&obj)) return false;
2382   }
2383   set_global_property_cell_map(Map::cast(obj));
2384
2385   { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2386     if (!maybe_obj->ToObject(&obj)) return false;
2387   }
2388   set_one_pointer_filler_map(Map::cast(obj));
2389
2390   { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2391     if (!maybe_obj->ToObject(&obj)) return false;
2392   }
2393   set_two_pointer_filler_map(Map::cast(obj));
2394
2395   for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2396     const StructTable& entry = struct_table[i];
2397     { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2398       if (!maybe_obj->ToObject(&obj)) return false;
2399     }
2400     roots_[entry.index] = Map::cast(obj);
2401   }
2402
2403   { MaybeObject* maybe_obj =
2404         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2405     if (!maybe_obj->ToObject(&obj)) return false;
2406   }
2407   set_hash_table_map(Map::cast(obj));
2408
2409   { MaybeObject* maybe_obj =
2410         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2411     if (!maybe_obj->ToObject(&obj)) return false;
2412   }
2413   set_function_context_map(Map::cast(obj));
2414
2415   { MaybeObject* maybe_obj =
2416         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2417     if (!maybe_obj->ToObject(&obj)) return false;
2418   }
2419   set_catch_context_map(Map::cast(obj));
2420
2421   { MaybeObject* maybe_obj =
2422         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2423     if (!maybe_obj->ToObject(&obj)) return false;
2424   }
2425   set_with_context_map(Map::cast(obj));
2426
2427   { MaybeObject* maybe_obj =
2428         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2429     if (!maybe_obj->ToObject(&obj)) return false;
2430   }
2431   set_block_context_map(Map::cast(obj));
2432
2433   { MaybeObject* maybe_obj =
2434         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2435     if (!maybe_obj->ToObject(&obj)) return false;
2436   }
2437   set_module_context_map(Map::cast(obj));
2438
2439   { MaybeObject* maybe_obj =
2440         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2441     if (!maybe_obj->ToObject(&obj)) return false;
2442   }
2443   set_global_context_map(Map::cast(obj));
2444
2445   { MaybeObject* maybe_obj =
2446         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2447     if (!maybe_obj->ToObject(&obj)) return false;
2448   }
2449   Map* native_context_map = Map::cast(obj);
2450   native_context_map->set_dictionary_map(true);
2451   native_context_map->set_visitor_id(StaticVisitorBase::kVisitNativeContext);
2452   set_native_context_map(native_context_map);
2453
2454   { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2455                                          SharedFunctionInfo::kAlignedSize);
2456     if (!maybe_obj->ToObject(&obj)) return false;
2457   }
2458   set_shared_function_info_map(Map::cast(obj));
2459
2460   { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2461                                          JSMessageObject::kSize);
2462     if (!maybe_obj->ToObject(&obj)) return false;
2463   }
2464   set_message_object_map(Map::cast(obj));
2465
2466   ASSERT(!InNewSpace(empty_fixed_array()));
2467   return true;
2468 }
2469
2470
2471 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2472   // Statically ensure that it is safe to allocate heap numbers in paged
2473   // spaces.
2474   STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2475   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2476
2477   Object* result;
2478   { MaybeObject* maybe_result =
2479         AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2480     if (!maybe_result->ToObject(&result)) return maybe_result;
2481   }
2482
2483   HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2484   HeapNumber::cast(result)->set_value(value);
2485   return result;
2486 }
2487
2488
2489 MaybeObject* Heap::AllocateHeapNumber(double value) {
2490   // Use general version, if we're forced to always allocate.
2491   if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2492
2493   // This version of AllocateHeapNumber is optimized for
2494   // allocation in new space.
2495   STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2496   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2497   Object* result;
2498   { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2499     if (!maybe_result->ToObject(&result)) return maybe_result;
2500   }
2501   HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2502   HeapNumber::cast(result)->set_value(value);
2503   return result;
2504 }
2505
2506
2507 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2508   Object* result;
2509   { MaybeObject* maybe_result = AllocateRawCell();
2510     if (!maybe_result->ToObject(&result)) return maybe_result;
2511   }
2512   HeapObject::cast(result)->set_map_no_write_barrier(
2513       global_property_cell_map());
2514   JSGlobalPropertyCell::cast(result)->set_value(value);
2515   return result;
2516 }
2517
2518
2519 MaybeObject* Heap::CreateOddball(const char* to_string,
2520                                  Object* to_number,
2521                                  byte kind) {
2522   Object* result;
2523   { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2524     if (!maybe_result->ToObject(&result)) return maybe_result;
2525   }
2526   return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2527 }
2528
2529
2530 bool Heap::CreateApiObjects() {
2531   Object* obj;
2532
2533   { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2534     if (!maybe_obj->ToObject(&obj)) return false;
2535   }
2536   // Don't use Smi-only elements optimizations for objects with the neander
2537   // map. There are too many cases where element values are set directly with a
2538   // bottleneck to trap the Smi-only -> fast elements transition, and there
2539   // appears to be no benefit for optimize this case.
2540   Map* new_neander_map = Map::cast(obj);
2541   new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
2542   set_neander_map(new_neander_map);
2543
2544   { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2545     if (!maybe_obj->ToObject(&obj)) return false;
2546   }
2547   Object* elements;
2548   { MaybeObject* maybe_elements = AllocateFixedArray(2);
2549     if (!maybe_elements->ToObject(&elements)) return false;
2550   }
2551   FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2552   JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2553   set_message_listeners(JSObject::cast(obj));
2554
2555   return true;
2556 }
2557
2558
2559 void Heap::CreateJSEntryStub() {
2560   JSEntryStub stub;
2561   set_js_entry_code(*stub.GetCode());
2562 }
2563
2564
2565 void Heap::CreateJSConstructEntryStub() {
2566   JSConstructEntryStub stub;
2567   set_js_construct_entry_code(*stub.GetCode());
2568 }
2569
2570
2571 void Heap::CreateFixedStubs() {
2572   // Here we create roots for fixed stubs. They are needed at GC
2573   // for cooking and uncooking (check out frames.cc).
2574   // The eliminates the need for doing dictionary lookup in the
2575   // stub cache for these stubs.
2576   HandleScope scope;
2577   // gcc-4.4 has problem generating correct code of following snippet:
2578   // {  JSEntryStub stub;
2579   //    js_entry_code_ = *stub.GetCode();
2580   // }
2581   // {  JSConstructEntryStub stub;
2582   //    js_construct_entry_code_ = *stub.GetCode();
2583   // }
2584   // To workaround the problem, make separate functions without inlining.
2585   Heap::CreateJSEntryStub();
2586   Heap::CreateJSConstructEntryStub();
2587
2588   // Create stubs that should be there, so we don't unexpectedly have to
2589   // create them if we need them during the creation of another stub.
2590   // Stub creation mixes raw pointers and handles in an unsafe manner so
2591   // we cannot create stubs while we are creating stubs.
2592   CodeStub::GenerateStubsAheadOfTime();
2593 }
2594
2595
2596 bool Heap::CreateInitialObjects() {
2597   Object* obj;
2598
2599   // The -0 value must be set before NumberFromDouble works.
2600   { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2601     if (!maybe_obj->ToObject(&obj)) return false;
2602   }
2603   set_minus_zero_value(HeapNumber::cast(obj));
2604   ASSERT(signbit(minus_zero_value()->Number()) != 0);
2605
2606   { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2607     if (!maybe_obj->ToObject(&obj)) return false;
2608   }
2609   set_nan_value(HeapNumber::cast(obj));
2610
2611   { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2612     if (!maybe_obj->ToObject(&obj)) return false;
2613   }
2614   set_infinity_value(HeapNumber::cast(obj));
2615
2616   // The hole has not been created yet, but we want to put something
2617   // predictable in the gaps in the symbol table, so lets make that Smi zero.
2618   set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2619
2620   // Allocate initial symbol table.
2621   { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2622     if (!maybe_obj->ToObject(&obj)) return false;
2623   }
2624   // Don't use set_symbol_table() due to asserts.
2625   roots_[kSymbolTableRootIndex] = obj;
2626
2627   // Finish initializing oddballs after creating symboltable.
2628   { MaybeObject* maybe_obj =
2629         undefined_value()->Initialize("undefined",
2630                                       nan_value(),
2631                                       Oddball::kUndefined);
2632     if (!maybe_obj->ToObject(&obj)) return false;
2633   }
2634
2635   // Initialize the null_value.
2636   { MaybeObject* maybe_obj =
2637         null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2638     if (!maybe_obj->ToObject(&obj)) return false;
2639   }
2640
2641   { MaybeObject* maybe_obj = CreateOddball("true",
2642                                            Smi::FromInt(1),
2643                                            Oddball::kTrue);
2644     if (!maybe_obj->ToObject(&obj)) return false;
2645   }
2646   set_true_value(Oddball::cast(obj));
2647
2648   { MaybeObject* maybe_obj = CreateOddball("false",
2649                                            Smi::FromInt(0),
2650                                            Oddball::kFalse);
2651     if (!maybe_obj->ToObject(&obj)) return false;
2652   }
2653   set_false_value(Oddball::cast(obj));
2654
2655   { MaybeObject* maybe_obj = CreateOddball("hole",
2656                                            Smi::FromInt(-1),
2657                                            Oddball::kTheHole);
2658     if (!maybe_obj->ToObject(&obj)) return false;
2659   }
2660   set_the_hole_value(Oddball::cast(obj));
2661
2662   { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2663                                            Smi::FromInt(-4),
2664                                            Oddball::kArgumentMarker);
2665     if (!maybe_obj->ToObject(&obj)) return false;
2666   }
2667   set_arguments_marker(Oddball::cast(obj));
2668
2669   { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2670                                            Smi::FromInt(-2),
2671                                            Oddball::kOther);
2672     if (!maybe_obj->ToObject(&obj)) return false;
2673   }
2674   set_no_interceptor_result_sentinel(obj);
2675
2676   { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2677                                            Smi::FromInt(-3),
2678                                            Oddball::kOther);
2679     if (!maybe_obj->ToObject(&obj)) return false;
2680   }
2681   set_termination_exception(obj);
2682
2683   // Allocate the empty string.
2684   { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2685     if (!maybe_obj->ToObject(&obj)) return false;
2686   }
2687   set_empty_string(String::cast(obj));
2688
2689   for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2690     { MaybeObject* maybe_obj =
2691           LookupAsciiSymbol(constant_symbol_table[i].contents);
2692       if (!maybe_obj->ToObject(&obj)) return false;
2693     }
2694     roots_[constant_symbol_table[i].index] = String::cast(obj);
2695   }
2696
2697   // Allocate the hidden symbol which is used to identify the hidden properties
2698   // in JSObjects. The hash code has a special value so that it will not match
2699   // the empty string when searching for the property. It cannot be part of the
2700   // loop above because it needs to be allocated manually with the special
2701   // hash code in place. The hash code for the hidden_symbol is zero to ensure
2702   // that it will always be at the first entry in property descriptors.
2703   { MaybeObject* maybe_obj =
2704         AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2705     if (!maybe_obj->ToObject(&obj)) return false;
2706   }
2707   hidden_symbol_ = String::cast(obj);
2708
2709   // Allocate the foreign for __proto__.
2710   { MaybeObject* maybe_obj =
2711         AllocateForeign((Address) &Accessors::ObjectPrototype);
2712     if (!maybe_obj->ToObject(&obj)) return false;
2713   }
2714   set_prototype_accessors(Foreign::cast(obj));
2715
2716   // Allocate the code_stubs dictionary. The initial size is set to avoid
2717   // expanding the dictionary during bootstrapping.
2718   { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2719     if (!maybe_obj->ToObject(&obj)) return false;
2720   }
2721   set_code_stubs(UnseededNumberDictionary::cast(obj));
2722
2723
2724   // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2725   // is set to avoid expanding the dictionary during bootstrapping.
2726   { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2727     if (!maybe_obj->ToObject(&obj)) return false;
2728   }
2729   set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2730
2731   { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2732     if (!maybe_obj->ToObject(&obj)) return false;
2733   }
2734   set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2735
2736   set_instanceof_cache_function(Smi::FromInt(0));
2737   set_instanceof_cache_map(Smi::FromInt(0));
2738   set_instanceof_cache_answer(Smi::FromInt(0));
2739
2740   CreateFixedStubs();
2741
2742   // Allocate the dictionary of intrinsic function names.
2743   { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2744     if (!maybe_obj->ToObject(&obj)) return false;
2745   }
2746   { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2747                                                                        obj);
2748     if (!maybe_obj->ToObject(&obj)) return false;
2749   }
2750   set_intrinsic_function_names(StringDictionary::cast(obj));
2751
2752   { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2753     if (!maybe_obj->ToObject(&obj)) return false;
2754   }
2755   set_number_string_cache(FixedArray::cast(obj));
2756
2757   // Allocate cache for single character ASCII strings.
2758   { MaybeObject* maybe_obj =
2759         AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2760     if (!maybe_obj->ToObject(&obj)) return false;
2761   }
2762   set_single_character_string_cache(FixedArray::cast(obj));
2763
2764   // Allocate cache for string split.
2765   { MaybeObject* maybe_obj = AllocateFixedArray(
2766       RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
2767     if (!maybe_obj->ToObject(&obj)) return false;
2768   }
2769   set_string_split_cache(FixedArray::cast(obj));
2770
2771   { MaybeObject* maybe_obj = AllocateFixedArray(
2772       RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
2773     if (!maybe_obj->ToObject(&obj)) return false;
2774   }
2775   set_regexp_multiple_cache(FixedArray::cast(obj));
2776
2777   // Allocate cache for external strings pointing to native source code.
2778   { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2779     if (!maybe_obj->ToObject(&obj)) return false;
2780   }
2781   set_natives_source_cache(FixedArray::cast(obj));
2782
2783   // Handling of script id generation is in FACTORY->NewScript.
2784   set_last_script_id(undefined_value());
2785
2786   // Initialize keyed lookup cache.
2787   isolate_->keyed_lookup_cache()->Clear();
2788
2789   // Initialize context slot cache.
2790   isolate_->context_slot_cache()->Clear();
2791
2792   // Initialize descriptor cache.
2793   isolate_->descriptor_lookup_cache()->Clear();
2794
2795   // Initialize compilation cache.
2796   isolate_->compilation_cache()->Clear();
2797
2798   return true;
2799 }
2800
2801
2802 Object* RegExpResultsCache::Lookup(Heap* heap,
2803                                    String* key_string,
2804                                    Object* key_pattern,
2805                                    ResultsCacheType type) {
2806   FixedArray* cache;
2807   if (!key_string->IsSymbol()) return Smi::FromInt(0);
2808   if (type == STRING_SPLIT_SUBSTRINGS) {
2809     ASSERT(key_pattern->IsString());
2810     if (!key_pattern->IsSymbol()) return Smi::FromInt(0);
2811     cache = heap->string_split_cache();
2812   } else {
2813     ASSERT(type == REGEXP_MULTIPLE_INDICES);
2814     ASSERT(key_pattern->IsFixedArray());
2815     cache = heap->regexp_multiple_cache();
2816   }
2817
2818   uint32_t hash = key_string->Hash();
2819   uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
2820       ~(kArrayEntriesPerCacheEntry - 1));
2821   if (cache->get(index + kStringOffset) == key_string &&
2822       cache->get(index + kPatternOffset) == key_pattern) {
2823     return cache->get(index + kArrayOffset);
2824   }
2825   index =
2826       ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
2827   if (cache->get(index + kStringOffset) == key_string &&
2828       cache->get(index + kPatternOffset) == key_pattern) {
2829     return cache->get(index + kArrayOffset);
2830   }
2831   return Smi::FromInt(0);
2832 }
2833
2834
2835 void RegExpResultsCache::Enter(Heap* heap,
2836                                String* key_string,
2837                                Object* key_pattern,
2838                                FixedArray* value_array,
2839                                ResultsCacheType type) {
2840   FixedArray* cache;
2841   if (!key_string->IsSymbol()) return;
2842   if (type == STRING_SPLIT_SUBSTRINGS) {
2843     ASSERT(key_pattern->IsString());
2844     if (!key_pattern->IsSymbol()) return;
2845     cache = heap->string_split_cache();
2846   } else {
2847     ASSERT(type == REGEXP_MULTIPLE_INDICES);
2848     ASSERT(key_pattern->IsFixedArray());
2849     cache = heap->regexp_multiple_cache();
2850   }
2851
2852   uint32_t hash = key_string->Hash();
2853   uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
2854       ~(kArrayEntriesPerCacheEntry - 1));
2855   if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2856     cache->set(index + kStringOffset, key_string);
2857     cache->set(index + kPatternOffset, key_pattern);
2858     cache->set(index + kArrayOffset, value_array);
2859   } else {
2860     uint32_t index2 =
2861         ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
2862     if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2863       cache->set(index2 + kStringOffset, key_string);
2864       cache->set(index2 + kPatternOffset, key_pattern);
2865       cache->set(index2 + kArrayOffset, value_array);
2866     } else {
2867       cache->set(index2 + kStringOffset, Smi::FromInt(0));
2868       cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2869       cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2870       cache->set(index + kStringOffset, key_string);
2871       cache->set(index + kPatternOffset, key_pattern);
2872       cache->set(index + kArrayOffset, value_array);
2873     }
2874   }
2875   // If the array is a reasonably short list of substrings, convert it into a
2876   // list of symbols.
2877   if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) {
2878     for (int i = 0; i < value_array->length(); i++) {
2879       String* str = String::cast(value_array->get(i));
2880       Object* symbol;
2881       MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2882       if (maybe_symbol->ToObject(&symbol)) {
2883         value_array->set(i, symbol);
2884       }
2885     }
2886   }
2887   // Convert backing store to a copy-on-write array.
2888   value_array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2889 }
2890
2891
2892 void RegExpResultsCache::Clear(FixedArray* cache) {
2893   for (int i = 0; i < kRegExpResultsCacheSize; i++) {
2894     cache->set(i, Smi::FromInt(0));
2895   }
2896 }
2897
2898
2899 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2900   MaybeObject* maybe_obj =
2901       AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2902   return maybe_obj;
2903 }
2904
2905
2906 int Heap::FullSizeNumberStringCacheLength() {
2907   // Compute the size of the number string cache based on the max newspace size.
2908   // The number string cache has a minimum size based on twice the initial cache
2909   // size to ensure that it is bigger after being made 'full size'.
2910   int number_string_cache_size = max_semispace_size_ / 512;
2911   number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2912                                  Min(0x4000, number_string_cache_size));
2913   // There is a string and a number per entry so the length is twice the number
2914   // of entries.
2915   return number_string_cache_size * 2;
2916 }
2917
2918
2919 void Heap::AllocateFullSizeNumberStringCache() {
2920   // The idea is to have a small number string cache in the snapshot to keep
2921   // boot-time memory usage down.  If we expand the number string cache already
2922   // while creating the snapshot then that didn't work out.
2923   ASSERT(!Serializer::enabled() || FLAG_extra_code != NULL);
2924   MaybeObject* maybe_obj =
2925       AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2926   Object* new_cache;
2927   if (maybe_obj->ToObject(&new_cache)) {
2928     // We don't bother to repopulate the cache with entries from the old cache.
2929     // It will be repopulated soon enough with new strings.
2930     set_number_string_cache(FixedArray::cast(new_cache));
2931   }
2932   // If allocation fails then we just return without doing anything.  It is only
2933   // a cache, so best effort is OK here.
2934 }
2935
2936
2937 void Heap::FlushNumberStringCache() {
2938   // Flush the number to string cache.
2939   int len = number_string_cache()->length();
2940   for (int i = 0; i < len; i++) {
2941     number_string_cache()->set_undefined(this, i);
2942   }
2943 }
2944
2945
2946 static inline int double_get_hash(double d) {
2947   DoubleRepresentation rep(d);
2948   return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2949 }
2950
2951
2952 static inline int smi_get_hash(Smi* smi) {
2953   return smi->value();
2954 }
2955
2956
2957 Object* Heap::GetNumberStringCache(Object* number) {
2958   int hash;
2959   int mask = (number_string_cache()->length() >> 1) - 1;
2960   if (number->IsSmi()) {
2961     hash = smi_get_hash(Smi::cast(number)) & mask;
2962   } else {
2963     hash = double_get_hash(number->Number()) & mask;
2964   }
2965   Object* key = number_string_cache()->get(hash * 2);
2966   if (key == number) {
2967     return String::cast(number_string_cache()->get(hash * 2 + 1));
2968   } else if (key->IsHeapNumber() &&
2969              number->IsHeapNumber() &&
2970              key->Number() == number->Number()) {
2971     return String::cast(number_string_cache()->get(hash * 2 + 1));
2972   }
2973   return undefined_value();
2974 }
2975
2976
2977 void Heap::SetNumberStringCache(Object* number, String* string) {
2978   int hash;
2979   int mask = (number_string_cache()->length() >> 1) - 1;
2980   if (number->IsSmi()) {
2981     hash = smi_get_hash(Smi::cast(number)) & mask;
2982   } else {
2983     hash = double_get_hash(number->Number()) & mask;
2984   }
2985   if (number_string_cache()->get(hash * 2) != undefined_value() &&
2986       number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2987     // The first time we have a hash collision, we move to the full sized
2988     // number string cache.
2989     AllocateFullSizeNumberStringCache();
2990     return;
2991   }
2992   number_string_cache()->set(hash * 2, number);
2993   number_string_cache()->set(hash * 2 + 1, string);
2994 }
2995
2996
2997 MaybeObject* Heap::NumberToString(Object* number,
2998                                   bool check_number_string_cache) {
2999   isolate_->counters()->number_to_string_runtime()->Increment();
3000   if (check_number_string_cache) {
3001     Object* cached = GetNumberStringCache(number);
3002     if (cached != undefined_value()) {
3003       return cached;
3004     }
3005   }
3006
3007   char arr[100];
3008   Vector<char> buffer(arr, ARRAY_SIZE(arr));
3009   const char* str;
3010   if (number->IsSmi()) {
3011     int num = Smi::cast(number)->value();
3012     str = IntToCString(num, buffer);
3013   } else {
3014     double num = HeapNumber::cast(number)->value();
3015     str = DoubleToCString(num, buffer);
3016   }
3017
3018   Object* js_string;
3019   MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
3020   if (maybe_js_string->ToObject(&js_string)) {
3021     SetNumberStringCache(number, String::cast(js_string));
3022   }
3023   return maybe_js_string;
3024 }
3025
3026
3027 MaybeObject* Heap::Uint32ToString(uint32_t value,
3028                                   bool check_number_string_cache) {
3029   Object* number;
3030   MaybeObject* maybe = NumberFromUint32(value);
3031   if (!maybe->To<Object>(&number)) return maybe;
3032   return NumberToString(number, check_number_string_cache);
3033 }
3034
3035
3036 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
3037   return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
3038 }
3039
3040
3041 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
3042     ExternalArrayType array_type) {
3043   switch (array_type) {
3044     case kExternalByteArray:
3045       return kExternalByteArrayMapRootIndex;
3046     case kExternalUnsignedByteArray:
3047       return kExternalUnsignedByteArrayMapRootIndex;
3048     case kExternalShortArray:
3049       return kExternalShortArrayMapRootIndex;
3050     case kExternalUnsignedShortArray:
3051       return kExternalUnsignedShortArrayMapRootIndex;
3052     case kExternalIntArray:
3053       return kExternalIntArrayMapRootIndex;
3054     case kExternalUnsignedIntArray:
3055       return kExternalUnsignedIntArrayMapRootIndex;
3056     case kExternalFloatArray:
3057       return kExternalFloatArrayMapRootIndex;
3058     case kExternalDoubleArray:
3059       return kExternalDoubleArrayMapRootIndex;
3060     case kExternalPixelArray:
3061       return kExternalPixelArrayMapRootIndex;
3062     default:
3063       UNREACHABLE();
3064       return kUndefinedValueRootIndex;
3065   }
3066 }
3067
3068
3069 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
3070   // We need to distinguish the minus zero value and this cannot be
3071   // done after conversion to int. Doing this by comparing bit
3072   // patterns is faster than using fpclassify() et al.
3073   static const DoubleRepresentation minus_zero(-0.0);
3074
3075   DoubleRepresentation rep(value);
3076   if (rep.bits == minus_zero.bits) {
3077     return AllocateHeapNumber(-0.0, pretenure);
3078   }
3079
3080   int int_value = FastD2I(value);
3081   if (value == int_value && Smi::IsValid(int_value)) {
3082     return Smi::FromInt(int_value);
3083   }
3084
3085   // Materialize the value in the heap.
3086   return AllocateHeapNumber(value, pretenure);
3087 }
3088
3089
3090 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
3091   // Statically ensure that it is safe to allocate foreigns in paged spaces.
3092   STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
3093   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3094   Foreign* result;
3095   MaybeObject* maybe_result = Allocate(foreign_map(), space);
3096   if (!maybe_result->To(&result)) return maybe_result;
3097   result->set_foreign_address(address);
3098   return result;
3099 }
3100
3101
3102 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
3103   SharedFunctionInfo* share;
3104   MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
3105   if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
3106
3107   // Set pointer fields.
3108   share->set_name(name);
3109   Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
3110   share->set_code(illegal);
3111   share->ClearOptimizedCodeMap();
3112   share->set_scope_info(ScopeInfo::Empty());
3113   Code* construct_stub =
3114       isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
3115   share->set_construct_stub(construct_stub);
3116   share->set_instance_class_name(Object_symbol());
3117   share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
3118   share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
3119   share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
3120   share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
3121   share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
3122   share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
3123   share->set_ast_node_count(0);
3124   share->set_stress_deopt_counter(FLAG_deopt_every_n_times);
3125   share->set_counters(0);
3126
3127   // Set integer fields (smi or int, depending on the architecture).
3128   share->set_length(0);
3129   share->set_formal_parameter_count(0);
3130   share->set_expected_nof_properties(0);
3131   share->set_num_literals(0);
3132   share->set_start_position_and_type(0);
3133   share->set_end_position(0);
3134   share->set_function_token_position(0);
3135   // All compiler hints default to false or 0.
3136   share->set_compiler_hints(0);
3137   share->set_this_property_assignments_count(0);
3138   share->set_opt_count(0);
3139
3140   return share;
3141 }
3142
3143
3144 MaybeObject* Heap::AllocateJSMessageObject(String* type,
3145                                            JSArray* arguments,
3146                                            int start_position,
3147                                            int end_position,
3148                                            Object* script,
3149                                            Object* stack_trace,
3150                                            Object* stack_frames) {
3151   Object* result;
3152   { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
3153     if (!maybe_result->ToObject(&result)) return maybe_result;
3154   }
3155   JSMessageObject* message = JSMessageObject::cast(result);
3156   message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3157   message->initialize_elements();
3158   message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3159   message->set_type(type);
3160   message->set_arguments(arguments);
3161   message->set_start_position(start_position);
3162   message->set_end_position(end_position);
3163   message->set_script(script);
3164   message->set_stack_trace(stack_trace);
3165   message->set_stack_frames(stack_frames);
3166   return result;
3167 }
3168
3169
3170
3171 // Returns true for a character in a range.  Both limits are inclusive.
3172 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
3173   // This makes uses of the the unsigned wraparound.
3174   return character - from <= to - from;
3175 }
3176
3177
3178 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
3179     Heap* heap,
3180     uint32_t c1,
3181     uint32_t c2) {
3182   String* symbol;
3183   // Numeric strings have a different hash algorithm not known by
3184   // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
3185   if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
3186       heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
3187     return symbol;
3188   // Now we know the length is 2, we might as well make use of that fact
3189   // when building the new string.
3190   } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) {  // We can do this
3191     ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1));  // because of this.
3192     Object* result;
3193     { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
3194       if (!maybe_result->ToObject(&result)) return maybe_result;
3195     }
3196     char* dest = SeqAsciiString::cast(result)->GetChars();
3197     dest[0] = c1;
3198     dest[1] = c2;
3199     return result;
3200   } else {
3201     Object* result;
3202     { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
3203       if (!maybe_result->ToObject(&result)) return maybe_result;
3204     }
3205     uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3206     dest[0] = c1;
3207     dest[1] = c2;
3208     return result;
3209   }
3210 }
3211
3212
3213 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
3214   int first_length = first->length();
3215   if (first_length == 0) {
3216     return second;
3217   }
3218
3219   int second_length = second->length();
3220   if (second_length == 0) {
3221     return first;
3222   }
3223
3224   int length = first_length + second_length;
3225
3226   // Optimization for 2-byte strings often used as keys in a decompression
3227   // dictionary.  Check whether we already have the string in the symbol
3228   // table to prevent creation of many unneccesary strings.
3229   if (length == 2) {
3230     unsigned c1 = first->Get(0);
3231     unsigned c2 = second->Get(0);
3232     return MakeOrFindTwoCharacterString(this, c1, c2);
3233   }
3234
3235   bool first_is_ascii = first->IsAsciiRepresentation();
3236   bool second_is_ascii = second->IsAsciiRepresentation();
3237   bool is_ascii = first_is_ascii && second_is_ascii;
3238
3239   // Make sure that an out of memory exception is thrown if the length
3240   // of the new cons string is too large.
3241   if (length > String::kMaxLength || length < 0) {
3242     isolate()->context()->mark_out_of_memory();
3243     return Failure::OutOfMemoryException();
3244   }
3245
3246   bool is_ascii_data_in_two_byte_string = false;
3247   if (!is_ascii) {
3248     // At least one of the strings uses two-byte representation so we
3249     // can't use the fast case code for short ASCII strings below, but
3250     // we can try to save memory if all chars actually fit in ASCII.
3251     is_ascii_data_in_two_byte_string =
3252         first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3253     if (is_ascii_data_in_two_byte_string) {
3254       isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3255     }
3256   }
3257
3258   // If the resulting string is small make a flat string.
3259   if (length < ConsString::kMinLength) {
3260     // Note that neither of the two inputs can be a slice because:
3261     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3262     ASSERT(first->IsFlat());
3263     ASSERT(second->IsFlat());
3264     if (is_ascii) {
3265       Object* result;
3266       { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3267         if (!maybe_result->ToObject(&result)) return maybe_result;
3268       }
3269       // Copy the characters into the new object.
3270       char* dest = SeqAsciiString::cast(result)->GetChars();
3271       // Copy first part.
3272       const char* src;
3273       if (first->IsExternalString()) {
3274         src = ExternalAsciiString::cast(first)->GetChars();
3275       } else {
3276         src = SeqAsciiString::cast(first)->GetChars();
3277       }
3278       for (int i = 0; i < first_length; i++) *dest++ = src[i];
3279       // Copy second part.
3280       if (second->IsExternalString()) {
3281         src = ExternalAsciiString::cast(second)->GetChars();
3282       } else {
3283         src = SeqAsciiString::cast(second)->GetChars();
3284       }
3285       for (int i = 0; i < second_length; i++) *dest++ = src[i];
3286       return result;
3287     } else {
3288       if (is_ascii_data_in_two_byte_string) {
3289         Object* result;
3290         { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3291           if (!maybe_result->ToObject(&result)) return maybe_result;
3292         }
3293         // Copy the characters into the new object.
3294         char* dest = SeqAsciiString::cast(result)->GetChars();
3295         String::WriteToFlat(first, dest, 0, first_length);
3296         String::WriteToFlat(second, dest + first_length, 0, second_length);
3297         isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3298         return result;
3299       }
3300
3301       Object* result;
3302       { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3303         if (!maybe_result->ToObject(&result)) return maybe_result;
3304       }
3305       // Copy the characters into the new object.
3306       uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3307       String::WriteToFlat(first, dest, 0, first_length);
3308       String::WriteToFlat(second, dest + first_length, 0, second_length);
3309       return result;
3310     }
3311   }
3312
3313   Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3314       cons_ascii_string_map() : cons_string_map();
3315
3316   Object* result;
3317   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3318     if (!maybe_result->ToObject(&result)) return maybe_result;
3319   }
3320
3321   AssertNoAllocation no_gc;
3322   ConsString* cons_string = ConsString::cast(result);
3323   WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3324   cons_string->set_length(length);
3325   cons_string->set_hash_field(String::kEmptyHashField);
3326   cons_string->set_first(first, mode);
3327   cons_string->set_second(second, mode);
3328   return result;
3329 }
3330
3331
3332 MaybeObject* Heap::AllocateSubString(String* buffer,
3333                                      int start,
3334                                      int end,
3335                                      PretenureFlag pretenure) {
3336   int length = end - start;
3337   if (length <= 0) {
3338     return empty_string();
3339   } else if (length == 1) {
3340     return LookupSingleCharacterStringFromCode(buffer->Get(start));
3341   } else if (length == 2) {
3342     // Optimization for 2-byte strings often used as keys in a decompression
3343     // dictionary.  Check whether we already have the string in the symbol
3344     // table to prevent creation of many unneccesary strings.
3345     unsigned c1 = buffer->Get(start);
3346     unsigned c2 = buffer->Get(start + 1);
3347     return MakeOrFindTwoCharacterString(this, c1, c2);
3348   }
3349
3350   // Make an attempt to flatten the buffer to reduce access time.
3351   buffer = buffer->TryFlattenGetString();
3352
3353   if (!FLAG_string_slices ||
3354       !buffer->IsFlat() ||
3355       length < SlicedString::kMinLength ||
3356       pretenure == TENURED) {
3357     Object* result;
3358     // WriteToFlat takes care of the case when an indirect string has a
3359     // different encoding from its underlying string.  These encodings may
3360     // differ because of externalization.
3361     bool is_ascii = buffer->IsAsciiRepresentation();
3362     { MaybeObject* maybe_result = is_ascii
3363                                   ? AllocateRawAsciiString(length, pretenure)
3364                                   : AllocateRawTwoByteString(length, pretenure);
3365       if (!maybe_result->ToObject(&result)) return maybe_result;
3366     }
3367     String* string_result = String::cast(result);
3368     // Copy the characters into the new object.
3369     if (is_ascii) {
3370       ASSERT(string_result->IsAsciiRepresentation());
3371       char* dest = SeqAsciiString::cast(string_result)->GetChars();
3372       String::WriteToFlat(buffer, dest, start, end);
3373     } else {
3374       ASSERT(string_result->IsTwoByteRepresentation());
3375       uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3376       String::WriteToFlat(buffer, dest, start, end);
3377     }
3378     return result;
3379   }
3380
3381   ASSERT(buffer->IsFlat());
3382 #if DEBUG
3383   if (FLAG_verify_heap) {
3384     buffer->StringVerify();
3385   }
3386 #endif
3387
3388   Object* result;
3389   // When slicing an indirect string we use its encoding for a newly created
3390   // slice and don't check the encoding of the underlying string.  This is safe
3391   // even if the encodings are different because of externalization.  If an
3392   // indirect ASCII string is pointing to a two-byte string, the two-byte char
3393   // codes of the underlying string must still fit into ASCII (because
3394   // externalization must not change char codes).
3395   { Map* map = buffer->IsAsciiRepresentation()
3396                  ? sliced_ascii_string_map()
3397                  : sliced_string_map();
3398     MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3399     if (!maybe_result->ToObject(&result)) return maybe_result;
3400   }
3401
3402   AssertNoAllocation no_gc;
3403   SlicedString* sliced_string = SlicedString::cast(result);
3404   sliced_string->set_length(length);
3405   sliced_string->set_hash_field(String::kEmptyHashField);
3406   if (buffer->IsConsString()) {
3407     ConsString* cons = ConsString::cast(buffer);
3408     ASSERT(cons->second()->length() == 0);
3409     sliced_string->set_parent(cons->first());
3410     sliced_string->set_offset(start);
3411   } else if (buffer->IsSlicedString()) {
3412     // Prevent nesting sliced strings.
3413     SlicedString* parent_slice = SlicedString::cast(buffer);
3414     sliced_string->set_parent(parent_slice->parent());
3415     sliced_string->set_offset(start + parent_slice->offset());
3416   } else {
3417     sliced_string->set_parent(buffer);
3418     sliced_string->set_offset(start);
3419   }
3420   ASSERT(sliced_string->parent()->IsSeqString() ||
3421          sliced_string->parent()->IsExternalString());
3422   return result;
3423 }
3424
3425
3426 MaybeObject* Heap::AllocateExternalStringFromAscii(
3427     const ExternalAsciiString::Resource* resource) {
3428   size_t length = resource->length();
3429   if (length > static_cast<size_t>(String::kMaxLength)) {
3430     isolate()->context()->mark_out_of_memory();
3431     return Failure::OutOfMemoryException();
3432   }
3433
3434   ASSERT(String::IsAscii(resource->data(), static_cast<int>(length)));
3435
3436   Map* map = external_ascii_string_map();
3437   Object* result;
3438   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3439     if (!maybe_result->ToObject(&result)) return maybe_result;
3440   }
3441
3442   ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3443   external_string->set_length(static_cast<int>(length));
3444   external_string->set_hash_field(String::kEmptyHashField);
3445   external_string->set_resource(resource);
3446
3447   return result;
3448 }
3449
3450
3451 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3452     const ExternalTwoByteString::Resource* resource) {
3453   size_t length = resource->length();
3454   if (length > static_cast<size_t>(String::kMaxLength)) {
3455     isolate()->context()->mark_out_of_memory();
3456     return Failure::OutOfMemoryException();
3457   }
3458
3459   // For small strings we check whether the resource contains only
3460   // ASCII characters.  If yes, we use a different string map.
3461   static const size_t kAsciiCheckLengthLimit = 32;
3462   bool is_ascii = length <= kAsciiCheckLengthLimit &&
3463       String::IsAscii(resource->data(), static_cast<int>(length));
3464   Map* map = is_ascii ?
3465       external_string_with_ascii_data_map() : external_string_map();
3466   Object* result;
3467   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3468     if (!maybe_result->ToObject(&result)) return maybe_result;
3469   }
3470
3471   ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3472   external_string->set_length(static_cast<int>(length));
3473   external_string->set_hash_field(String::kEmptyHashField);
3474   external_string->set_resource(resource);
3475
3476   return result;
3477 }
3478
3479
3480 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3481   if (code <= String::kMaxAsciiCharCode) {
3482     Object* value = single_character_string_cache()->get(code);
3483     if (value != undefined_value()) return value;
3484
3485     char buffer[1];
3486     buffer[0] = static_cast<char>(code);
3487     Object* result;
3488     MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3489
3490     if (!maybe_result->ToObject(&result)) return maybe_result;
3491     single_character_string_cache()->set(code, result);
3492     return result;
3493   }
3494
3495   Object* result;
3496   { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3497     if (!maybe_result->ToObject(&result)) return maybe_result;
3498   }
3499   String* answer = String::cast(result);
3500   answer->Set(0, code);
3501   return answer;
3502 }
3503
3504
3505 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3506   if (length < 0 || length > ByteArray::kMaxLength) {
3507     return Failure::OutOfMemoryException();
3508   }
3509   if (pretenure == NOT_TENURED) {
3510     return AllocateByteArray(length);
3511   }
3512   int size = ByteArray::SizeFor(length);
3513   Object* result;
3514   { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3515                    ? old_data_space_->AllocateRaw(size)
3516                    : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3517     if (!maybe_result->ToObject(&result)) return maybe_result;
3518   }
3519
3520   reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3521       byte_array_map());
3522   reinterpret_cast<ByteArray*>(result)->set_length(length);
3523   return result;
3524 }
3525
3526
3527 MaybeObject* Heap::AllocateByteArray(int length) {
3528   if (length < 0 || length > ByteArray::kMaxLength) {
3529     return Failure::OutOfMemoryException();
3530   }
3531   int size = ByteArray::SizeFor(length);
3532   AllocationSpace space =
3533       (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3534   Object* result;
3535   { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3536     if (!maybe_result->ToObject(&result)) return maybe_result;
3537   }
3538
3539   reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3540       byte_array_map());
3541   reinterpret_cast<ByteArray*>(result)->set_length(length);
3542   return result;
3543 }
3544
3545
3546 void Heap::CreateFillerObjectAt(Address addr, int size) {
3547   if (size == 0) return;
3548   HeapObject* filler = HeapObject::FromAddress(addr);
3549   if (size == kPointerSize) {
3550     filler->set_map_no_write_barrier(one_pointer_filler_map());
3551   } else if (size == 2 * kPointerSize) {
3552     filler->set_map_no_write_barrier(two_pointer_filler_map());
3553   } else {
3554     filler->set_map_no_write_barrier(free_space_map());
3555     FreeSpace::cast(filler)->set_size(size);
3556   }
3557 }
3558
3559
3560 MaybeObject* Heap::AllocateExternalArray(int length,
3561                                          ExternalArrayType array_type,
3562                                          void* external_pointer,
3563                                          PretenureFlag pretenure) {
3564   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3565   Object* result;
3566   { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3567                                             space,
3568                                             OLD_DATA_SPACE);
3569     if (!maybe_result->ToObject(&result)) return maybe_result;
3570   }
3571
3572   reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3573       MapForExternalArrayType(array_type));
3574   reinterpret_cast<ExternalArray*>(result)->set_length(length);
3575   reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3576       external_pointer);
3577
3578   return result;
3579 }
3580
3581
3582 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3583                               Code::Flags flags,
3584                               Handle<Object> self_reference,
3585                               bool immovable) {
3586   // Allocate ByteArray before the Code object, so that we do not risk
3587   // leaving uninitialized Code object (and breaking the heap).
3588   ByteArray* reloc_info;
3589   MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3590   if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3591
3592   // Compute size.
3593   int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3594   int obj_size = Code::SizeFor(body_size);
3595   ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3596   MaybeObject* maybe_result;
3597   // Large code objects and code objects which should stay at a fixed address
3598   // are allocated in large object space.
3599   if (obj_size > code_space()->AreaSize() || immovable) {
3600     maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3601   } else {
3602     maybe_result = code_space_->AllocateRaw(obj_size);
3603   }
3604
3605   Object* result;
3606   if (!maybe_result->ToObject(&result)) return maybe_result;
3607
3608   // Initialize the object
3609   HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3610   Code* code = Code::cast(result);
3611   ASSERT(!isolate_->code_range()->exists() ||
3612       isolate_->code_range()->contains(code->address()));
3613   code->set_instruction_size(desc.instr_size);
3614   code->set_relocation_info(reloc_info);
3615   code->set_flags(flags);
3616   if (code->is_call_stub() || code->is_keyed_call_stub()) {
3617     code->set_check_type(RECEIVER_MAP_CHECK);
3618   }
3619   code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3620   code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3621   code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3622   code->set_gc_metadata(Smi::FromInt(0));
3623   code->set_ic_age(global_ic_age_);
3624   // Allow self references to created code object by patching the handle to
3625   // point to the newly allocated Code object.
3626   if (!self_reference.is_null()) {
3627     *(self_reference.location()) = code;
3628   }
3629   // Migrate generated code.
3630   // The generated code can contain Object** values (typically from handles)
3631   // that are dereferenced during the copy to point directly to the actual heap
3632   // objects. These pointers can include references to the code object itself,
3633   // through the self_reference parameter.
3634   code->CopyFrom(desc);
3635
3636 #ifdef DEBUG
3637   if (FLAG_verify_heap) {
3638     code->Verify();
3639   }
3640 #endif
3641   return code;
3642 }
3643
3644
3645 MaybeObject* Heap::CopyCode(Code* code) {
3646   // Allocate an object the same size as the code object.
3647   int obj_size = code->Size();
3648   MaybeObject* maybe_result;
3649   if (obj_size > code_space()->AreaSize()) {
3650     maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3651   } else {
3652     maybe_result = code_space_->AllocateRaw(obj_size);
3653   }
3654
3655   Object* result;
3656   if (!maybe_result->ToObject(&result)) return maybe_result;
3657
3658   // Copy code object.
3659   Address old_addr = code->address();
3660   Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3661   CopyBlock(new_addr, old_addr, obj_size);
3662   // Relocate the copy.
3663   Code* new_code = Code::cast(result);
3664   ASSERT(!isolate_->code_range()->exists() ||
3665       isolate_->code_range()->contains(code->address()));
3666   new_code->Relocate(new_addr - old_addr);
3667   return new_code;
3668 }
3669
3670
3671 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3672   // Allocate ByteArray before the Code object, so that we do not risk
3673   // leaving uninitialized Code object (and breaking the heap).
3674   Object* reloc_info_array;
3675   { MaybeObject* maybe_reloc_info_array =
3676         AllocateByteArray(reloc_info.length(), TENURED);
3677     if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3678       return maybe_reloc_info_array;
3679     }
3680   }
3681
3682   int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3683
3684   int new_obj_size = Code::SizeFor(new_body_size);
3685
3686   Address old_addr = code->address();
3687
3688   size_t relocation_offset =
3689       static_cast<size_t>(code->instruction_end() - old_addr);
3690
3691   MaybeObject* maybe_result;
3692   if (new_obj_size > code_space()->AreaSize()) {
3693     maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3694   } else {
3695     maybe_result = code_space_->AllocateRaw(new_obj_size);
3696   }
3697
3698   Object* result;
3699   if (!maybe_result->ToObject(&result)) return maybe_result;
3700
3701   // Copy code object.
3702   Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3703
3704   // Copy header and instructions.
3705   memcpy(new_addr, old_addr, relocation_offset);
3706
3707   Code* new_code = Code::cast(result);
3708   new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3709
3710   // Copy patched rinfo.
3711   memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3712
3713   // Relocate the copy.
3714   ASSERT(!isolate_->code_range()->exists() ||
3715       isolate_->code_range()->contains(code->address()));
3716   new_code->Relocate(new_addr - old_addr);
3717
3718 #ifdef DEBUG
3719   if (FLAG_verify_heap) {
3720     code->Verify();
3721   }
3722 #endif
3723   return new_code;
3724 }
3725
3726
3727 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3728   ASSERT(gc_state_ == NOT_IN_GC);
3729   ASSERT(map->instance_type() != MAP_TYPE);
3730   // If allocation failures are disallowed, we may allocate in a different
3731   // space when new space is full and the object is not a large object.
3732   AllocationSpace retry_space =
3733       (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3734   Object* result;
3735   { MaybeObject* maybe_result =
3736         AllocateRaw(map->instance_size(), space, retry_space);
3737     if (!maybe_result->ToObject(&result)) return maybe_result;
3738   }
3739   // No need for write barrier since object is white and map is in old space.
3740   HeapObject::cast(result)->set_map_no_write_barrier(map);
3741   return result;
3742 }
3743
3744
3745 void Heap::InitializeFunction(JSFunction* function,
3746                               SharedFunctionInfo* shared,
3747                               Object* prototype) {
3748   ASSERT(!prototype->IsMap());
3749   function->initialize_properties();
3750   function->initialize_elements();
3751   function->set_shared(shared);
3752   function->set_code(shared->code());
3753   function->set_prototype_or_initial_map(prototype);
3754   function->set_context(undefined_value());
3755   function->set_literals_or_bindings(empty_fixed_array());
3756   function->set_next_function_link(undefined_value());
3757 }
3758
3759
3760 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3761   // Allocate the prototype.  Make sure to use the object function
3762   // from the function's context, since the function can be from a
3763   // different context.
3764   JSFunction* object_function =
3765       function->context()->native_context()->object_function();
3766
3767   // Each function prototype gets a copy of the object function map.
3768   // This avoid unwanted sharing of maps between prototypes of different
3769   // constructors.
3770   Map* new_map;
3771   ASSERT(object_function->has_initial_map());
3772   MaybeObject* maybe_map = object_function->initial_map()->Copy();
3773   if (!maybe_map->To(&new_map)) return maybe_map;
3774
3775   Object* prototype;
3776   MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3777   if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3778
3779   // When creating the prototype for the function we must set its
3780   // constructor to the function.
3781   MaybeObject* maybe_failure =
3782       JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3783           constructor_symbol(), function, DONT_ENUM);
3784   if (maybe_failure->IsFailure()) return maybe_failure;
3785
3786   return prototype;
3787 }
3788
3789
3790 MaybeObject* Heap::AllocateFunction(Map* function_map,
3791                                     SharedFunctionInfo* shared,
3792                                     Object* prototype,
3793                                     PretenureFlag pretenure) {
3794   AllocationSpace space =
3795       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3796   Object* result;
3797   { MaybeObject* maybe_result = Allocate(function_map, space);
3798     if (!maybe_result->ToObject(&result)) return maybe_result;
3799   }
3800   InitializeFunction(JSFunction::cast(result), shared, prototype);
3801   return result;
3802 }
3803
3804
3805 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3806   // To get fast allocation and map sharing for arguments objects we
3807   // allocate them based on an arguments boilerplate.
3808
3809   JSObject* boilerplate;
3810   int arguments_object_size;
3811   bool strict_mode_callee = callee->IsJSFunction() &&
3812       !JSFunction::cast(callee)->shared()->is_classic_mode();
3813   if (strict_mode_callee) {
3814     boilerplate =
3815         isolate()->context()->native_context()->
3816             strict_mode_arguments_boilerplate();
3817     arguments_object_size = kArgumentsObjectSizeStrict;
3818   } else {
3819     boilerplate =
3820         isolate()->context()->native_context()->arguments_boilerplate();
3821     arguments_object_size = kArgumentsObjectSize;
3822   }
3823
3824   // This calls Copy directly rather than using Heap::AllocateRaw so we
3825   // duplicate the check here.
3826   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3827
3828   // Check that the size of the boilerplate matches our
3829   // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3830   // on the size being a known constant.
3831   ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3832
3833   // Do the allocation.
3834   Object* result;
3835   { MaybeObject* maybe_result =
3836         AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3837     if (!maybe_result->ToObject(&result)) return maybe_result;
3838   }
3839
3840   // Copy the content. The arguments boilerplate doesn't have any
3841   // fields that point to new space so it's safe to skip the write
3842   // barrier here.
3843   CopyBlock(HeapObject::cast(result)->address(),
3844             boilerplate->address(),
3845             JSObject::kHeaderSize);
3846
3847   // Set the length property.
3848   JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3849                                                 Smi::FromInt(length),
3850                                                 SKIP_WRITE_BARRIER);
3851   // Set the callee property for non-strict mode arguments object only.
3852   if (!strict_mode_callee) {
3853     JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3854                                                   callee);
3855   }
3856
3857   // Check the state of the object
3858   ASSERT(JSObject::cast(result)->HasFastProperties());
3859   ASSERT(JSObject::cast(result)->HasFastObjectElements());
3860
3861   return result;
3862 }
3863
3864
3865 static bool HasDuplicates(DescriptorArray* descriptors) {
3866   int count = descriptors->number_of_descriptors();
3867   if (count > 1) {
3868     String* prev_key = descriptors->GetKey(0);
3869     for (int i = 1; i != count; i++) {
3870       String* current_key = descriptors->GetKey(i);
3871       if (prev_key == current_key) return true;
3872       prev_key = current_key;
3873     }
3874   }
3875   return false;
3876 }
3877
3878
3879 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3880   ASSERT(!fun->has_initial_map());
3881
3882   // First create a new map with the size and number of in-object properties
3883   // suggested by the function.
3884   int instance_size = fun->shared()->CalculateInstanceSize();
3885   int in_object_properties = fun->shared()->CalculateInObjectProperties();
3886   Map* map;
3887   MaybeObject* maybe_map = AllocateMap(JS_OBJECT_TYPE, instance_size);
3888   if (!maybe_map->To(&map)) return maybe_map;
3889
3890   // Fetch or allocate prototype.
3891   Object* prototype;
3892   if (fun->has_instance_prototype()) {
3893     prototype = fun->instance_prototype();
3894   } else {
3895     MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3896     if (!maybe_prototype->To(&prototype)) return maybe_prototype;
3897   }
3898   map->set_inobject_properties(in_object_properties);
3899   map->set_unused_property_fields(in_object_properties);
3900   map->set_prototype(prototype);
3901   ASSERT(map->has_fast_object_elements());
3902
3903   // If the function has only simple this property assignments add
3904   // field descriptors for these to the initial map as the object
3905   // cannot be constructed without having these properties.  Guard by
3906   // the inline_new flag so we only change the map if we generate a
3907   // specialized construct stub.
3908   ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3909   if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3910     int count = fun->shared()->this_property_assignments_count();
3911     if (count > in_object_properties) {
3912       // Inline constructor can only handle inobject properties.
3913       fun->shared()->ForbidInlineConstructor();
3914     } else {
3915       DescriptorArray* descriptors;
3916       MaybeObject* maybe_descriptors = DescriptorArray::Allocate(count);
3917       if (!maybe_descriptors->To(&descriptors)) return maybe_descriptors;
3918
3919       DescriptorArray::WhitenessWitness witness(descriptors);
3920       for (int i = 0; i < count; i++) {
3921         String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3922         ASSERT(name->IsSymbol());
3923         FieldDescriptor field(name, i, NONE, i + 1);
3924         descriptors->Set(i, &field, witness);
3925       }
3926       descriptors->Sort();
3927
3928       // The descriptors may contain duplicates because the compiler does not
3929       // guarantee the uniqueness of property names (it would have required
3930       // quadratic time). Once the descriptors are sorted we can check for
3931       // duplicates in linear time.
3932       if (HasDuplicates(descriptors)) {
3933         fun->shared()->ForbidInlineConstructor();
3934       } else {
3935         MaybeObject* maybe_failure = map->InitializeDescriptors(descriptors);
3936         if (maybe_failure->IsFailure()) return maybe_failure;
3937         map->set_pre_allocated_property_fields(count);
3938         map->set_unused_property_fields(in_object_properties - count);
3939       }
3940     }
3941   }
3942
3943   fun->shared()->StartInobjectSlackTracking(map);
3944
3945   return map;
3946 }
3947
3948
3949 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3950                                      FixedArray* properties,
3951                                      Map* map) {
3952   obj->set_properties(properties);
3953   obj->initialize_elements();
3954   // TODO(1240798): Initialize the object's body using valid initial values
3955   // according to the object's initial map.  For example, if the map's
3956   // instance type is JS_ARRAY_TYPE, the length field should be initialized
3957   // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3958   // fixed array (e.g. Heap::empty_fixed_array()).  Currently, the object
3959   // verification code has to cope with (temporarily) invalid objects.  See
3960   // for example, JSArray::JSArrayVerify).
3961   Object* filler;
3962   // We cannot always fill with one_pointer_filler_map because objects
3963   // created from API functions expect their internal fields to be initialized
3964   // with undefined_value.
3965   // Pre-allocated fields need to be initialized with undefined_value as well
3966   // so that object accesses before the constructor completes (e.g. in the
3967   // debugger) will not cause a crash.
3968   if (map->constructor()->IsJSFunction() &&
3969       JSFunction::cast(map->constructor())->shared()->
3970           IsInobjectSlackTrackingInProgress()) {
3971     // We might want to shrink the object later.
3972     ASSERT(obj->GetInternalFieldCount() == 0);
3973     filler = Heap::one_pointer_filler_map();
3974   } else {
3975     filler = Heap::undefined_value();
3976   }
3977   obj->InitializeBody(map, Heap::undefined_value(), filler);
3978 }
3979
3980
3981 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3982   // JSFunctions should be allocated using AllocateFunction to be
3983   // properly initialized.
3984   ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3985
3986   // Both types of global objects should be allocated using
3987   // AllocateGlobalObject to be properly initialized.
3988   ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3989   ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3990
3991   // Allocate the backing storage for the properties.
3992   int prop_size =
3993       map->pre_allocated_property_fields() +
3994       map->unused_property_fields() -
3995       map->inobject_properties();
3996   ASSERT(prop_size >= 0);
3997   Object* properties;
3998   { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3999     if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4000   }
4001
4002   // Allocate the JSObject.
4003   AllocationSpace space =
4004       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4005   if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
4006   Object* obj;
4007   { MaybeObject* maybe_obj = Allocate(map, space);
4008     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4009   }
4010
4011   // Initialize the JSObject.
4012   InitializeJSObjectFromMap(JSObject::cast(obj),
4013                             FixedArray::cast(properties),
4014                             map);
4015   ASSERT(JSObject::cast(obj)->HasFastSmiOrObjectElements());
4016   return obj;
4017 }
4018
4019
4020 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
4021                                     PretenureFlag pretenure) {
4022   // Allocate the initial map if absent.
4023   if (!constructor->has_initial_map()) {
4024     Object* initial_map;
4025     { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
4026       if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
4027     }
4028     constructor->set_initial_map(Map::cast(initial_map));
4029     Map::cast(initial_map)->set_constructor(constructor);
4030   }
4031   // Allocate the object based on the constructors initial map.
4032   MaybeObject* result = AllocateJSObjectFromMap(
4033       constructor->initial_map(), pretenure);
4034 #ifdef DEBUG
4035   // Make sure result is NOT a global object if valid.
4036   Object* non_failure;
4037   ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
4038 #endif
4039   return result;
4040 }
4041
4042
4043 MaybeObject* Heap::AllocateJSModule(Context* context, ScopeInfo* scope_info) {
4044   // Allocate a fresh map. Modules do not have a prototype.
4045   Map* map;
4046   MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
4047   if (!maybe_map->To(&map)) return maybe_map;
4048   // Allocate the object based on the map.
4049   JSModule* module;
4050   MaybeObject* maybe_module = AllocateJSObjectFromMap(map, TENURED);
4051   if (!maybe_module->To(&module)) return maybe_module;
4052   module->set_context(context);
4053   module->set_scope_info(scope_info);
4054   return module;
4055 }
4056
4057
4058 MaybeObject* Heap::AllocateJSArrayAndStorage(
4059     ElementsKind elements_kind,
4060     int length,
4061     int capacity,
4062     ArrayStorageAllocationMode mode,
4063     PretenureFlag pretenure) {
4064   ASSERT(capacity >= length);
4065   if (length != 0 && mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE) {
4066     elements_kind = GetHoleyElementsKind(elements_kind);
4067   }
4068   MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4069   JSArray* array;
4070   if (!maybe_array->To(&array)) return maybe_array;
4071
4072   if (capacity == 0) {
4073     array->set_length(Smi::FromInt(0));
4074     array->set_elements(empty_fixed_array());
4075     return array;
4076   }
4077
4078   FixedArrayBase* elms;
4079   MaybeObject* maybe_elms = NULL;
4080   if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4081     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
4082       maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
4083     } else {
4084       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
4085       maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
4086     }
4087   } else {
4088     ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
4089     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
4090       maybe_elms = AllocateUninitializedFixedArray(capacity);
4091     } else {
4092       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
4093       maybe_elms = AllocateFixedArrayWithHoles(capacity);
4094     }
4095   }
4096   if (!maybe_elms->To(&elms)) return maybe_elms;
4097
4098   array->set_elements(elms);
4099   array->set_length(Smi::FromInt(length));
4100   return array;
4101 }
4102
4103
4104 MaybeObject* Heap::AllocateJSArrayWithElements(
4105     FixedArrayBase* elements,
4106     ElementsKind elements_kind,
4107     PretenureFlag pretenure) {
4108   MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4109   JSArray* array;
4110   if (!maybe_array->To(&array)) return maybe_array;
4111
4112   array->set_elements(elements);
4113   array->set_length(Smi::FromInt(elements->length()));
4114   array->ValidateElements();
4115   return array;
4116 }
4117
4118
4119 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
4120   // Allocate map.
4121   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4122   // maps. Will probably depend on the identity of the handler object, too.
4123   Map* map;
4124   MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
4125   if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4126   map->set_prototype(prototype);
4127
4128   // Allocate the proxy object.
4129   JSProxy* result;
4130   MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4131   if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
4132   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4133   result->set_handler(handler);
4134   result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4135   return result;
4136 }
4137
4138
4139 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
4140                                            Object* call_trap,
4141                                            Object* construct_trap,
4142                                            Object* prototype) {
4143   // Allocate map.
4144   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4145   // maps. Will probably depend on the identity of the handler object, too.
4146   Map* map;
4147   MaybeObject* maybe_map_obj =
4148       AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
4149   if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4150   map->set_prototype(prototype);
4151
4152   // Allocate the proxy object.
4153   JSFunctionProxy* result;
4154   MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4155   if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
4156   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4157   result->set_handler(handler);
4158   result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4159   result->set_call_trap(call_trap);
4160   result->set_construct_trap(construct_trap);
4161   return result;
4162 }
4163
4164
4165 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
4166   ASSERT(constructor->has_initial_map());
4167   Map* map = constructor->initial_map();
4168   ASSERT(map->is_dictionary_map());
4169
4170   // Make sure no field properties are described in the initial map.
4171   // This guarantees us that normalizing the properties does not
4172   // require us to change property values to JSGlobalPropertyCells.
4173   ASSERT(map->NextFreePropertyIndex() == 0);
4174
4175   // Make sure we don't have a ton of pre-allocated slots in the
4176   // global objects. They will be unused once we normalize the object.
4177   ASSERT(map->unused_property_fields() == 0);
4178   ASSERT(map->inobject_properties() == 0);
4179
4180   // Initial size of the backing store to avoid resize of the storage during
4181   // bootstrapping. The size differs between the JS global object ad the
4182   // builtins object.
4183   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
4184
4185   // Allocate a dictionary object for backing storage.
4186   StringDictionary* dictionary;
4187   MaybeObject* maybe_dictionary =
4188       StringDictionary::Allocate(
4189           map->NumberOfDescribedProperties() * 2 + initial_size);
4190   if (!maybe_dictionary->To(&dictionary)) return maybe_dictionary;
4191
4192   // The global object might be created from an object template with accessors.
4193   // Fill these accessors into the dictionary.
4194   DescriptorArray* descs = map->instance_descriptors();
4195   for (int i = 0; i < descs->number_of_descriptors(); i++) {
4196     PropertyDetails details = descs->GetDetails(i);
4197     ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
4198     PropertyDetails d = PropertyDetails(details.attributes(),
4199                                         CALLBACKS,
4200                                         details.descriptor_index());
4201     Object* value = descs->GetCallbacksObject(i);
4202     MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
4203     if (!maybe_value->ToObject(&value)) return maybe_value;
4204
4205     MaybeObject* maybe_added = dictionary->Add(descs->GetKey(i), value, d);
4206     if (!maybe_added->To(&dictionary)) return maybe_added;
4207   }
4208
4209   // Allocate the global object and initialize it with the backing store.
4210   JSObject* global;
4211   MaybeObject* maybe_global = Allocate(map, OLD_POINTER_SPACE);
4212   if (!maybe_global->To(&global)) return maybe_global;
4213
4214   InitializeJSObjectFromMap(global, dictionary, map);
4215
4216   // Create a new map for the global object.
4217   Map* new_map;
4218   MaybeObject* maybe_map = map->CopyDropDescriptors();
4219   if (!maybe_map->To(&new_map)) return maybe_map;
4220   new_map->set_dictionary_map(true);
4221
4222   // Set up the global object as a normalized object.
4223   global->set_map(new_map);
4224   global->set_properties(dictionary);
4225
4226   // Make sure result is a global object with properties in dictionary.
4227   ASSERT(global->IsGlobalObject());
4228   ASSERT(!global->HasFastProperties());
4229   return global;
4230 }
4231
4232
4233 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4234   // Never used to copy functions.  If functions need to be copied we
4235   // have to be careful to clear the literals array.
4236   SLOW_ASSERT(!source->IsJSFunction());
4237
4238   // Make the clone.
4239   Map* map = source->map();
4240   int object_size = map->instance_size();
4241   Object* clone;
4242
4243   WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4244
4245   // If we're forced to always allocate, we use the general allocation
4246   // functions which may leave us with an object in old space.
4247   if (always_allocate()) {
4248     { MaybeObject* maybe_clone =
4249           AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4250       if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4251     }
4252     Address clone_address = HeapObject::cast(clone)->address();
4253     CopyBlock(clone_address,
4254               source->address(),
4255               object_size);
4256     // Update write barrier for all fields that lie beyond the header.
4257     RecordWrites(clone_address,
4258                  JSObject::kHeaderSize,
4259                  (object_size - JSObject::kHeaderSize) / kPointerSize);
4260   } else {
4261     wb_mode = SKIP_WRITE_BARRIER;
4262     { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4263       if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4264     }
4265     SLOW_ASSERT(InNewSpace(clone));
4266     // Since we know the clone is allocated in new space, we can copy
4267     // the contents without worrying about updating the write barrier.
4268     CopyBlock(HeapObject::cast(clone)->address(),
4269               source->address(),
4270               object_size);
4271   }
4272
4273   SLOW_ASSERT(
4274       JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4275   FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4276   FixedArray* properties = FixedArray::cast(source->properties());
4277   // Update elements if necessary.
4278   if (elements->length() > 0) {
4279     Object* elem;
4280     { MaybeObject* maybe_elem;
4281       if (elements->map() == fixed_cow_array_map()) {
4282         maybe_elem = FixedArray::cast(elements);
4283       } else if (source->HasFastDoubleElements()) {
4284         maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4285       } else {
4286         maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4287       }
4288       if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4289     }
4290     JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4291   }
4292   // Update properties if necessary.
4293   if (properties->length() > 0) {
4294     Object* prop;
4295     { MaybeObject* maybe_prop = CopyFixedArray(properties);
4296       if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4297     }
4298     JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4299   }
4300   // Return the new clone.
4301   return clone;
4302 }
4303
4304
4305 MaybeObject* Heap::ReinitializeJSReceiver(
4306     JSReceiver* object, InstanceType type, int size) {
4307   ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4308
4309   // Allocate fresh map.
4310   // TODO(rossberg): Once we optimize proxies, cache these maps.
4311   Map* map;
4312   MaybeObject* maybe = AllocateMap(type, size);
4313   if (!maybe->To<Map>(&map)) return maybe;
4314
4315   // Check that the receiver has at least the size of the fresh object.
4316   int size_difference = object->map()->instance_size() - map->instance_size();
4317   ASSERT(size_difference >= 0);
4318
4319   map->set_prototype(object->map()->prototype());
4320
4321   // Allocate the backing storage for the properties.
4322   int prop_size = map->unused_property_fields() - map->inobject_properties();
4323   Object* properties;
4324   maybe = AllocateFixedArray(prop_size, TENURED);
4325   if (!maybe->ToObject(&properties)) return maybe;
4326
4327   // Functions require some allocation, which might fail here.
4328   SharedFunctionInfo* shared = NULL;
4329   if (type == JS_FUNCTION_TYPE) {
4330     String* name;
4331     maybe = LookupAsciiSymbol("<freezing call trap>");
4332     if (!maybe->To<String>(&name)) return maybe;
4333     maybe = AllocateSharedFunctionInfo(name);
4334     if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4335   }
4336
4337   // Because of possible retries of this function after failure,
4338   // we must NOT fail after this point, where we have changed the type!
4339
4340   // Reset the map for the object.
4341   object->set_map(map);
4342   JSObject* jsobj = JSObject::cast(object);
4343
4344   // Reinitialize the object from the constructor map.
4345   InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4346
4347   // Functions require some minimal initialization.
4348   if (type == JS_FUNCTION_TYPE) {
4349     map->set_function_with_prototype(true);
4350     InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4351     JSFunction::cast(object)->set_context(
4352         isolate()->context()->native_context());
4353   }
4354
4355   // Put in filler if the new object is smaller than the old.
4356   if (size_difference > 0) {
4357     CreateFillerObjectAt(
4358         object->address() + map->instance_size(), size_difference);
4359   }
4360
4361   return object;
4362 }
4363
4364
4365 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4366                                              JSGlobalProxy* object) {
4367   ASSERT(constructor->has_initial_map());
4368   Map* map = constructor->initial_map();
4369
4370   // Check that the already allocated object has the same size and type as
4371   // objects allocated using the constructor.
4372   ASSERT(map->instance_size() == object->map()->instance_size());
4373   ASSERT(map->instance_type() == object->map()->instance_type());
4374
4375   // Allocate the backing storage for the properties.
4376   int prop_size = map->unused_property_fields() - map->inobject_properties();
4377   Object* properties;
4378   { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4379     if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4380   }
4381
4382   // Reset the map for the object.
4383   object->set_map(constructor->initial_map());
4384
4385   // Reinitialize the object from the constructor map.
4386   InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4387   return object;
4388 }
4389
4390
4391 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4392                                            PretenureFlag pretenure) {
4393   if (string.length() == 1) {
4394     return Heap::LookupSingleCharacterStringFromCode(string[0]);
4395   }
4396   Object* result;
4397   { MaybeObject* maybe_result =
4398         AllocateRawAsciiString(string.length(), pretenure);
4399     if (!maybe_result->ToObject(&result)) return maybe_result;
4400   }
4401
4402   // Copy the characters into the new object.
4403   SeqAsciiString* string_result = SeqAsciiString::cast(result);
4404   for (int i = 0; i < string.length(); i++) {
4405     string_result->SeqAsciiStringSet(i, string[i]);
4406   }
4407   return result;
4408 }
4409
4410
4411 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4412                                               PretenureFlag pretenure) {
4413   // Count the number of characters in the UTF-8 string and check if
4414   // it is an ASCII string.
4415   Access<UnicodeCache::Utf8Decoder>
4416       decoder(isolate_->unicode_cache()->utf8_decoder());
4417   decoder->Reset(string.start(), string.length());
4418   int chars = 0;
4419   while (decoder->has_more()) {
4420     uint32_t r = decoder->GetNext();
4421     if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4422       chars++;
4423     } else {
4424       chars += 2;
4425     }
4426   }
4427
4428   Object* result;
4429   { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4430     if (!maybe_result->ToObject(&result)) return maybe_result;
4431   }
4432
4433   // Convert and copy the characters into the new object.
4434   String* string_result = String::cast(result);
4435   decoder->Reset(string.start(), string.length());
4436   int i = 0;
4437   while (i < chars) {
4438     uint32_t r = decoder->GetNext();
4439     if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4440       string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4441       string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4442     } else {
4443       string_result->Set(i++, r);
4444     }
4445   }
4446   return result;
4447 }
4448
4449
4450 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4451                                              PretenureFlag pretenure) {
4452   // Check if the string is an ASCII string.
4453   MaybeObject* maybe_result;
4454   if (String::IsAscii(string.start(), string.length())) {
4455     maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4456   } else {  // It's not an ASCII string.
4457     maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4458   }
4459   Object* result;
4460   if (!maybe_result->ToObject(&result)) return maybe_result;
4461
4462   // Copy the characters into the new object, which may be either ASCII or
4463   // UTF-16.
4464   String* string_result = String::cast(result);
4465   for (int i = 0; i < string.length(); i++) {
4466     string_result->Set(i, string[i]);
4467   }
4468   return result;
4469 }
4470
4471
4472 Map* Heap::SymbolMapForString(String* string) {
4473   // If the string is in new space it cannot be used as a symbol.
4474   if (InNewSpace(string)) return NULL;
4475
4476   // Find the corresponding symbol map for strings.
4477   switch (string->map()->instance_type()) {
4478     case STRING_TYPE: return symbol_map();
4479     case ASCII_STRING_TYPE: return ascii_symbol_map();
4480     case CONS_STRING_TYPE: return cons_symbol_map();
4481     case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4482     case EXTERNAL_STRING_TYPE: return external_symbol_map();
4483     case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4484     case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4485       return external_symbol_with_ascii_data_map();
4486     case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4487     case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4488       return short_external_ascii_symbol_map();
4489     case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4490       return short_external_symbol_with_ascii_data_map();
4491     default: return NULL;  // No match found.
4492   }
4493 }
4494
4495
4496 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4497                                           int chars,
4498                                           uint32_t hash_field) {
4499   ASSERT(chars >= 0);
4500   // Ensure the chars matches the number of characters in the buffer.
4501   ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4502   // Determine whether the string is ASCII.
4503   bool is_ascii = true;
4504   while (buffer->has_more()) {
4505     if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4506       is_ascii = false;
4507       break;
4508     }
4509   }
4510   buffer->Rewind();
4511
4512   // Compute map and object size.
4513   int size;
4514   Map* map;
4515
4516   if (is_ascii) {
4517     if (chars > SeqAsciiString::kMaxLength) {
4518       return Failure::OutOfMemoryException();
4519     }
4520     map = ascii_symbol_map();
4521     size = SeqAsciiString::SizeFor(chars);
4522   } else {
4523     if (chars > SeqTwoByteString::kMaxLength) {
4524       return Failure::OutOfMemoryException();
4525     }
4526     map = symbol_map();
4527     size = SeqTwoByteString::SizeFor(chars);
4528   }
4529
4530   // Allocate string.
4531   Object* result;
4532   { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4533                    ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4534                    : old_data_space_->AllocateRaw(size);
4535     if (!maybe_result->ToObject(&result)) return maybe_result;
4536   }
4537
4538   reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4539   // Set length and hash fields of the allocated string.
4540   String* answer = String::cast(result);
4541   answer->set_length(chars);
4542   answer->set_hash_field(hash_field);
4543
4544   ASSERT_EQ(size, answer->Size());
4545
4546   // Fill in the characters.
4547   int i = 0;
4548   while (i < chars) {
4549     uint32_t character = buffer->GetNext();
4550     if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4551       answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4552       answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4553     } else {
4554       answer->Set(i++, character);
4555     }
4556   }
4557   return answer;
4558 }
4559
4560
4561 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4562   if (length < 0 || length > SeqAsciiString::kMaxLength) {
4563     return Failure::OutOfMemoryException();
4564   }
4565
4566   int size = SeqAsciiString::SizeFor(length);
4567   ASSERT(size <= SeqAsciiString::kMaxSize);
4568
4569   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4570   AllocationSpace retry_space = OLD_DATA_SPACE;
4571
4572   if (space == NEW_SPACE) {
4573     if (size > kMaxObjectSizeInNewSpace) {
4574       // Allocate in large object space, retry space will be ignored.
4575       space = LO_SPACE;
4576     } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4577       // Allocate in new space, retry in large object space.
4578       retry_space = LO_SPACE;
4579     }
4580   } else if (space == OLD_DATA_SPACE &&
4581              size > Page::kMaxNonCodeHeapObjectSize) {
4582     space = LO_SPACE;
4583   }
4584   Object* result;
4585   { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4586     if (!maybe_result->ToObject(&result)) return maybe_result;
4587   }
4588
4589   // Partially initialize the object.
4590   HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4591   String::cast(result)->set_length(length);
4592   String::cast(result)->set_hash_field(String::kEmptyHashField);
4593   ASSERT_EQ(size, HeapObject::cast(result)->Size());
4594
4595 #ifdef DEBUG
4596   if (FLAG_verify_heap) {
4597     // Initialize string's content to ensure ASCII-ness (character range 0-127)
4598     // as required when verifying the heap.
4599     char* dest = SeqAsciiString::cast(result)->GetChars();
4600     memset(dest, 0x0F, length * kCharSize);
4601   }
4602 #endif  // DEBUG
4603
4604   return result;
4605 }
4606
4607
4608 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4609                                             PretenureFlag pretenure) {
4610   if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4611     return Failure::OutOfMemoryException();
4612   }
4613   int size = SeqTwoByteString::SizeFor(length);
4614   ASSERT(size <= SeqTwoByteString::kMaxSize);
4615   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4616   AllocationSpace retry_space = OLD_DATA_SPACE;
4617
4618   if (space == NEW_SPACE) {
4619     if (size > kMaxObjectSizeInNewSpace) {
4620       // Allocate in large object space, retry space will be ignored.
4621       space = LO_SPACE;
4622     } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4623       // Allocate in new space, retry in large object space.
4624       retry_space = LO_SPACE;
4625     }
4626   } else if (space == OLD_DATA_SPACE &&
4627              size > Page::kMaxNonCodeHeapObjectSize) {
4628     space = LO_SPACE;
4629   }
4630   Object* result;
4631   { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4632     if (!maybe_result->ToObject(&result)) return maybe_result;
4633   }
4634
4635   // Partially initialize the object.
4636   HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4637   String::cast(result)->set_length(length);
4638   String::cast(result)->set_hash_field(String::kEmptyHashField);
4639   ASSERT_EQ(size, HeapObject::cast(result)->Size());
4640   return result;
4641 }
4642
4643
4644 MaybeObject* Heap::AllocateJSArray(
4645     ElementsKind elements_kind,
4646     PretenureFlag pretenure) {
4647   Context* native_context = isolate()->context()->native_context();
4648   JSFunction* array_function = native_context->array_function();
4649   Map* map = array_function->initial_map();
4650   Object* maybe_map_array = native_context->js_array_maps();
4651   if (!maybe_map_array->IsUndefined()) {
4652     Object* maybe_transitioned_map =
4653         FixedArray::cast(maybe_map_array)->get(elements_kind);
4654     if (!maybe_transitioned_map->IsUndefined()) {
4655       map = Map::cast(maybe_transitioned_map);
4656     }
4657   }
4658
4659   return AllocateJSObjectFromMap(map, pretenure);
4660 }
4661
4662
4663 MaybeObject* Heap::AllocateEmptyFixedArray() {
4664   int size = FixedArray::SizeFor(0);
4665   Object* result;
4666   { MaybeObject* maybe_result =
4667         AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4668     if (!maybe_result->ToObject(&result)) return maybe_result;
4669   }
4670   // Initialize the object.
4671   reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4672       fixed_array_map());
4673   reinterpret_cast<FixedArray*>(result)->set_length(0);
4674   return result;
4675 }
4676
4677
4678 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4679   if (length < 0 || length > FixedArray::kMaxLength) {
4680     return Failure::OutOfMemoryException();
4681   }
4682   ASSERT(length > 0);
4683   // Use the general function if we're forced to always allocate.
4684   if (always_allocate()) return AllocateFixedArray(length, TENURED);
4685   // Allocate the raw data for a fixed array.
4686   int size = FixedArray::SizeFor(length);
4687   return size <= kMaxObjectSizeInNewSpace
4688       ? new_space_.AllocateRaw(size)
4689       : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4690 }
4691
4692
4693 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4694   int len = src->length();
4695   Object* obj;
4696   { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4697     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4698   }
4699   if (InNewSpace(obj)) {
4700     HeapObject* dst = HeapObject::cast(obj);
4701     dst->set_map_no_write_barrier(map);
4702     CopyBlock(dst->address() + kPointerSize,
4703               src->address() + kPointerSize,
4704               FixedArray::SizeFor(len) - kPointerSize);
4705     return obj;
4706   }
4707   HeapObject::cast(obj)->set_map_no_write_barrier(map);
4708   FixedArray* result = FixedArray::cast(obj);
4709   result->set_length(len);
4710
4711   // Copy the content
4712   AssertNoAllocation no_gc;
4713   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4714   for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4715   return result;
4716 }
4717
4718
4719 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4720                                                Map* map) {
4721   int len = src->length();
4722   Object* obj;
4723   { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4724     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4725   }
4726   HeapObject* dst = HeapObject::cast(obj);
4727   dst->set_map_no_write_barrier(map);
4728   CopyBlock(
4729       dst->address() + FixedDoubleArray::kLengthOffset,
4730       src->address() + FixedDoubleArray::kLengthOffset,
4731       FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4732   return obj;
4733 }
4734
4735
4736 MaybeObject* Heap::AllocateFixedArray(int length) {
4737   ASSERT(length >= 0);
4738   if (length == 0) return empty_fixed_array();
4739   Object* result;
4740   { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4741     if (!maybe_result->ToObject(&result)) return maybe_result;
4742   }
4743   // Initialize header.
4744   FixedArray* array = reinterpret_cast<FixedArray*>(result);
4745   array->set_map_no_write_barrier(fixed_array_map());
4746   array->set_length(length);
4747   // Initialize body.
4748   ASSERT(!InNewSpace(undefined_value()));
4749   MemsetPointer(array->data_start(), undefined_value(), length);
4750   return result;
4751 }
4752
4753
4754 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4755   if (length < 0 || length > FixedArray::kMaxLength) {
4756     return Failure::OutOfMemoryException();
4757   }
4758
4759   AllocationSpace space =
4760       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4761   int size = FixedArray::SizeFor(length);
4762   if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4763     // Too big for new space.
4764     space = LO_SPACE;
4765   } else if (space == OLD_POINTER_SPACE &&
4766              size > Page::kMaxNonCodeHeapObjectSize) {
4767     // Too big for old pointer space.
4768     space = LO_SPACE;
4769   }
4770
4771   AllocationSpace retry_space =
4772       (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4773
4774   return AllocateRaw(size, space, retry_space);
4775 }
4776
4777
4778 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4779     Heap* heap,
4780     int length,
4781     PretenureFlag pretenure,
4782     Object* filler) {
4783   ASSERT(length >= 0);
4784   ASSERT(heap->empty_fixed_array()->IsFixedArray());
4785   if (length == 0) return heap->empty_fixed_array();
4786
4787   ASSERT(!heap->InNewSpace(filler));
4788   Object* result;
4789   { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4790     if (!maybe_result->ToObject(&result)) return maybe_result;
4791   }
4792
4793   HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4794   FixedArray* array = FixedArray::cast(result);
4795   array->set_length(length);
4796   MemsetPointer(array->data_start(), filler, length);
4797   return array;
4798 }
4799
4800
4801 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4802   return AllocateFixedArrayWithFiller(this,
4803                                       length,
4804                                       pretenure,
4805                                       undefined_value());
4806 }
4807
4808
4809 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4810                                                PretenureFlag pretenure) {
4811   return AllocateFixedArrayWithFiller(this,
4812                                       length,
4813                                       pretenure,
4814                                       the_hole_value());
4815 }
4816
4817
4818 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4819   if (length == 0) return empty_fixed_array();
4820
4821   Object* obj;
4822   { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4823     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4824   }
4825
4826   reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4827       fixed_array_map());
4828   FixedArray::cast(obj)->set_length(length);
4829   return obj;
4830 }
4831
4832
4833 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4834   int size = FixedDoubleArray::SizeFor(0);
4835   Object* result;
4836   { MaybeObject* maybe_result =
4837         AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4838     if (!maybe_result->ToObject(&result)) return maybe_result;
4839   }
4840   // Initialize the object.
4841   reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4842       fixed_double_array_map());
4843   reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4844   return result;
4845 }
4846
4847
4848 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4849     int length,
4850     PretenureFlag pretenure) {
4851   if (length == 0) return empty_fixed_array();
4852
4853   Object* elements_object;
4854   MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4855   if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4856   FixedDoubleArray* elements =
4857       reinterpret_cast<FixedDoubleArray*>(elements_object);
4858
4859   elements->set_map_no_write_barrier(fixed_double_array_map());
4860   elements->set_length(length);
4861   return elements;
4862 }
4863
4864
4865 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4866     int length,
4867     PretenureFlag pretenure) {
4868   if (length == 0) return empty_fixed_array();
4869
4870   Object* elements_object;
4871   MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4872   if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4873   FixedDoubleArray* elements =
4874       reinterpret_cast<FixedDoubleArray*>(elements_object);
4875
4876   for (int i = 0; i < length; ++i) {
4877     elements->set_the_hole(i);
4878   }
4879
4880   elements->set_map_no_write_barrier(fixed_double_array_map());
4881   elements->set_length(length);
4882   return elements;
4883 }
4884
4885
4886 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4887                                                PretenureFlag pretenure) {
4888   if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4889     return Failure::OutOfMemoryException();
4890   }
4891
4892   AllocationSpace space =
4893       (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4894   int size = FixedDoubleArray::SizeFor(length);
4895
4896 #ifndef V8_HOST_ARCH_64_BIT
4897   size += kPointerSize;
4898 #endif
4899
4900   if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4901     // Too big for new space.
4902     space = LO_SPACE;
4903   } else if (space == OLD_DATA_SPACE &&
4904              size > Page::kMaxNonCodeHeapObjectSize) {
4905     // Too big for old data space.
4906     space = LO_SPACE;
4907   }
4908
4909   AllocationSpace retry_space =
4910       (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4911
4912   HeapObject* object;
4913   { MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
4914     if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
4915   }
4916
4917   return EnsureDoubleAligned(this, object, size);
4918 }
4919
4920
4921 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4922   Object* result;
4923   { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4924     if (!maybe_result->ToObject(&result)) return maybe_result;
4925   }
4926   reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4927       hash_table_map());
4928   ASSERT(result->IsHashTable());
4929   return result;
4930 }
4931
4932
4933 MaybeObject* Heap::AllocateNativeContext() {
4934   Object* result;
4935   { MaybeObject* maybe_result =
4936         AllocateFixedArray(Context::NATIVE_CONTEXT_SLOTS);
4937     if (!maybe_result->ToObject(&result)) return maybe_result;
4938   }
4939   Context* context = reinterpret_cast<Context*>(result);
4940   context->set_map_no_write_barrier(native_context_map());
4941   context->set_js_array_maps(undefined_value());
4942   ASSERT(context->IsNativeContext());
4943   ASSERT(result->IsContext());
4944   return result;
4945 }
4946
4947
4948 MaybeObject* Heap::AllocateGlobalContext(JSFunction* function,
4949                                          ScopeInfo* scope_info) {
4950   Object* result;
4951   { MaybeObject* maybe_result =
4952         AllocateFixedArray(scope_info->ContextLength(), TENURED);
4953     if (!maybe_result->ToObject(&result)) return maybe_result;
4954   }
4955   Context* context = reinterpret_cast<Context*>(result);
4956   context->set_map_no_write_barrier(global_context_map());
4957   context->set_closure(function);
4958   context->set_previous(function->context());
4959   context->set_extension(scope_info);
4960   context->set_global_object(function->context()->global_object());
4961   ASSERT(context->IsGlobalContext());
4962   ASSERT(result->IsContext());
4963   return context;
4964 }
4965
4966
4967 MaybeObject* Heap::AllocateModuleContext(ScopeInfo* scope_info) {
4968   Object* result;
4969   { MaybeObject* maybe_result =
4970         AllocateFixedArray(scope_info->ContextLength(), TENURED);
4971     if (!maybe_result->ToObject(&result)) return maybe_result;
4972   }
4973   Context* context = reinterpret_cast<Context*>(result);
4974   context->set_map_no_write_barrier(module_context_map());
4975   // Context links will be set later.
4976   context->set_extension(Smi::FromInt(0));
4977   return context;
4978 }
4979
4980
4981 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4982   ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4983   Object* result;
4984   { MaybeObject* maybe_result = AllocateFixedArray(length);
4985     if (!maybe_result->ToObject(&result)) return maybe_result;
4986   }
4987   Context* context = reinterpret_cast<Context*>(result);
4988   context->set_map_no_write_barrier(function_context_map());
4989   context->set_closure(function);
4990   context->set_previous(function->context());
4991   context->set_extension(Smi::FromInt(0));
4992   context->set_global_object(function->context()->global_object());
4993   return context;
4994 }
4995
4996
4997 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4998                                         Context* previous,
4999                                         String* name,
5000                                         Object* thrown_object) {
5001   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
5002   Object* result;
5003   { MaybeObject* maybe_result =
5004         AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
5005     if (!maybe_result->ToObject(&result)) return maybe_result;
5006   }
5007   Context* context = reinterpret_cast<Context*>(result);
5008   context->set_map_no_write_barrier(catch_context_map());
5009   context->set_closure(function);
5010   context->set_previous(previous);
5011   context->set_extension(name);
5012   context->set_global_object(previous->global_object());
5013   context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
5014   return context;
5015 }
5016
5017
5018 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
5019                                        Context* previous,
5020                                        JSObject* extension) {
5021   Object* result;
5022   { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
5023     if (!maybe_result->ToObject(&result)) return maybe_result;
5024   }
5025   Context* context = reinterpret_cast<Context*>(result);
5026   context->set_map_no_write_barrier(with_context_map());
5027   context->set_closure(function);
5028   context->set_previous(previous);
5029   context->set_extension(extension);
5030   context->set_global_object(previous->global_object());
5031   return context;
5032 }
5033
5034
5035 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
5036                                         Context* previous,
5037                                         ScopeInfo* scope_info) {
5038   Object* result;
5039   { MaybeObject* maybe_result =
5040         AllocateFixedArrayWithHoles(scope_info->ContextLength());
5041     if (!maybe_result->ToObject(&result)) return maybe_result;
5042   }
5043   Context* context = reinterpret_cast<Context*>(result);
5044   context->set_map_no_write_barrier(block_context_map());
5045   context->set_closure(function);
5046   context->set_previous(previous);
5047   context->set_extension(scope_info);
5048   context->set_global_object(previous->global_object());
5049   return context;
5050 }
5051
5052
5053 MaybeObject* Heap::AllocateScopeInfo(int length) {
5054   FixedArray* scope_info;
5055   MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
5056   if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
5057   scope_info->set_map_no_write_barrier(scope_info_map());
5058   return scope_info;
5059 }
5060
5061
5062 MaybeObject* Heap::AllocateStruct(InstanceType type) {
5063   Map* map;
5064   switch (type) {
5065 #define MAKE_CASE(NAME, Name, name) \
5066     case NAME##_TYPE: map = name##_map(); break;
5067 STRUCT_LIST(MAKE_CASE)
5068 #undef MAKE_CASE
5069     default:
5070       UNREACHABLE();
5071       return Failure::InternalError();
5072   }
5073   int size = map->instance_size();
5074   AllocationSpace space =
5075       (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
5076   Object* result;
5077   { MaybeObject* maybe_result = Allocate(map, space);
5078     if (!maybe_result->ToObject(&result)) return maybe_result;
5079   }
5080   Struct::cast(result)->InitializeBody(size);
5081   return result;
5082 }
5083
5084
5085 bool Heap::IsHeapIterable() {
5086   return (!old_pointer_space()->was_swept_conservatively() &&
5087           !old_data_space()->was_swept_conservatively());
5088 }
5089
5090
5091 void Heap::EnsureHeapIsIterable() {
5092   ASSERT(IsAllocationAllowed());
5093   if (!IsHeapIterable()) {
5094     CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
5095   }
5096   ASSERT(IsHeapIterable());
5097 }
5098
5099
5100 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
5101   incremental_marking()->Step(step_size,
5102                               IncrementalMarking::NO_GC_VIA_STACK_GUARD);
5103
5104   if (incremental_marking()->IsComplete()) {
5105     bool uncommit = false;
5106     if (gc_count_at_last_idle_gc_ == gc_count_) {
5107       // No GC since the last full GC, the mutator is probably not active.
5108       isolate_->compilation_cache()->Clear();
5109       uncommit = true;
5110     }
5111     CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
5112     gc_count_at_last_idle_gc_ = gc_count_;
5113     if (uncommit) {
5114       new_space_.Shrink();
5115       UncommitFromSpace();
5116     }
5117   }
5118 }
5119
5120
5121 bool Heap::IdleNotification(int hint) {
5122   // Hints greater than this value indicate that
5123   // the embedder is requesting a lot of GC work.
5124   const int kMaxHint = 1000;
5125   // Minimal hint that allows to do full GC.
5126   const int kMinHintForFullGC = 100;
5127   intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
5128   // The size factor is in range [5..250]. The numbers here are chosen from
5129   // experiments. If you changes them, make sure to test with
5130   // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
5131   intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
5132
5133   if (contexts_disposed_ > 0) {
5134     if (hint >= kMaxHint) {
5135       // The embedder is requesting a lot of GC work after context disposal,
5136       // we age inline caches so that they don't keep objects from
5137       // the old context alive.
5138       AgeInlineCaches();
5139     }
5140     int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
5141     if (hint >= mark_sweep_time && !FLAG_expose_gc &&
5142         incremental_marking()->IsStopped()) {
5143       HistogramTimerScope scope(isolate_->counters()->gc_context());
5144       CollectAllGarbage(kReduceMemoryFootprintMask,
5145                         "idle notification: contexts disposed");
5146     } else {
5147       AdvanceIdleIncrementalMarking(step_size);
5148       contexts_disposed_ = 0;
5149     }
5150     // Make sure that we have no pending context disposals.
5151     // Take into account that we might have decided to delay full collection
5152     // because incremental marking is in progress.
5153     ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
5154     // After context disposal there is likely a lot of garbage remaining, reset
5155     // the idle notification counters in order to trigger more incremental GCs
5156     // on subsequent idle notifications.
5157     StartIdleRound();
5158     return false;
5159   }
5160
5161   if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
5162     return IdleGlobalGC();
5163   }
5164
5165   // By doing small chunks of GC work in each IdleNotification,
5166   // perform a round of incremental GCs and after that wait until
5167   // the mutator creates enough garbage to justify a new round.
5168   // An incremental GC progresses as follows:
5169   // 1. many incremental marking steps,
5170   // 2. one old space mark-sweep-compact,
5171   // 3. many lazy sweep steps.
5172   // Use mark-sweep-compact events to count incremental GCs in a round.
5173
5174
5175   if (incremental_marking()->IsStopped()) {
5176     if (!IsSweepingComplete() &&
5177         !AdvanceSweepers(static_cast<int>(step_size))) {
5178       return false;
5179     }
5180   }
5181
5182   if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5183     if (EnoughGarbageSinceLastIdleRound()) {
5184       StartIdleRound();
5185     } else {
5186       return true;
5187     }
5188   }
5189
5190   int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
5191   mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
5192   ms_count_at_last_idle_notification_ = ms_count_;
5193
5194   int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound -
5195                               mark_sweeps_since_idle_round_started_;
5196
5197   if (remaining_mark_sweeps <= 0) {
5198     FinishIdleRound();
5199     return true;
5200   }
5201
5202   if (incremental_marking()->IsStopped()) {
5203     // If there are no more than two GCs left in this idle round and we are
5204     // allowed to do a full GC, then make those GCs full in order to compact
5205     // the code space.
5206     // TODO(ulan): Once we enable code compaction for incremental marking,
5207     // we can get rid of this special case and always start incremental marking.
5208     if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) {
5209       CollectAllGarbage(kReduceMemoryFootprintMask,
5210                         "idle notification: finalize idle round");
5211     } else {
5212       incremental_marking()->Start();
5213     }
5214   }
5215   if (!incremental_marking()->IsStopped()) {
5216     AdvanceIdleIncrementalMarking(step_size);
5217   }
5218   return false;
5219 }
5220
5221
5222 bool Heap::IdleGlobalGC() {
5223   static const int kIdlesBeforeScavenge = 4;
5224   static const int kIdlesBeforeMarkSweep = 7;
5225   static const int kIdlesBeforeMarkCompact = 8;
5226   static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
5227   static const unsigned int kGCsBetweenCleanup = 4;
5228
5229   if (!last_idle_notification_gc_count_init_) {
5230     last_idle_notification_gc_count_ = gc_count_;
5231     last_idle_notification_gc_count_init_ = true;
5232   }
5233
5234   bool uncommit = true;
5235   bool finished = false;
5236
5237   // Reset the number of idle notifications received when a number of
5238   // GCs have taken place. This allows another round of cleanup based
5239   // on idle notifications if enough work has been carried out to
5240   // provoke a number of garbage collections.
5241   if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
5242     number_idle_notifications_ =
5243         Min(number_idle_notifications_ + 1, kMaxIdleCount);
5244   } else {
5245     number_idle_notifications_ = 0;
5246     last_idle_notification_gc_count_ = gc_count_;
5247   }
5248
5249   if (number_idle_notifications_ == kIdlesBeforeScavenge) {
5250     CollectGarbage(NEW_SPACE, "idle notification");
5251     new_space_.Shrink();
5252     last_idle_notification_gc_count_ = gc_count_;
5253   } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
5254     // Before doing the mark-sweep collections we clear the
5255     // compilation cache to avoid hanging on to source code and
5256     // generated code for cached functions.
5257     isolate_->compilation_cache()->Clear();
5258
5259     CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5260     new_space_.Shrink();
5261     last_idle_notification_gc_count_ = gc_count_;
5262
5263   } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
5264     CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5265     new_space_.Shrink();
5266     last_idle_notification_gc_count_ = gc_count_;
5267     number_idle_notifications_ = 0;
5268     finished = true;
5269   } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
5270     // If we have received more than kIdlesBeforeMarkCompact idle
5271     // notifications we do not perform any cleanup because we don't
5272     // expect to gain much by doing so.
5273     finished = true;
5274   }
5275
5276   if (uncommit) UncommitFromSpace();
5277
5278   return finished;
5279 }
5280
5281
5282 #ifdef DEBUG
5283
5284 void Heap::Print() {
5285   if (!HasBeenSetUp()) return;
5286   isolate()->PrintStack();
5287   AllSpaces spaces;
5288   for (Space* space = spaces.next(); space != NULL; space = spaces.next())
5289     space->Print();
5290 }
5291
5292
5293 void Heap::ReportCodeStatistics(const char* title) {
5294   PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5295   PagedSpace::ResetCodeStatistics();
5296   // We do not look for code in new space, map space, or old space.  If code
5297   // somehow ends up in those spaces, we would miss it here.
5298   code_space_->CollectCodeStatistics();
5299   lo_space_->CollectCodeStatistics();
5300   PagedSpace::ReportCodeStatistics();
5301 }
5302
5303
5304 // This function expects that NewSpace's allocated objects histogram is
5305 // populated (via a call to CollectStatistics or else as a side effect of a
5306 // just-completed scavenge collection).
5307 void Heap::ReportHeapStatistics(const char* title) {
5308   USE(title);
5309   PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5310          title, gc_count_);
5311   PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5312          old_gen_promotion_limit_);
5313   PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5314          old_gen_allocation_limit_);
5315   PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5316
5317   PrintF("\n");
5318   PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5319   isolate_->global_handles()->PrintStats();
5320   PrintF("\n");
5321
5322   PrintF("Heap statistics : ");
5323   isolate_->memory_allocator()->ReportStatistics();
5324   PrintF("To space : ");
5325   new_space_.ReportStatistics();
5326   PrintF("Old pointer space : ");
5327   old_pointer_space_->ReportStatistics();
5328   PrintF("Old data space : ");
5329   old_data_space_->ReportStatistics();
5330   PrintF("Code space : ");
5331   code_space_->ReportStatistics();
5332   PrintF("Map space : ");
5333   map_space_->ReportStatistics();
5334   PrintF("Cell space : ");
5335   cell_space_->ReportStatistics();
5336   PrintF("Large object space : ");
5337   lo_space_->ReportStatistics();
5338   PrintF(">>>>>> ========================================= >>>>>>\n");
5339 }
5340
5341 #endif  // DEBUG
5342
5343 bool Heap::Contains(HeapObject* value) {
5344   return Contains(value->address());
5345 }
5346
5347
5348 bool Heap::Contains(Address addr) {
5349   if (OS::IsOutsideAllocatedSpace(addr)) return false;
5350   return HasBeenSetUp() &&
5351     (new_space_.ToSpaceContains(addr) ||
5352      old_pointer_space_->Contains(addr) ||
5353      old_data_space_->Contains(addr) ||
5354      code_space_->Contains(addr) ||
5355      map_space_->Contains(addr) ||
5356      cell_space_->Contains(addr) ||
5357      lo_space_->SlowContains(addr));
5358 }
5359
5360
5361 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5362   return InSpace(value->address(), space);
5363 }
5364
5365
5366 bool Heap::InSpace(Address addr, AllocationSpace space) {
5367   if (OS::IsOutsideAllocatedSpace(addr)) return false;
5368   if (!HasBeenSetUp()) return false;
5369
5370   switch (space) {
5371     case NEW_SPACE:
5372       return new_space_.ToSpaceContains(addr);
5373     case OLD_POINTER_SPACE:
5374       return old_pointer_space_->Contains(addr);
5375     case OLD_DATA_SPACE:
5376       return old_data_space_->Contains(addr);
5377     case CODE_SPACE:
5378       return code_space_->Contains(addr);
5379     case MAP_SPACE:
5380       return map_space_->Contains(addr);
5381     case CELL_SPACE:
5382       return cell_space_->Contains(addr);
5383     case LO_SPACE:
5384       return lo_space_->SlowContains(addr);
5385   }
5386
5387   return false;
5388 }
5389
5390
5391 #ifdef DEBUG
5392 void Heap::Verify() {
5393   ASSERT(HasBeenSetUp());
5394
5395   store_buffer()->Verify();
5396
5397   VerifyPointersVisitor visitor;
5398   IterateRoots(&visitor, VISIT_ONLY_STRONG);
5399
5400   new_space_.Verify();
5401
5402   old_pointer_space_->Verify(&visitor);
5403   map_space_->Verify(&visitor);
5404
5405   VerifyPointersVisitor no_dirty_regions_visitor;
5406   old_data_space_->Verify(&no_dirty_regions_visitor);
5407   code_space_->Verify(&no_dirty_regions_visitor);
5408   cell_space_->Verify(&no_dirty_regions_visitor);
5409
5410   lo_space_->Verify();
5411 }
5412
5413
5414 #endif  // DEBUG
5415
5416
5417 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5418   Object* symbol = NULL;
5419   Object* new_table;
5420   { MaybeObject* maybe_new_table =
5421         symbol_table()->LookupSymbol(string, &symbol);
5422     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5423   }
5424   // Can't use set_symbol_table because SymbolTable::cast knows that
5425   // SymbolTable is a singleton and checks for identity.
5426   roots_[kSymbolTableRootIndex] = new_table;
5427   ASSERT(symbol != NULL);
5428   return symbol;
5429 }
5430
5431
5432 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5433   Object* symbol = NULL;
5434   Object* new_table;
5435   { MaybeObject* maybe_new_table =
5436         symbol_table()->LookupAsciiSymbol(string, &symbol);
5437     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5438   }
5439   // Can't use set_symbol_table because SymbolTable::cast knows that
5440   // SymbolTable is a singleton and checks for identity.
5441   roots_[kSymbolTableRootIndex] = new_table;
5442   ASSERT(symbol != NULL);
5443   return symbol;
5444 }
5445
5446
5447 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5448                                      int from,
5449                                      int length) {
5450   Object* symbol = NULL;
5451   Object* new_table;
5452   { MaybeObject* maybe_new_table =
5453         symbol_table()->LookupSubStringAsciiSymbol(string,
5454                                                    from,
5455                                                    length,
5456                                                    &symbol);
5457     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5458   }
5459   // Can't use set_symbol_table because SymbolTable::cast knows that
5460   // SymbolTable is a singleton and checks for identity.
5461   roots_[kSymbolTableRootIndex] = new_table;
5462   ASSERT(symbol != NULL);
5463   return symbol;
5464 }
5465
5466
5467 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5468   Object* symbol = NULL;
5469   Object* new_table;
5470   { MaybeObject* maybe_new_table =
5471         symbol_table()->LookupTwoByteSymbol(string, &symbol);
5472     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5473   }
5474   // Can't use set_symbol_table because SymbolTable::cast knows that
5475   // SymbolTable is a singleton and checks for identity.
5476   roots_[kSymbolTableRootIndex] = new_table;
5477   ASSERT(symbol != NULL);
5478   return symbol;
5479 }
5480
5481
5482 MaybeObject* Heap::LookupSymbol(String* string) {
5483   if (string->IsSymbol()) return string;
5484   Object* symbol = NULL;
5485   Object* new_table;
5486   { MaybeObject* maybe_new_table =
5487         symbol_table()->LookupString(string, &symbol);
5488     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5489   }
5490   // Can't use set_symbol_table because SymbolTable::cast knows that
5491   // SymbolTable is a singleton and checks for identity.
5492   roots_[kSymbolTableRootIndex] = new_table;
5493   ASSERT(symbol != NULL);
5494   return symbol;
5495 }
5496
5497
5498 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5499   if (string->IsSymbol()) {
5500     *symbol = string;
5501     return true;
5502   }
5503   return symbol_table()->LookupSymbolIfExists(string, symbol);
5504 }
5505
5506
5507 #ifdef DEBUG
5508 void Heap::ZapFromSpace() {
5509   NewSpacePageIterator it(new_space_.FromSpaceStart(),
5510                           new_space_.FromSpaceEnd());
5511   while (it.has_next()) {
5512     NewSpacePage* page = it.next();
5513     for (Address cursor = page->area_start(), limit = page->area_end();
5514          cursor < limit;
5515          cursor += kPointerSize) {
5516       Memory::Address_at(cursor) = kFromSpaceZapValue;
5517     }
5518   }
5519 }
5520 #endif  // DEBUG
5521
5522
5523 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5524                                              Address end,
5525                                              ObjectSlotCallback callback) {
5526   Address slot_address = start;
5527
5528   // We are not collecting slots on new space objects during mutation
5529   // thus we have to scan for pointers to evacuation candidates when we
5530   // promote objects. But we should not record any slots in non-black
5531   // objects. Grey object's slots would be rescanned.
5532   // White object might not survive until the end of collection
5533   // it would be a violation of the invariant to record it's slots.
5534   bool record_slots = false;
5535   if (incremental_marking()->IsCompacting()) {
5536     MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5537     record_slots = Marking::IsBlack(mark_bit);
5538   }
5539
5540   while (slot_address < end) {
5541     Object** slot = reinterpret_cast<Object**>(slot_address);
5542     Object* object = *slot;
5543     // If the store buffer becomes overfull we mark pages as being exempt from
5544     // the store buffer.  These pages are scanned to find pointers that point
5545     // to the new space.  In that case we may hit newly promoted objects and
5546     // fix the pointers before the promotion queue gets to them.  Thus the 'if'.
5547     if (object->IsHeapObject()) {
5548       if (Heap::InFromSpace(object)) {
5549         callback(reinterpret_cast<HeapObject**>(slot),
5550                  HeapObject::cast(object));
5551         Object* new_object = *slot;
5552         if (InNewSpace(new_object)) {
5553           SLOW_ASSERT(Heap::InToSpace(new_object));
5554           SLOW_ASSERT(new_object->IsHeapObject());
5555           store_buffer_.EnterDirectlyIntoStoreBuffer(
5556               reinterpret_cast<Address>(slot));
5557         }
5558         SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5559       } else if (record_slots &&
5560                  MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5561         mark_compact_collector()->RecordSlot(slot, slot, object);
5562       }
5563     }
5564     slot_address += kPointerSize;
5565   }
5566 }
5567
5568
5569 #ifdef DEBUG
5570 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5571
5572
5573 bool IsAMapPointerAddress(Object** addr) {
5574   uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5575   int mod = a % Map::kSize;
5576   return mod >= Map::kPointerFieldsBeginOffset &&
5577          mod < Map::kPointerFieldsEndOffset;
5578 }
5579
5580
5581 bool EverythingsAPointer(Object** addr) {
5582   return true;
5583 }
5584
5585
5586 static void CheckStoreBuffer(Heap* heap,
5587                              Object** current,
5588                              Object** limit,
5589                              Object**** store_buffer_position,
5590                              Object*** store_buffer_top,
5591                              CheckStoreBufferFilter filter,
5592                              Address special_garbage_start,
5593                              Address special_garbage_end) {
5594   Map* free_space_map = heap->free_space_map();
5595   for ( ; current < limit; current++) {
5596     Object* o = *current;
5597     Address current_address = reinterpret_cast<Address>(current);
5598     // Skip free space.
5599     if (o == free_space_map) {
5600       Address current_address = reinterpret_cast<Address>(current);
5601       FreeSpace* free_space =
5602           FreeSpace::cast(HeapObject::FromAddress(current_address));
5603       int skip = free_space->Size();
5604       ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5605       ASSERT(skip > 0);
5606       current_address += skip - kPointerSize;
5607       current = reinterpret_cast<Object**>(current_address);
5608       continue;
5609     }
5610     // Skip the current linear allocation space between top and limit which is
5611     // unmarked with the free space map, but can contain junk.
5612     if (current_address == special_garbage_start &&
5613         special_garbage_end != special_garbage_start) {
5614       current_address = special_garbage_end - kPointerSize;
5615       current = reinterpret_cast<Object**>(current_address);
5616       continue;
5617     }
5618     if (!(*filter)(current)) continue;
5619     ASSERT(current_address < special_garbage_start ||
5620            current_address >= special_garbage_end);
5621     ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5622     // We have to check that the pointer does not point into new space
5623     // without trying to cast it to a heap object since the hash field of
5624     // a string can contain values like 1 and 3 which are tagged null
5625     // pointers.
5626     if (!heap->InNewSpace(o)) continue;
5627     while (**store_buffer_position < current &&
5628            *store_buffer_position < store_buffer_top) {
5629       (*store_buffer_position)++;
5630     }
5631     if (**store_buffer_position != current ||
5632         *store_buffer_position == store_buffer_top) {
5633       Object** obj_start = current;
5634       while (!(*obj_start)->IsMap()) obj_start--;
5635       UNREACHABLE();
5636     }
5637   }
5638 }
5639
5640
5641 // Check that the store buffer contains all intergenerational pointers by
5642 // scanning a page and ensuring that all pointers to young space are in the
5643 // store buffer.
5644 void Heap::OldPointerSpaceCheckStoreBuffer() {
5645   OldSpace* space = old_pointer_space();
5646   PageIterator pages(space);
5647
5648   store_buffer()->SortUniq();
5649
5650   while (pages.has_next()) {
5651     Page* page = pages.next();
5652     Object** current = reinterpret_cast<Object**>(page->area_start());
5653
5654     Address end = page->area_end();
5655
5656     Object*** store_buffer_position = store_buffer()->Start();
5657     Object*** store_buffer_top = store_buffer()->Top();
5658
5659     Object** limit = reinterpret_cast<Object**>(end);
5660     CheckStoreBuffer(this,
5661                      current,
5662                      limit,
5663                      &store_buffer_position,
5664                      store_buffer_top,
5665                      &EverythingsAPointer,
5666                      space->top(),
5667                      space->limit());
5668   }
5669 }
5670
5671
5672 void Heap::MapSpaceCheckStoreBuffer() {
5673   MapSpace* space = map_space();
5674   PageIterator pages(space);
5675
5676   store_buffer()->SortUniq();
5677
5678   while (pages.has_next()) {
5679     Page* page = pages.next();
5680     Object** current = reinterpret_cast<Object**>(page->area_start());
5681
5682     Address end = page->area_end();
5683
5684     Object*** store_buffer_position = store_buffer()->Start();
5685     Object*** store_buffer_top = store_buffer()->Top();
5686
5687     Object** limit = reinterpret_cast<Object**>(end);
5688     CheckStoreBuffer(this,
5689                      current,
5690                      limit,
5691                      &store_buffer_position,
5692                      store_buffer_top,
5693                      &IsAMapPointerAddress,
5694                      space->top(),
5695                      space->limit());
5696   }
5697 }
5698
5699
5700 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5701   LargeObjectIterator it(lo_space());
5702   for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5703     // We only have code, sequential strings, or fixed arrays in large
5704     // object space, and only fixed arrays can possibly contain pointers to
5705     // the young generation.
5706     if (object->IsFixedArray()) {
5707       Object*** store_buffer_position = store_buffer()->Start();
5708       Object*** store_buffer_top = store_buffer()->Top();
5709       Object** current = reinterpret_cast<Object**>(object->address());
5710       Object** limit =
5711           reinterpret_cast<Object**>(object->address() + object->Size());
5712       CheckStoreBuffer(this,
5713                        current,
5714                        limit,
5715                        &store_buffer_position,
5716                        store_buffer_top,
5717                        &EverythingsAPointer,
5718                        NULL,
5719                        NULL);
5720     }
5721   }
5722 }
5723 #endif
5724
5725
5726 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5727   IterateStrongRoots(v, mode);
5728   IterateWeakRoots(v, mode);
5729 }
5730
5731
5732 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5733   v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5734   v->Synchronize(VisitorSynchronization::kSymbolTable);
5735   if (mode != VISIT_ALL_IN_SCAVENGE &&
5736       mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5737     // Scavenge collections have special processing for this.
5738     external_string_table_.Iterate(v);
5739   }
5740   v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5741 }
5742
5743
5744 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5745   v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5746   v->Synchronize(VisitorSynchronization::kStrongRootList);
5747
5748   v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5749   v->Synchronize(VisitorSynchronization::kSymbol);
5750
5751   isolate_->bootstrapper()->Iterate(v);
5752   v->Synchronize(VisitorSynchronization::kBootstrapper);
5753   isolate_->Iterate(v);
5754   v->Synchronize(VisitorSynchronization::kTop);
5755   Relocatable::Iterate(v);
5756   v->Synchronize(VisitorSynchronization::kRelocatable);
5757
5758 #ifdef ENABLE_DEBUGGER_SUPPORT
5759   isolate_->debug()->Iterate(v);
5760   if (isolate_->deoptimizer_data() != NULL) {
5761     isolate_->deoptimizer_data()->Iterate(v);
5762   }
5763 #endif
5764   v->Synchronize(VisitorSynchronization::kDebug);
5765   isolate_->compilation_cache()->Iterate(v);
5766   v->Synchronize(VisitorSynchronization::kCompilationCache);
5767
5768   // Iterate over local handles in handle scopes.
5769   isolate_->handle_scope_implementer()->Iterate(v);
5770   isolate_->IterateDeferredHandles(v);
5771   v->Synchronize(VisitorSynchronization::kHandleScope);
5772
5773   // Iterate over the builtin code objects and code stubs in the
5774   // heap. Note that it is not necessary to iterate over code objects
5775   // on scavenge collections.
5776   if (mode != VISIT_ALL_IN_SCAVENGE) {
5777     isolate_->builtins()->IterateBuiltins(v);
5778   }
5779   v->Synchronize(VisitorSynchronization::kBuiltins);
5780
5781   // Iterate over global handles.
5782   switch (mode) {
5783     case VISIT_ONLY_STRONG:
5784       isolate_->global_handles()->IterateStrongRoots(v);
5785       break;
5786     case VISIT_ALL_IN_SCAVENGE:
5787       isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5788       break;
5789     case VISIT_ALL_IN_SWEEP_NEWSPACE:
5790     case VISIT_ALL:
5791       isolate_->global_handles()->IterateAllRoots(v);
5792       break;
5793   }
5794   v->Synchronize(VisitorSynchronization::kGlobalHandles);
5795
5796   // Iterate over pointers being held by inactive threads.
5797   isolate_->thread_manager()->Iterate(v);
5798   v->Synchronize(VisitorSynchronization::kThreadManager);
5799
5800   // Iterate over the pointers the Serialization/Deserialization code is
5801   // holding.
5802   // During garbage collection this keeps the partial snapshot cache alive.
5803   // During deserialization of the startup snapshot this creates the partial
5804   // snapshot cache and deserializes the objects it refers to.  During
5805   // serialization this does nothing, since the partial snapshot cache is
5806   // empty.  However the next thing we do is create the partial snapshot,
5807   // filling up the partial snapshot cache with objects it needs as we go.
5808   SerializerDeserializer::Iterate(v);
5809   // We don't do a v->Synchronize call here, because in debug mode that will
5810   // output a flag to the snapshot.  However at this point the serializer and
5811   // deserializer are deliberately a little unsynchronized (see above) so the
5812   // checking of the sync flag in the snapshot would fail.
5813 }
5814
5815
5816 // TODO(1236194): Since the heap size is configurable on the command line
5817 // and through the API, we should gracefully handle the case that the heap
5818 // size is not big enough to fit all the initial objects.
5819 bool Heap::ConfigureHeap(int max_semispace_size,
5820                          intptr_t max_old_gen_size,
5821                          intptr_t max_executable_size) {
5822   if (HasBeenSetUp()) return false;
5823
5824   if (FLAG_stress_compaction) {
5825     // This will cause more frequent GCs when stressing.
5826     max_semispace_size_ = Page::kPageSize;
5827   }
5828
5829   if (max_semispace_size > 0) {
5830     if (max_semispace_size < Page::kPageSize) {
5831       max_semispace_size = Page::kPageSize;
5832       if (FLAG_trace_gc) {
5833         PrintPID("Max semispace size cannot be less than %dkbytes\n",
5834                  Page::kPageSize >> 10);
5835       }
5836     }
5837     max_semispace_size_ = max_semispace_size;
5838   }
5839
5840   if (Snapshot::IsEnabled()) {
5841     // If we are using a snapshot we always reserve the default amount
5842     // of memory for each semispace because code in the snapshot has
5843     // write-barrier code that relies on the size and alignment of new
5844     // space.  We therefore cannot use a larger max semispace size
5845     // than the default reserved semispace size.
5846     if (max_semispace_size_ > reserved_semispace_size_) {
5847       max_semispace_size_ = reserved_semispace_size_;
5848       if (FLAG_trace_gc) {
5849         PrintPID("Max semispace size cannot be more than %dkbytes\n",
5850                  reserved_semispace_size_ >> 10);
5851       }
5852     }
5853   } else {
5854     // If we are not using snapshots we reserve space for the actual
5855     // max semispace size.
5856     reserved_semispace_size_ = max_semispace_size_;
5857   }
5858
5859   if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5860   if (max_executable_size > 0) {
5861     max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5862   }
5863
5864   // The max executable size must be less than or equal to the max old
5865   // generation size.
5866   if (max_executable_size_ > max_old_generation_size_) {
5867     max_executable_size_ = max_old_generation_size_;
5868   }
5869
5870   // The new space size must be a power of two to support single-bit testing
5871   // for containment.
5872   max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5873   reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5874   initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5875   external_allocation_limit_ = 16 * max_semispace_size_;
5876
5877   // The old generation is paged and needs at least one page for each space.
5878   int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5879   max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5880                                                        Page::kPageSize),
5881                                  RoundUp(max_old_generation_size_,
5882                                          Page::kPageSize));
5883
5884   configured_ = true;
5885   return true;
5886 }
5887
5888
5889 bool Heap::ConfigureHeapDefault() {
5890   return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5891                        static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5892                        static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5893 }
5894
5895
5896 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5897   *stats->start_marker = HeapStats::kStartMarker;
5898   *stats->end_marker = HeapStats::kEndMarker;
5899   *stats->new_space_size = new_space_.SizeAsInt();
5900   *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5901   *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5902   *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5903   *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5904   *stats->old_data_space_capacity = old_data_space_->Capacity();
5905   *stats->code_space_size = code_space_->SizeOfObjects();
5906   *stats->code_space_capacity = code_space_->Capacity();
5907   *stats->map_space_size = map_space_->SizeOfObjects();
5908   *stats->map_space_capacity = map_space_->Capacity();
5909   *stats->cell_space_size = cell_space_->SizeOfObjects();
5910   *stats->cell_space_capacity = cell_space_->Capacity();
5911   *stats->lo_space_size = lo_space_->Size();
5912   isolate_->global_handles()->RecordStats(stats);
5913   *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5914   *stats->memory_allocator_capacity =
5915       isolate()->memory_allocator()->Size() +
5916       isolate()->memory_allocator()->Available();
5917   *stats->os_error = OS::GetLastError();
5918       isolate()->memory_allocator()->Available();
5919   if (take_snapshot) {
5920     HeapIterator iterator;
5921     for (HeapObject* obj = iterator.next();
5922          obj != NULL;
5923          obj = iterator.next()) {
5924       InstanceType type = obj->map()->instance_type();
5925       ASSERT(0 <= type && type <= LAST_TYPE);
5926       stats->objects_per_type[type]++;
5927       stats->size_per_type[type] += obj->Size();
5928     }
5929   }
5930 }
5931
5932
5933 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5934   return old_pointer_space_->SizeOfObjects()
5935       + old_data_space_->SizeOfObjects()
5936       + code_space_->SizeOfObjects()
5937       + map_space_->SizeOfObjects()
5938       + cell_space_->SizeOfObjects()
5939       + lo_space_->SizeOfObjects();
5940 }
5941
5942
5943 intptr_t Heap::PromotedExternalMemorySize() {
5944   if (amount_of_external_allocated_memory_
5945       <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5946   return amount_of_external_allocated_memory_
5947       - amount_of_external_allocated_memory_at_last_global_gc_;
5948 }
5949
5950 #ifdef DEBUG
5951
5952 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5953 static const int kMarkTag = 2;
5954
5955
5956 class HeapDebugUtils {
5957  public:
5958   explicit HeapDebugUtils(Heap* heap)
5959     : search_for_any_global_(false),
5960       search_target_(NULL),
5961       found_target_(false),
5962       object_stack_(20),
5963       heap_(heap) {
5964   }
5965
5966   class MarkObjectVisitor : public ObjectVisitor {
5967    public:
5968     explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5969
5970     void VisitPointers(Object** start, Object** end) {
5971       // Copy all HeapObject pointers in [start, end)
5972       for (Object** p = start; p < end; p++) {
5973         if ((*p)->IsHeapObject())
5974           utils_->MarkObjectRecursively(p);
5975       }
5976     }
5977
5978     HeapDebugUtils* utils_;
5979   };
5980
5981   void MarkObjectRecursively(Object** p) {
5982     if (!(*p)->IsHeapObject()) return;
5983
5984     HeapObject* obj = HeapObject::cast(*p);
5985
5986     Object* map = obj->map();
5987
5988     if (!map->IsHeapObject()) return;  // visited before
5989
5990     if (found_target_) return;  // stop if target found
5991     object_stack_.Add(obj);
5992     if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5993         (!search_for_any_global_ && (obj == search_target_))) {
5994       found_target_ = true;
5995       return;
5996     }
5997
5998     // not visited yet
5999     Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6000
6001     Address map_addr = map_p->address();
6002
6003     obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6004
6005     MarkObjectRecursively(&map);
6006
6007     MarkObjectVisitor mark_visitor(this);
6008
6009     obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
6010                      &mark_visitor);
6011
6012     if (!found_target_)  // don't pop if found the target
6013       object_stack_.RemoveLast();
6014   }
6015
6016
6017   class UnmarkObjectVisitor : public ObjectVisitor {
6018    public:
6019     explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6020
6021     void VisitPointers(Object** start, Object** end) {
6022       // Copy all HeapObject pointers in [start, end)
6023       for (Object** p = start; p < end; p++) {
6024         if ((*p)->IsHeapObject())
6025           utils_->UnmarkObjectRecursively(p);
6026       }
6027     }
6028
6029     HeapDebugUtils* utils_;
6030   };
6031
6032
6033   void UnmarkObjectRecursively(Object** p) {
6034     if (!(*p)->IsHeapObject()) return;
6035
6036     HeapObject* obj = HeapObject::cast(*p);
6037
6038     Object* map = obj->map();
6039
6040     if (map->IsHeapObject()) return;  // unmarked already
6041
6042     Address map_addr = reinterpret_cast<Address>(map);
6043
6044     map_addr -= kMarkTag;
6045
6046     ASSERT_TAG_ALIGNED(map_addr);
6047
6048     HeapObject* map_p = HeapObject::FromAddress(map_addr);
6049
6050     obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6051
6052     UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
6053
6054     UnmarkObjectVisitor unmark_visitor(this);
6055
6056     obj->IterateBody(Map::cast(map_p)->instance_type(),
6057                      obj->SizeFromMap(Map::cast(map_p)),
6058                      &unmark_visitor);
6059   }
6060
6061
6062   void MarkRootObjectRecursively(Object** root) {
6063     if (search_for_any_global_) {
6064       ASSERT(search_target_ == NULL);
6065     } else {
6066       ASSERT(search_target_->IsHeapObject());
6067     }
6068     found_target_ = false;
6069     object_stack_.Clear();
6070
6071     MarkObjectRecursively(root);
6072     UnmarkObjectRecursively(root);
6073
6074     if (found_target_) {
6075       PrintF("=====================================\n");
6076       PrintF("====        Path to object       ====\n");
6077       PrintF("=====================================\n\n");
6078
6079       ASSERT(!object_stack_.is_empty());
6080       for (int i = 0; i < object_stack_.length(); i++) {
6081         if (i > 0) PrintF("\n     |\n     |\n     V\n\n");
6082         Object* obj = object_stack_[i];
6083         obj->Print();
6084       }
6085       PrintF("=====================================\n");
6086     }
6087   }
6088
6089   // Helper class for visiting HeapObjects recursively.
6090   class MarkRootVisitor: public ObjectVisitor {
6091    public:
6092     explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6093
6094     void VisitPointers(Object** start, Object** end) {
6095       // Visit all HeapObject pointers in [start, end)
6096       for (Object** p = start; p < end; p++) {
6097         if ((*p)->IsHeapObject())
6098           utils_->MarkRootObjectRecursively(p);
6099       }
6100     }
6101
6102     HeapDebugUtils* utils_;
6103   };
6104
6105   bool search_for_any_global_;
6106   Object* search_target_;
6107   bool found_target_;
6108   List<Object*> object_stack_;
6109   Heap* heap_;
6110
6111   friend class Heap;
6112 };
6113
6114 #endif
6115
6116
6117 V8_DECLARE_ONCE(initialize_gc_once);
6118
6119 static void InitializeGCOnce() {
6120   InitializeScavengingVisitorsTables();
6121   NewSpaceScavenger::Initialize();
6122   MarkCompactCollector::Initialize();
6123 }
6124
6125 bool Heap::SetUp(bool create_heap_objects) {
6126 #ifdef DEBUG
6127   allocation_timeout_ = FLAG_gc_interval;
6128   debug_utils_ = new HeapDebugUtils(this);
6129 #endif
6130
6131   // Initialize heap spaces and initial maps and objects. Whenever something
6132   // goes wrong, just return false. The caller should check the results and
6133   // call Heap::TearDown() to release allocated memory.
6134   //
6135   // If the heap is not yet configured (e.g. through the API), configure it.
6136   // Configuration is based on the flags new-space-size (really the semispace
6137   // size) and old-space-size if set or the initial values of semispace_size_
6138   // and old_generation_size_ otherwise.
6139   if (!configured_) {
6140     if (!ConfigureHeapDefault()) return false;
6141   }
6142
6143   CallOnce(&initialize_gc_once, &InitializeGCOnce);
6144
6145   MarkMapPointersAsEncoded(false);
6146
6147   // Set up memory allocator.
6148   if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
6149       return false;
6150
6151   // Set up new space.
6152   if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
6153     return false;
6154   }
6155
6156   // Initialize old pointer space.
6157   old_pointer_space_ =
6158       new OldSpace(this,
6159                    max_old_generation_size_,
6160                    OLD_POINTER_SPACE,
6161                    NOT_EXECUTABLE);
6162   if (old_pointer_space_ == NULL) return false;
6163   if (!old_pointer_space_->SetUp()) return false;
6164
6165   // Initialize old data space.
6166   old_data_space_ =
6167       new OldSpace(this,
6168                    max_old_generation_size_,
6169                    OLD_DATA_SPACE,
6170                    NOT_EXECUTABLE);
6171   if (old_data_space_ == NULL) return false;
6172   if (!old_data_space_->SetUp()) return false;
6173
6174   // Initialize the code space, set its maximum capacity to the old
6175   // generation size. It needs executable memory.
6176   // On 64-bit platform(s), we put all code objects in a 2 GB range of
6177   // virtual address space, so that they can call each other with near calls.
6178   if (code_range_size_ > 0) {
6179     if (!isolate_->code_range()->SetUp(code_range_size_)) {
6180       return false;
6181     }
6182   }
6183
6184   code_space_ =
6185       new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
6186   if (code_space_ == NULL) return false;
6187   if (!code_space_->SetUp()) return false;
6188
6189   // Initialize map space.
6190   map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
6191   if (map_space_ == NULL) return false;
6192   if (!map_space_->SetUp()) return false;
6193
6194   // Initialize global property cell space.
6195   cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
6196   if (cell_space_ == NULL) return false;
6197   if (!cell_space_->SetUp()) return false;
6198
6199   // The large object code space may contain code or data.  We set the memory
6200   // to be non-executable here for safety, but this means we need to enable it
6201   // explicitly when allocating large code objects.
6202   lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
6203   if (lo_space_ == NULL) return false;
6204   if (!lo_space_->SetUp()) return false;
6205
6206   // Set up the seed that is used to randomize the string hash function.
6207   ASSERT(hash_seed() == 0);
6208   if (FLAG_randomize_hashes) {
6209     if (FLAG_hash_seed == 0) {
6210       set_hash_seed(
6211           Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
6212     } else {
6213       set_hash_seed(Smi::FromInt(FLAG_hash_seed));
6214     }
6215   }
6216
6217   if (create_heap_objects) {
6218     // Create initial maps.
6219     if (!CreateInitialMaps()) return false;
6220     if (!CreateApiObjects()) return false;
6221
6222     // Create initial objects
6223     if (!CreateInitialObjects()) return false;
6224
6225     native_contexts_list_ = undefined_value();
6226   }
6227
6228   LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
6229   LOG(isolate_, IntPtrTEvent("heap-available", Available()));
6230
6231   store_buffer()->SetUp();
6232
6233   if (FLAG_parallel_recompilation) relocation_mutex_ = OS::CreateMutex();
6234
6235   return true;
6236 }
6237
6238
6239 void Heap::SetStackLimits() {
6240   ASSERT(isolate_ != NULL);
6241   ASSERT(isolate_ == isolate());
6242   // On 64 bit machines, pointers are generally out of range of Smis.  We write
6243   // something that looks like an out of range Smi to the GC.
6244
6245   // Set up the special root array entries containing the stack limits.
6246   // These are actually addresses, but the tag makes the GC ignore it.
6247   roots_[kStackLimitRootIndex] =
6248       reinterpret_cast<Object*>(
6249           (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
6250   roots_[kRealStackLimitRootIndex] =
6251       reinterpret_cast<Object*>(
6252           (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
6253 }
6254
6255
6256 void Heap::TearDown() {
6257 #ifdef DEBUG
6258   if (FLAG_verify_heap) {
6259     Verify();
6260   }
6261 #endif
6262   if (FLAG_print_cumulative_gc_stat) {
6263     PrintF("\n\n");
6264     PrintF("gc_count=%d ", gc_count_);
6265     PrintF("mark_sweep_count=%d ", ms_count_);
6266     PrintF("max_gc_pause=%d ", get_max_gc_pause());
6267     PrintF("total_gc_time=%d ", total_gc_time_ms_);
6268     PrintF("min_in_mutator=%d ", get_min_in_mutator());
6269     PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
6270            get_max_alive_after_gc());
6271     PrintF("\n\n");
6272   }
6273
6274   isolate_->global_handles()->TearDown();
6275
6276   external_string_table_.TearDown();
6277
6278   new_space_.TearDown();
6279
6280   if (old_pointer_space_ != NULL) {
6281     old_pointer_space_->TearDown();
6282     delete old_pointer_space_;
6283     old_pointer_space_ = NULL;
6284   }
6285
6286   if (old_data_space_ != NULL) {
6287     old_data_space_->TearDown();
6288     delete old_data_space_;
6289     old_data_space_ = NULL;
6290   }
6291
6292   if (code_space_ != NULL) {
6293     code_space_->TearDown();
6294     delete code_space_;
6295     code_space_ = NULL;
6296   }
6297
6298   if (map_space_ != NULL) {
6299     map_space_->TearDown();
6300     delete map_space_;
6301     map_space_ = NULL;
6302   }
6303
6304   if (cell_space_ != NULL) {
6305     cell_space_->TearDown();
6306     delete cell_space_;
6307     cell_space_ = NULL;
6308   }
6309
6310   if (lo_space_ != NULL) {
6311     lo_space_->TearDown();
6312     delete lo_space_;
6313     lo_space_ = NULL;
6314   }
6315
6316   store_buffer()->TearDown();
6317   incremental_marking()->TearDown();
6318
6319   isolate_->memory_allocator()->TearDown();
6320
6321   delete relocation_mutex_;
6322
6323 #ifdef DEBUG
6324   delete debug_utils_;
6325   debug_utils_ = NULL;
6326 #endif
6327 }
6328
6329
6330 void Heap::Shrink() {
6331   // Try to shrink all paged spaces.
6332   PagedSpaces spaces;
6333   for (PagedSpace* space = spaces.next();
6334        space != NULL;
6335        space = spaces.next()) {
6336     space->ReleaseAllUnusedPages();
6337   }
6338 }
6339
6340
6341 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6342   ASSERT(callback != NULL);
6343   GCPrologueCallbackPair pair(callback, gc_type);
6344   ASSERT(!gc_prologue_callbacks_.Contains(pair));
6345   return gc_prologue_callbacks_.Add(pair);
6346 }
6347
6348
6349 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6350   ASSERT(callback != NULL);
6351   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6352     if (gc_prologue_callbacks_[i].callback == callback) {
6353       gc_prologue_callbacks_.Remove(i);
6354       return;
6355     }
6356   }
6357   UNREACHABLE();
6358 }
6359
6360
6361 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6362   ASSERT(callback != NULL);
6363   GCEpilogueCallbackPair pair(callback, gc_type);
6364   ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6365   return gc_epilogue_callbacks_.Add(pair);
6366 }
6367
6368
6369 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6370   ASSERT(callback != NULL);
6371   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6372     if (gc_epilogue_callbacks_[i].callback == callback) {
6373       gc_epilogue_callbacks_.Remove(i);
6374       return;
6375     }
6376   }
6377   UNREACHABLE();
6378 }
6379
6380
6381 #ifdef DEBUG
6382
6383 class PrintHandleVisitor: public ObjectVisitor {
6384  public:
6385   void VisitPointers(Object** start, Object** end) {
6386     for (Object** p = start; p < end; p++)
6387       PrintF("  handle %p to %p\n",
6388              reinterpret_cast<void*>(p),
6389              reinterpret_cast<void*>(*p));
6390   }
6391 };
6392
6393 void Heap::PrintHandles() {
6394   PrintF("Handles:\n");
6395   PrintHandleVisitor v;
6396   isolate_->handle_scope_implementer()->Iterate(&v);
6397 }
6398
6399 #endif
6400
6401
6402 Space* AllSpaces::next() {
6403   switch (counter_++) {
6404     case NEW_SPACE:
6405       return HEAP->new_space();
6406     case OLD_POINTER_SPACE:
6407       return HEAP->old_pointer_space();
6408     case OLD_DATA_SPACE:
6409       return HEAP->old_data_space();
6410     case CODE_SPACE:
6411       return HEAP->code_space();
6412     case MAP_SPACE:
6413       return HEAP->map_space();
6414     case CELL_SPACE:
6415       return HEAP->cell_space();
6416     case LO_SPACE:
6417       return HEAP->lo_space();
6418     default:
6419       return NULL;
6420   }
6421 }
6422
6423
6424 PagedSpace* PagedSpaces::next() {
6425   switch (counter_++) {
6426     case OLD_POINTER_SPACE:
6427       return HEAP->old_pointer_space();
6428     case OLD_DATA_SPACE:
6429       return HEAP->old_data_space();
6430     case CODE_SPACE:
6431       return HEAP->code_space();
6432     case MAP_SPACE:
6433       return HEAP->map_space();
6434     case CELL_SPACE:
6435       return HEAP->cell_space();
6436     default:
6437       return NULL;
6438   }
6439 }
6440
6441
6442
6443 OldSpace* OldSpaces::next() {
6444   switch (counter_++) {
6445     case OLD_POINTER_SPACE:
6446       return HEAP->old_pointer_space();
6447     case OLD_DATA_SPACE:
6448       return HEAP->old_data_space();
6449     case CODE_SPACE:
6450       return HEAP->code_space();
6451     default:
6452       return NULL;
6453   }
6454 }
6455
6456
6457 SpaceIterator::SpaceIterator()
6458     : current_space_(FIRST_SPACE),
6459       iterator_(NULL),
6460       size_func_(NULL) {
6461 }
6462
6463
6464 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6465     : current_space_(FIRST_SPACE),
6466       iterator_(NULL),
6467       size_func_(size_func) {
6468 }
6469
6470
6471 SpaceIterator::~SpaceIterator() {
6472   // Delete active iterator if any.
6473   delete iterator_;
6474 }
6475
6476
6477 bool SpaceIterator::has_next() {
6478   // Iterate until no more spaces.
6479   return current_space_ != LAST_SPACE;
6480 }
6481
6482
6483 ObjectIterator* SpaceIterator::next() {
6484   if (iterator_ != NULL) {
6485     delete iterator_;
6486     iterator_ = NULL;
6487     // Move to the next space
6488     current_space_++;
6489     if (current_space_ > LAST_SPACE) {
6490       return NULL;
6491     }
6492   }
6493
6494   // Return iterator for the new current space.
6495   return CreateIterator();
6496 }
6497
6498
6499 // Create an iterator for the space to iterate.
6500 ObjectIterator* SpaceIterator::CreateIterator() {
6501   ASSERT(iterator_ == NULL);
6502
6503   switch (current_space_) {
6504     case NEW_SPACE:
6505       iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6506       break;
6507     case OLD_POINTER_SPACE:
6508       iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6509       break;
6510     case OLD_DATA_SPACE:
6511       iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6512       break;
6513     case CODE_SPACE:
6514       iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6515       break;
6516     case MAP_SPACE:
6517       iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6518       break;
6519     case CELL_SPACE:
6520       iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6521       break;
6522     case LO_SPACE:
6523       iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6524       break;
6525   }
6526
6527   // Return the newly allocated iterator;
6528   ASSERT(iterator_ != NULL);
6529   return iterator_;
6530 }
6531
6532
6533 class HeapObjectsFilter {
6534  public:
6535   virtual ~HeapObjectsFilter() {}
6536   virtual bool SkipObject(HeapObject* object) = 0;
6537 };
6538
6539
6540 class UnreachableObjectsFilter : public HeapObjectsFilter {
6541  public:
6542   UnreachableObjectsFilter() {
6543     MarkReachableObjects();
6544   }
6545
6546   ~UnreachableObjectsFilter() {
6547     Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6548   }
6549
6550   bool SkipObject(HeapObject* object) {
6551     MarkBit mark_bit = Marking::MarkBitFrom(object);
6552     return !mark_bit.Get();
6553   }
6554
6555  private:
6556   class MarkingVisitor : public ObjectVisitor {
6557    public:
6558     MarkingVisitor() : marking_stack_(10) {}
6559
6560     void VisitPointers(Object** start, Object** end) {
6561       for (Object** p = start; p < end; p++) {
6562         if (!(*p)->IsHeapObject()) continue;
6563         HeapObject* obj = HeapObject::cast(*p);
6564         MarkBit mark_bit = Marking::MarkBitFrom(obj);
6565         if (!mark_bit.Get()) {
6566           mark_bit.Set();
6567           marking_stack_.Add(obj);
6568         }
6569       }
6570     }
6571
6572     void TransitiveClosure() {
6573       while (!marking_stack_.is_empty()) {
6574         HeapObject* obj = marking_stack_.RemoveLast();
6575         obj->Iterate(this);
6576       }
6577     }
6578
6579    private:
6580     List<HeapObject*> marking_stack_;
6581   };
6582
6583   void MarkReachableObjects() {
6584     Heap* heap = Isolate::Current()->heap();
6585     MarkingVisitor visitor;
6586     heap->IterateRoots(&visitor, VISIT_ALL);
6587     visitor.TransitiveClosure();
6588   }
6589
6590   AssertNoAllocation no_alloc;
6591 };
6592
6593
6594 HeapIterator::HeapIterator()
6595     : filtering_(HeapIterator::kNoFiltering),
6596       filter_(NULL) {
6597   Init();
6598 }
6599
6600
6601 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6602     : filtering_(filtering),
6603       filter_(NULL) {
6604   Init();
6605 }
6606
6607
6608 HeapIterator::~HeapIterator() {
6609   Shutdown();
6610 }
6611
6612
6613 void HeapIterator::Init() {
6614   // Start the iteration.
6615   space_iterator_ = new SpaceIterator;
6616   switch (filtering_) {
6617     case kFilterUnreachable:
6618       filter_ = new UnreachableObjectsFilter;
6619       break;
6620     default:
6621       break;
6622   }
6623   object_iterator_ = space_iterator_->next();
6624 }
6625
6626
6627 void HeapIterator::Shutdown() {
6628 #ifdef DEBUG
6629   // Assert that in filtering mode we have iterated through all
6630   // objects. Otherwise, heap will be left in an inconsistent state.
6631   if (filtering_ != kNoFiltering) {
6632     ASSERT(object_iterator_ == NULL);
6633   }
6634 #endif
6635   // Make sure the last iterator is deallocated.
6636   delete space_iterator_;
6637   space_iterator_ = NULL;
6638   object_iterator_ = NULL;
6639   delete filter_;
6640   filter_ = NULL;
6641 }
6642
6643
6644 HeapObject* HeapIterator::next() {
6645   if (filter_ == NULL) return NextObject();
6646
6647   HeapObject* obj = NextObject();
6648   while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6649   return obj;
6650 }
6651
6652
6653 HeapObject* HeapIterator::NextObject() {
6654   // No iterator means we are done.
6655   if (object_iterator_ == NULL) return NULL;
6656
6657   if (HeapObject* obj = object_iterator_->next_object()) {
6658     // If the current iterator has more objects we are fine.
6659     return obj;
6660   } else {
6661     // Go though the spaces looking for one that has objects.
6662     while (space_iterator_->has_next()) {
6663       object_iterator_ = space_iterator_->next();
6664       if (HeapObject* obj = object_iterator_->next_object()) {
6665         return obj;
6666       }
6667     }
6668   }
6669   // Done with the last space.
6670   object_iterator_ = NULL;
6671   return NULL;
6672 }
6673
6674
6675 void HeapIterator::reset() {
6676   // Restart the iterator.
6677   Shutdown();
6678   Init();
6679 }
6680
6681
6682 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6683
6684 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6685
6686 class PathTracer::MarkVisitor: public ObjectVisitor {
6687  public:
6688   explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6689   void VisitPointers(Object** start, Object** end) {
6690     // Scan all HeapObject pointers in [start, end)
6691     for (Object** p = start; !tracer_->found() && (p < end); p++) {
6692       if ((*p)->IsHeapObject())
6693         tracer_->MarkRecursively(p, this);
6694     }
6695   }
6696
6697  private:
6698   PathTracer* tracer_;
6699 };
6700
6701
6702 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6703  public:
6704   explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6705   void VisitPointers(Object** start, Object** end) {
6706     // Scan all HeapObject pointers in [start, end)
6707     for (Object** p = start; p < end; p++) {
6708       if ((*p)->IsHeapObject())
6709         tracer_->UnmarkRecursively(p, this);
6710     }
6711   }
6712
6713  private:
6714   PathTracer* tracer_;
6715 };
6716
6717
6718 void PathTracer::VisitPointers(Object** start, Object** end) {
6719   bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6720   // Visit all HeapObject pointers in [start, end)
6721   for (Object** p = start; !done && (p < end); p++) {
6722     if ((*p)->IsHeapObject()) {
6723       TracePathFrom(p);
6724       done = ((what_to_find_ == FIND_FIRST) && found_target_);
6725     }
6726   }
6727 }
6728
6729
6730 void PathTracer::Reset() {
6731   found_target_ = false;
6732   object_stack_.Clear();
6733 }
6734
6735
6736 void PathTracer::TracePathFrom(Object** root) {
6737   ASSERT((search_target_ == kAnyGlobalObject) ||
6738          search_target_->IsHeapObject());
6739   found_target_in_trace_ = false;
6740   Reset();
6741
6742   MarkVisitor mark_visitor(this);
6743   MarkRecursively(root, &mark_visitor);
6744
6745   UnmarkVisitor unmark_visitor(this);
6746   UnmarkRecursively(root, &unmark_visitor);
6747
6748   ProcessResults();
6749 }
6750
6751
6752 static bool SafeIsNativeContext(HeapObject* obj) {
6753   return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map();
6754 }
6755
6756
6757 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6758   if (!(*p)->IsHeapObject()) return;
6759
6760   HeapObject* obj = HeapObject::cast(*p);
6761
6762   Object* map = obj->map();
6763
6764   if (!map->IsHeapObject()) return;  // visited before
6765
6766   if (found_target_in_trace_) return;  // stop if target found
6767   object_stack_.Add(obj);
6768   if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6769       (obj == search_target_)) {
6770     found_target_in_trace_ = true;
6771     found_target_ = true;
6772     return;
6773   }
6774
6775   bool is_native_context = SafeIsNativeContext(obj);
6776
6777   // not visited yet
6778   Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6779
6780   Address map_addr = map_p->address();
6781
6782   obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6783
6784   // Scan the object body.
6785   if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6786     // This is specialized to scan Context's properly.
6787     Object** start = reinterpret_cast<Object**>(obj->address() +
6788                                                 Context::kHeaderSize);
6789     Object** end = reinterpret_cast<Object**>(obj->address() +
6790         Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6791     mark_visitor->VisitPointers(start, end);
6792   } else {
6793     obj->IterateBody(map_p->instance_type(),
6794                      obj->SizeFromMap(map_p),
6795                      mark_visitor);
6796   }
6797
6798   // Scan the map after the body because the body is a lot more interesting
6799   // when doing leak detection.
6800   MarkRecursively(&map, mark_visitor);
6801
6802   if (!found_target_in_trace_)  // don't pop if found the target
6803     object_stack_.RemoveLast();
6804 }
6805
6806
6807 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6808   if (!(*p)->IsHeapObject()) return;
6809
6810   HeapObject* obj = HeapObject::cast(*p);
6811
6812   Object* map = obj->map();
6813
6814   if (map->IsHeapObject()) return;  // unmarked already
6815
6816   Address map_addr = reinterpret_cast<Address>(map);
6817
6818   map_addr -= kMarkTag;
6819
6820   ASSERT_TAG_ALIGNED(map_addr);
6821
6822   HeapObject* map_p = HeapObject::FromAddress(map_addr);
6823
6824   obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6825
6826   UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6827
6828   obj->IterateBody(Map::cast(map_p)->instance_type(),
6829                    obj->SizeFromMap(Map::cast(map_p)),
6830                    unmark_visitor);
6831 }
6832
6833
6834 void PathTracer::ProcessResults() {
6835   if (found_target_) {
6836     PrintF("=====================================\n");
6837     PrintF("====        Path to object       ====\n");
6838     PrintF("=====================================\n\n");
6839
6840     ASSERT(!object_stack_.is_empty());
6841     for (int i = 0; i < object_stack_.length(); i++) {
6842       if (i > 0) PrintF("\n     |\n     |\n     V\n\n");
6843       Object* obj = object_stack_[i];
6844       obj->Print();
6845     }
6846     PrintF("=====================================\n");
6847   }
6848 }
6849 #endif  // DEBUG || LIVE_OBJECT_LIST
6850
6851
6852 #ifdef DEBUG
6853 // Triggers a depth-first traversal of reachable objects from one
6854 // given root object and finds a path to a specific heap object and
6855 // prints it.
6856 void Heap::TracePathToObjectFrom(Object* target, Object* root) {
6857   PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6858   tracer.VisitPointer(&root);
6859 }
6860
6861
6862 // Triggers a depth-first traversal of reachable objects from roots
6863 // and finds a path to a specific heap object and prints it.
6864 void Heap::TracePathToObject(Object* target) {
6865   PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6866   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6867 }
6868
6869
6870 // Triggers a depth-first traversal of reachable objects from roots
6871 // and finds a path to any global object and prints it. Useful for
6872 // determining the source for leaks of global objects.
6873 void Heap::TracePathToGlobal() {
6874   PathTracer tracer(PathTracer::kAnyGlobalObject,
6875                     PathTracer::FIND_ALL,
6876                     VISIT_ALL);
6877   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6878 }
6879 #endif
6880
6881
6882 static intptr_t CountTotalHolesSize() {
6883   intptr_t holes_size = 0;
6884   OldSpaces spaces;
6885   for (OldSpace* space = spaces.next();
6886        space != NULL;
6887        space = spaces.next()) {
6888     holes_size += space->Waste() + space->Available();
6889   }
6890   return holes_size;
6891 }
6892
6893
6894 GCTracer::GCTracer(Heap* heap,
6895                    const char* gc_reason,
6896                    const char* collector_reason)
6897     : start_time_(0.0),
6898       start_object_size_(0),
6899       start_memory_size_(0),
6900       gc_count_(0),
6901       full_gc_count_(0),
6902       allocated_since_last_gc_(0),
6903       spent_in_mutator_(0),
6904       promoted_objects_size_(0),
6905       heap_(heap),
6906       gc_reason_(gc_reason),
6907       collector_reason_(collector_reason) {
6908   if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6909   start_time_ = OS::TimeCurrentMillis();
6910   start_object_size_ = heap_->SizeOfObjects();
6911   start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6912
6913   for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6914     scopes_[i] = 0;
6915   }
6916
6917   in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6918
6919   allocated_since_last_gc_ =
6920       heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6921
6922   if (heap_->last_gc_end_timestamp_ > 0) {
6923     spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6924   }
6925
6926   steps_count_ = heap_->incremental_marking()->steps_count();
6927   steps_took_ = heap_->incremental_marking()->steps_took();
6928   longest_step_ = heap_->incremental_marking()->longest_step();
6929   steps_count_since_last_gc_ =
6930       heap_->incremental_marking()->steps_count_since_last_gc();
6931   steps_took_since_last_gc_ =
6932       heap_->incremental_marking()->steps_took_since_last_gc();
6933 }
6934
6935
6936 GCTracer::~GCTracer() {
6937   // Printf ONE line iff flag is set.
6938   if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6939
6940   bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6941
6942   heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6943   heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6944
6945   int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6946
6947   // Update cumulative GC statistics if required.
6948   if (FLAG_print_cumulative_gc_stat) {
6949     heap_->total_gc_time_ms_ += time;
6950     heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6951     heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6952                                      heap_->alive_after_last_gc_);
6953     if (!first_gc) {
6954       heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6955                                    static_cast<int>(spent_in_mutator_));
6956     }
6957   } else if (FLAG_trace_gc_verbose) {
6958     heap_->total_gc_time_ms_ += time;
6959   }
6960
6961   if (collector_ == SCAVENGER && FLAG_trace_gc_ignore_scavenger) return;
6962
6963   PrintPID("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6964
6965   if (!FLAG_trace_gc_nvp) {
6966     int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6967
6968     double end_memory_size_mb =
6969         static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6970
6971     PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6972            CollectorString(),
6973            static_cast<double>(start_object_size_) / MB,
6974            static_cast<double>(start_memory_size_) / MB,
6975            SizeOfHeapObjects(),
6976            end_memory_size_mb);
6977
6978     if (external_time > 0) PrintF("%d / ", external_time);
6979     PrintF("%d ms", time);
6980     if (steps_count_ > 0) {
6981       if (collector_ == SCAVENGER) {
6982         PrintF(" (+ %d ms in %d steps since last GC)",
6983                static_cast<int>(steps_took_since_last_gc_),
6984                steps_count_since_last_gc_);
6985       } else {
6986         PrintF(" (+ %d ms in %d steps since start of marking, "
6987                    "biggest step %f ms)",
6988                static_cast<int>(steps_took_),
6989                steps_count_,
6990                longest_step_);
6991       }
6992     }
6993
6994     if (gc_reason_ != NULL) {
6995       PrintF(" [%s]", gc_reason_);
6996     }
6997
6998     if (collector_reason_ != NULL) {
6999       PrintF(" [%s]", collector_reason_);
7000     }
7001
7002     PrintF(".\n");
7003   } else {
7004     PrintF("pause=%d ", time);
7005     PrintF("mutator=%d ", static_cast<int>(spent_in_mutator_));
7006     PrintF("gc=");
7007     switch (collector_) {
7008       case SCAVENGER:
7009         PrintF("s");
7010         break;
7011       case MARK_COMPACTOR:
7012         PrintF("ms");
7013         break;
7014       default:
7015         UNREACHABLE();
7016     }
7017     PrintF(" ");
7018
7019     PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
7020     PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
7021     PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
7022     PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
7023     PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
7024     PrintF("new_new=%d ",
7025            static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
7026     PrintF("root_new=%d ",
7027            static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
7028     PrintF("old_new=%d ",
7029            static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
7030     PrintF("compaction_ptrs=%d ",
7031            static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
7032     PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
7033         Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
7034     PrintF("misc_compaction=%d ",
7035            static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
7036
7037     PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
7038     PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
7039     PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
7040            in_free_list_or_wasted_before_gc_);
7041     PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
7042
7043     PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
7044     PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
7045
7046     if (collector_ == SCAVENGER) {
7047       PrintF("stepscount=%d ", steps_count_since_last_gc_);
7048       PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
7049     } else {
7050       PrintF("stepscount=%d ", steps_count_);
7051       PrintF("stepstook=%d ", static_cast<int>(steps_took_));
7052     }
7053
7054     PrintF("\n");
7055   }
7056
7057   heap_->PrintShortHeapStatistics();
7058 }
7059
7060
7061 const char* GCTracer::CollectorString() {
7062   switch (collector_) {
7063     case SCAVENGER:
7064       return "Scavenge";
7065     case MARK_COMPACTOR:
7066       return "Mark-sweep";
7067   }
7068   return "Unknown GC";
7069 }
7070
7071
7072 int KeyedLookupCache::Hash(Map* map, String* name) {
7073   // Uses only lower 32 bits if pointers are larger.
7074   uintptr_t addr_hash =
7075       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
7076   return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
7077 }
7078
7079
7080 int KeyedLookupCache::Lookup(Map* map, String* name) {
7081   int index = (Hash(map, name) & kHashMask);
7082   for (int i = 0; i < kEntriesPerBucket; i++) {
7083     Key& key = keys_[index + i];
7084     if ((key.map == map) && key.name->Equals(name)) {
7085       return field_offsets_[index + i];
7086     }
7087   }
7088   return kNotFound;
7089 }
7090
7091
7092 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
7093   String* symbol;
7094   if (HEAP->LookupSymbolIfExists(name, &symbol)) {
7095     int index = (Hash(map, symbol) & kHashMask);
7096     // After a GC there will be free slots, so we use them in order (this may
7097     // help to get the most frequently used one in position 0).
7098     for (int i = 0; i< kEntriesPerBucket; i++) {
7099       Key& key = keys_[index];
7100       Object* free_entry_indicator = NULL;
7101       if (key.map == free_entry_indicator) {
7102         key.map = map;
7103         key.name = symbol;
7104         field_offsets_[index + i] = field_offset;
7105         return;
7106       }
7107     }
7108     // No free entry found in this bucket, so we move them all down one and
7109     // put the new entry at position zero.
7110     for (int i = kEntriesPerBucket - 1; i > 0; i--) {
7111       Key& key = keys_[index + i];
7112       Key& key2 = keys_[index + i - 1];
7113       key = key2;
7114       field_offsets_[index + i] = field_offsets_[index + i - 1];
7115     }
7116
7117     // Write the new first entry.
7118     Key& key = keys_[index];
7119     key.map = map;
7120     key.name = symbol;
7121     field_offsets_[index] = field_offset;
7122   }
7123 }
7124
7125
7126 void KeyedLookupCache::Clear() {
7127   for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
7128 }
7129
7130
7131 void DescriptorLookupCache::Clear() {
7132   for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
7133 }
7134
7135
7136 #ifdef DEBUG
7137 void Heap::GarbageCollectionGreedyCheck() {
7138   ASSERT(FLAG_gc_greedy);
7139   if (isolate_->bootstrapper()->IsActive()) return;
7140   if (disallow_allocation_failure()) return;
7141   CollectGarbage(NEW_SPACE);
7142 }
7143 #endif
7144
7145
7146 TranscendentalCache::SubCache::SubCache(Type t)
7147   : type_(t),
7148     isolate_(Isolate::Current()) {
7149   uint32_t in0 = 0xffffffffu;  // Bit-pattern for a NaN that isn't
7150   uint32_t in1 = 0xffffffffu;  // generated by the FPU.
7151   for (int i = 0; i < kCacheSize; i++) {
7152     elements_[i].in[0] = in0;
7153     elements_[i].in[1] = in1;
7154     elements_[i].output = NULL;
7155   }
7156 }
7157
7158
7159 void TranscendentalCache::Clear() {
7160   for (int i = 0; i < kNumberOfCaches; i++) {
7161     if (caches_[i] != NULL) {
7162       delete caches_[i];
7163       caches_[i] = NULL;
7164     }
7165   }
7166 }
7167
7168
7169 void ExternalStringTable::CleanUp() {
7170   int last = 0;
7171   for (int i = 0; i < new_space_strings_.length(); ++i) {
7172     if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7173       continue;
7174     }
7175     if (heap_->InNewSpace(new_space_strings_[i])) {
7176       new_space_strings_[last++] = new_space_strings_[i];
7177     } else {
7178       old_space_strings_.Add(new_space_strings_[i]);
7179     }
7180   }
7181   new_space_strings_.Rewind(last);
7182   last = 0;
7183   for (int i = 0; i < old_space_strings_.length(); ++i) {
7184     if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7185       continue;
7186     }
7187     ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
7188     old_space_strings_[last++] = old_space_strings_[i];
7189   }
7190   old_space_strings_.Rewind(last);
7191   if (FLAG_verify_heap) {
7192     Verify();
7193   }
7194 }
7195
7196
7197 void ExternalStringTable::TearDown() {
7198   new_space_strings_.Free();
7199   old_space_strings_.Free();
7200 }
7201
7202
7203 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
7204   chunk->set_next_chunk(chunks_queued_for_free_);
7205   chunks_queued_for_free_ = chunk;
7206 }
7207
7208
7209 void Heap::FreeQueuedChunks() {
7210   if (chunks_queued_for_free_ == NULL) return;
7211   MemoryChunk* next;
7212   MemoryChunk* chunk;
7213   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7214     next = chunk->next_chunk();
7215     chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7216
7217     if (chunk->owner()->identity() == LO_SPACE) {
7218       // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
7219       // If FromAnyPointerAddress encounters a slot that belongs to a large
7220       // chunk queued for deletion it will fail to find the chunk because
7221       // it try to perform a search in the list of pages owned by of the large
7222       // object space and queued chunks were detached from that list.
7223       // To work around this we split large chunk into normal kPageSize aligned
7224       // pieces and initialize size, owner and flags field of every piece.
7225       // If FromAnyPointerAddress encounters a slot that belongs to one of
7226       // these smaller pieces it will treat it as a slot on a normal Page.
7227       Address chunk_end = chunk->address() + chunk->size();
7228       MemoryChunk* inner = MemoryChunk::FromAddress(
7229           chunk->address() + Page::kPageSize);
7230       MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
7231       while (inner <= inner_last) {
7232         // Size of a large chunk is always a multiple of
7233         // OS::AllocateAlignment() so there is always
7234         // enough space for a fake MemoryChunk header.
7235         Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
7236         // Guard against overflow.
7237         if (area_end < inner->address()) area_end = chunk_end;
7238         inner->SetArea(inner->address(), area_end);
7239         inner->set_size(Page::kPageSize);
7240         inner->set_owner(lo_space());
7241         inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7242         inner = MemoryChunk::FromAddress(
7243             inner->address() + Page::kPageSize);
7244       }
7245     }
7246   }
7247   isolate_->heap()->store_buffer()->Compact();
7248   isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
7249   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7250     next = chunk->next_chunk();
7251     isolate_->memory_allocator()->Free(chunk);
7252   }
7253   chunks_queued_for_free_ = NULL;
7254 }
7255
7256
7257 void Heap::RememberUnmappedPage(Address page, bool compacted) {
7258   uintptr_t p = reinterpret_cast<uintptr_t>(page);
7259   // Tag the page pointer to make it findable in the dump file.
7260   if (compacted) {
7261     p ^= 0xc1ead & (Page::kPageSize - 1);  // Cleared.
7262   } else {
7263     p ^= 0x1d1ed & (Page::kPageSize - 1);  // I died.
7264   }
7265   remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
7266       reinterpret_cast<Address>(p);
7267   remembered_unmapped_pages_index_++;
7268   remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
7269 }
7270
7271
7272 void Heap::ClearObjectStats(bool clear_last_time_stats) {
7273   memset(object_counts_, 0, sizeof(object_counts_));
7274   memset(object_sizes_, 0, sizeof(object_sizes_));
7275   if (clear_last_time_stats) {
7276     memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_));
7277     memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_));
7278   }
7279 }
7280
7281
7282 static LazyMutex checkpoint_object_stats_mutex = LAZY_MUTEX_INITIALIZER;
7283
7284
7285 void Heap::CheckpointObjectStats() {
7286   ScopedLock lock(checkpoint_object_stats_mutex.Pointer());
7287   Counters* counters = isolate()->counters();
7288 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)                                    \
7289   counters->count_of_##name()->Increment(                                      \
7290       static_cast<int>(object_counts_[name]));                                 \
7291   counters->count_of_##name()->Decrement(                                      \
7292       static_cast<int>(object_counts_last_time_[name]));                       \
7293   counters->size_of_##name()->Increment(                                       \
7294       static_cast<int>(object_sizes_[name]));                                  \
7295   counters->size_of_##name()->Decrement(                                       \
7296       static_cast<int>(object_sizes_last_time_[name]));
7297   INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7298 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7299   int index;
7300 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)               \
7301   index = FIRST_CODE_KIND_SUB_TYPE + Code::name;          \
7302   counters->count_of_CODE_TYPE_##name()->Increment(       \
7303       static_cast<int>(object_counts_[index]));           \
7304   counters->count_of_CODE_TYPE_##name()->Decrement(       \
7305       static_cast<int>(object_counts_last_time_[index])); \
7306   counters->size_of_CODE_TYPE_##name()->Increment(        \
7307       static_cast<int>(object_sizes_[index]));            \
7308   counters->size_of_CODE_TYPE_##name()->Decrement(        \
7309       static_cast<int>(object_sizes_last_time_[index]));
7310   CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7311 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7312 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)               \
7313   index = FIRST_FIXED_ARRAY_SUB_TYPE + name;              \
7314   counters->count_of_FIXED_ARRAY_##name()->Increment(     \
7315       static_cast<int>(object_counts_[index]));           \
7316   counters->count_of_FIXED_ARRAY_##name()->Decrement(     \
7317       static_cast<int>(object_counts_last_time_[index])); \
7318   counters->size_of_FIXED_ARRAY_##name()->Increment(      \
7319       static_cast<int>(object_sizes_[index]));            \
7320   counters->size_of_FIXED_ARRAY_##name()->Decrement(      \
7321       static_cast<int>(object_sizes_last_time_[index]));
7322   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
7323 #undef ADJUST_LAST_TIME_OBJECT_COUNT
7324
7325   memcpy(object_counts_last_time_, object_counts_, sizeof(object_counts_));
7326   memcpy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_));
7327   ClearObjectStats();
7328 }
7329
7330 } }  // namespace v8::internal