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