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