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