blob: cd0417d23b12b84d52ab9e13f99a3bbec3fc57b3 [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. All Rights Reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
33#include "codegen-inl.h"
34#include "debug.h"
35#include "global-handles.h"
36#include "jsregexp.h"
37#include "mark-compact.h"
38#include "natives.h"
39#include "scanner.h"
40#include "scopeinfo.h"
41#include "v8threads.h"
42
43namespace v8 { namespace internal {
44
45#ifdef DEBUG
46DEFINE_bool(gc_greedy, false, "perform GC prior to some allocations");
47DEFINE_bool(gc_verbose, false, "print stuff during garbage collection");
48DEFINE_bool(heap_stats, false, "report heap statistics before and after GC");
49DEFINE_bool(code_stats, false, "report code statistics after GC");
50DEFINE_bool(verify_heap, false, "verify heap pointers before and after GC");
51DEFINE_bool(print_handles, false, "report handles after GC");
52DEFINE_bool(print_global_handles, false, "report global handles after GC");
53DEFINE_bool(print_rset, false, "print remembered sets before GC");
54#endif
55
56DEFINE_int(new_space_size, 0, "size of (each semispace in) the new generation");
57DEFINE_int(old_space_size, 0, "size of the old generation");
58
59DEFINE_bool(gc_global, false, "always perform global GCs");
60DEFINE_int(gc_interval, -1, "garbage collect after <n> allocations");
61DEFINE_bool(trace_gc, false,
62 "print one trace line following each garbage collection");
63
64
65#ifdef ENABLE_LOGGING_AND_PROFILING
66DECLARE_bool(log_gc);
67#endif
68
69
70#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
71 ROOT_LIST(ROOT_ALLOCATION)
72#undef ROOT_ALLOCATION
73
74
75#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
76 STRUCT_LIST(STRUCT_ALLOCATION)
77#undef STRUCT_ALLOCATION
78
79
80#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
81 SYMBOL_LIST(SYMBOL_ALLOCATION)
82#undef SYMBOL_ALLOCATION
83
84
85NewSpace* Heap::new_space_ = NULL;
86OldSpace* Heap::old_space_ = NULL;
87OldSpace* Heap::code_space_ = NULL;
88MapSpace* Heap::map_space_ = NULL;
89LargeObjectSpace* Heap::lo_space_ = NULL;
90
91int Heap::promoted_space_limit_ = 0;
92int Heap::old_gen_exhausted_ = false;
93
94// semispace_size_ should be a power of 2 and old_generation_size_ should be
95// a multiple of Page::kPageSize.
96int Heap::semispace_size_ = 1*MB;
97int Heap::old_generation_size_ = 512*MB;
98int Heap::initial_semispace_size_ = 256*KB;
99
100GCCallback Heap::global_gc_prologue_callback_ = NULL;
101GCCallback Heap::global_gc_epilogue_callback_ = NULL;
102
103// Variables set based on semispace_size_ and old_generation_size_ in
104// ConfigureHeap.
105int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
106
107// Double the new space after this many scavenge collections.
108int Heap::new_space_growth_limit_ = 8;
109int Heap::scavenge_count_ = 0;
110Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
111
112#ifdef DEBUG
113bool Heap::allocation_allowed_ = true;
114int Heap::mc_count_ = 0;
115int Heap::gc_count_ = 0;
116
117int Heap::allocation_timeout_ = 0;
118bool Heap::disallow_allocation_failure_ = false;
119#endif // DEBUG
120
121
122int Heap::Capacity() {
123 if (!HasBeenSetup()) return 0;
124
125 return new_space_->Capacity() +
126 old_space_->Capacity() +
127 code_space_->Capacity() +
128 map_space_->Capacity();
129}
130
131
132int Heap::Available() {
133 if (!HasBeenSetup()) return 0;
134
135 return new_space_->Available() +
136 old_space_->Available() +
137 code_space_->Available() +
138 map_space_->Available();
139}
140
141
142bool Heap::HasBeenSetup() {
143 return new_space_ != NULL &&
144 old_space_ != NULL &&
145 code_space_ != NULL &&
146 map_space_ != NULL &&
147 lo_space_ != NULL;
148}
149
150
151GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
152 // Is global GC requested?
153 if (space != NEW_SPACE || FLAG_gc_global) {
154 Counters::gc_compactor_caused_by_request.Increment();
155 return MARK_COMPACTOR;
156 }
157
158 // Is enough data promoted to justify a global GC?
159 if (PromotedSpaceSize() > promoted_space_limit_) {
160 Counters::gc_compactor_caused_by_promoted_data.Increment();
161 return MARK_COMPACTOR;
162 }
163
164 // Have allocation in OLD and LO failed?
165 if (old_gen_exhausted_) {
166 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
167 return MARK_COMPACTOR;
168 }
169
170 // Is there enough space left in OLD to guarantee that a scavenge can
171 // succeed?
172 //
173 // Note that old_space_->MaxAvailable() undercounts the memory available
174 // for object promotion. It counts only the bytes that the memory
175 // allocator has not yet allocated from the OS and assigned to any space,
176 // and does not count available bytes already in the old space or code
177 // space. Undercounting is safe---we may get an unrequested full GC when
178 // a scavenge would have succeeded.
179 if (old_space_->MaxAvailable() <= new_space_->Size()) {
180 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
181 return MARK_COMPACTOR;
182 }
183
184 // Default
185 return SCAVENGER;
186}
187
188
189// TODO(1238405): Combine the infrastructure for --heap-stats and
190// --log-gc to avoid the complicated preprocessor and flag testing.
191#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
192void Heap::ReportStatisticsBeforeGC() {
193 // Heap::ReportHeapStatistics will also log NewSpace statistics when
194 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
195 // following logic is used to avoid double logging.
196#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
197 if (FLAG_heap_stats || FLAG_log_gc) new_space_->CollectStatistics();
198 if (FLAG_heap_stats) {
199 ReportHeapStatistics("Before GC");
200 } else if (FLAG_log_gc) {
201 new_space_->ReportStatistics();
202 }
203 if (FLAG_heap_stats || FLAG_log_gc) new_space_->ClearHistograms();
204#elif defined(DEBUG)
205 if (FLAG_heap_stats) {
206 new_space_->CollectStatistics();
207 ReportHeapStatistics("Before GC");
208 new_space_->ClearHistograms();
209 }
210#elif defined(ENABLE_LOGGING_AND_PROFILING)
211 if (FLAG_log_gc) {
212 new_space_->CollectStatistics();
213 new_space_->ReportStatistics();
214 new_space_->ClearHistograms();
215 }
216#endif
217}
218
219
220// TODO(1238405): Combine the infrastructure for --heap-stats and
221// --log-gc to avoid the complicated preprocessor and flag testing.
222void Heap::ReportStatisticsAfterGC() {
223 // Similar to the before GC, we use some complicated logic to ensure that
224 // NewSpace statistics are logged exactly once when --log-gc is turned on.
225#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
226 if (FLAG_heap_stats) {
227 ReportHeapStatistics("After GC");
228 } else if (FLAG_log_gc) {
229 new_space_->ReportStatistics();
230 }
231#elif defined(DEBUG)
232 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
233#elif defined(ENABLE_LOGGING_AND_PROFILING)
234 if (FLAG_log_gc) new_space_->ReportStatistics();
235#endif
236}
237#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
238
239
240void Heap::GarbageCollectionPrologue() {
241 RegExpImpl::NewSpaceCollectionPrologue();
242#ifdef DEBUG
243 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
244 allow_allocation(false);
245 gc_count_++;
246
247 if (FLAG_verify_heap) {
248 Verify();
249 }
250
251 if (FLAG_gc_verbose) Print();
252
253 if (FLAG_print_rset) {
254 // By definition, code space does not have remembered set bits that we
255 // care about.
256 old_space_->PrintRSet();
257 map_space_->PrintRSet();
258 lo_space_->PrintRSet();
259 }
260#endif
261
262#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
263 ReportStatisticsBeforeGC();
264#endif
265}
266
267int Heap::SizeOfObjects() {
268 return new_space_->Size() +
269 old_space_->Size() +
270 code_space_->Size() +
271 map_space_->Size() +
272 lo_space_->Size();
273}
274
275void Heap::GarbageCollectionEpilogue() {
276#ifdef DEBUG
277 allow_allocation(true);
278 ZapFromSpace();
279
280 if (FLAG_verify_heap) {
281 Verify();
282 }
283
284 if (FLAG_print_global_handles) GlobalHandles::Print();
285 if (FLAG_print_handles) PrintHandles();
286 if (FLAG_gc_verbose) Print();
287 if (FLAG_code_stats) ReportCodeStatistics("After GC");
288#endif
289
290 Counters::alive_after_last_gc.Set(SizeOfObjects());
291
292 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
293 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
294 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
295#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
296 ReportStatisticsAfterGC();
297#endif
298}
299
300
301// GCTracer collects and prints ONE line after each garbage collector
302// invocation IFF --trace_gc is used.
303
304class GCTracer BASE_EMBEDDED {
305 public:
306 GCTracer() : start_time_(0.0), start_size_(0.0) {
307 if (!FLAG_trace_gc) return;
308 start_time_ = OS::TimeCurrentMillis();
309 start_size_ = SizeOfHeapObjects();
310 }
311
312 ~GCTracer() {
313 if (!FLAG_trace_gc) return;
314 // Printf ONE line iff flag is set.
315 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
316 CollectorString(),
317 start_size_, SizeOfHeapObjects(),
318 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
319 }
320
321 // Sets the collector.
322 void set_collector(GarbageCollector collector) {
323 collector_ = collector;
324 }
325
326 private:
327
328 // Returns a string matching the collector.
329 const char* CollectorString() {
330 switch (collector_) {
331 case SCAVENGER:
332 return "Scavenge";
333 case MARK_COMPACTOR:
334 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
335 : "Mark-sweep";
336 }
337 return "Unknown GC";
338 }
339
340 // Returns size of object in heap (in MB).
341 double SizeOfHeapObjects() {
342 return (static_cast<double>(Heap::SizeOfObjects())) / MB;
343 }
344
345 double start_time_; // Timestamp set in the constructor.
346 double start_size_; // Size of objects in heap set in constructor.
347 GarbageCollector collector_; // Type of collector.
348};
349
350
351
352bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
353 // The VM is in the GC state until exiting this function.
354 VMState state(GC);
355
356#ifdef DEBUG
357 // Reset the allocation timeout to the GC interval, but make sure to
358 // allow at least a few allocations after a collection. The reason
359 // for this is that we have a lot of allocation sequences and we
360 // assume that a garbage collection will allow the subsequent
361 // allocation attempts to go through.
362 allocation_timeout_ = Max(6, FLAG_gc_interval);
363#endif
364
365 { GCTracer tracer;
366 GarbageCollectionPrologue();
367
368 GarbageCollector collector = SelectGarbageCollector(space);
369 tracer.set_collector(collector);
370
371 StatsRate* rate = (collector == SCAVENGER)
372 ? &Counters::gc_scavenger
373 : &Counters::gc_compactor;
374 rate->Start();
375 PerformGarbageCollection(space, collector);
376 rate->Stop();
377
378 GarbageCollectionEpilogue();
379 }
380
381
382#ifdef ENABLE_LOGGING_AND_PROFILING
383 if (FLAG_log_gc) HeapProfiler::WriteSample();
384#endif
385
386 switch (space) {
387 case NEW_SPACE:
388 return new_space_->Available() >= requested_size;
389 case OLD_SPACE:
390 return old_space_->Available() >= requested_size;
391 case CODE_SPACE:
392 return code_space_->Available() >= requested_size;
393 case MAP_SPACE:
394 return map_space_->Available() >= requested_size;
395 case LO_SPACE:
396 return lo_space_->Available() >= requested_size;
397 }
398 return false;
399}
400
401
402void Heap::PerformGarbageCollection(AllocationSpace space,
403 GarbageCollector collector) {
404 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
405 ASSERT(!allocation_allowed_);
406 global_gc_prologue_callback_();
407 }
408
409 if (collector == MARK_COMPACTOR) {
410 MarkCompact();
411
412 int promoted_space_size = PromotedSpaceSize();
413 promoted_space_limit_ =
414 promoted_space_size + Max(2 * MB, (promoted_space_size/100) * 35);
415 old_gen_exhausted_ = false;
416
417 // If we have used the mark-compact collector to collect the new
418 // space, and it has not compacted the new space, we force a
419 // separate scavenge collection. THIS IS A HACK. It covers the
420 // case where (1) a new space collection was requested, (2) the
421 // collector selection policy selected the mark-compact collector,
422 // and (3) the mark-compact collector policy selected not to
423 // compact the new space. In that case, there is no more (usable)
424 // free space in the new space after the collection compared to
425 // before.
426 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
427 Scavenge();
428 }
429 } else {
430 Scavenge();
431 }
432 Counters::objs_since_last_young.Set(0);
433
434 // Process weak handles post gc.
435 GlobalHandles::PostGarbageCollectionProcessing();
436
437 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
438 ASSERT(!allocation_allowed_);
439 global_gc_epilogue_callback_();
440 }
441}
442
443
444void Heap::MarkCompact() {
445 gc_state_ = MARK_COMPACT;
446#ifdef DEBUG
447 mc_count_++;
448#endif
449 LOG(ResourceEvent("markcompact", "begin"));
450
451 MarkCompactPrologue();
452
453 MarkCompactCollector::CollectGarbage();
454
455 MarkCompactEpilogue();
456
457 LOG(ResourceEvent("markcompact", "end"));
458
459 gc_state_ = NOT_IN_GC;
460
461 Shrink();
462
463 Counters::objs_since_last_full.Set(0);
464}
465
466
467void Heap::MarkCompactPrologue() {
468 RegExpImpl::OldSpaceCollectionPrologue();
469 Top::MarkCompactPrologue();
470 ThreadManager::MarkCompactPrologue();
471}
472
473
474void Heap::MarkCompactEpilogue() {
475 Top::MarkCompactEpilogue();
476 ThreadManager::MarkCompactEpilogue();
477}
478
479
480Object* Heap::FindCodeObject(Address a) {
481 Object* obj = code_space_->FindObject(a);
482 if (obj->IsFailure()) {
483 obj = lo_space_->FindObject(a);
484 }
485 return obj;
486}
487
488
489// Helper class for copying HeapObjects
490class CopyVisitor: public ObjectVisitor {
491 public:
492
493 void VisitPointer(Object** p) {
494 CopyObject(p);
495 }
496
497 void VisitPointers(Object** start, Object** end) {
498 // Copy all HeapObject pointers in [start, end)
499 for (Object** p = start; p < end; p++) CopyObject(p);
500 }
501
502 private:
503 void CopyObject(Object** p) {
504 if (!Heap::InFromSpace(*p)) return;
505 Heap::CopyObject(reinterpret_cast<HeapObject**>(p));
506 }
507};
508
509
510// Shared state read by the scavenge collector and set by CopyObject.
511static Address promoted_top = NULL;
512
513
514#ifdef DEBUG
515// Visitor class to verify pointers in code space do not point into
516// new space.
517class VerifyCodeSpacePointersVisitor: public ObjectVisitor {
518 public:
519 void VisitPointers(Object** start, Object**end) {
520 for (Object** current = start; current < end; current++) {
521 if ((*current)->IsHeapObject()) {
522 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
523 }
524 }
525 }
526};
527#endif
528
529void Heap::Scavenge() {
530#ifdef DEBUG
531 if (FLAG_enable_slow_asserts) {
532 VerifyCodeSpacePointersVisitor v;
533 HeapObjectIterator it(code_space_);
534 while (it.has_next()) {
535 HeapObject* object = it.next();
536 if (object->IsCode()) {
537 Code::cast(object)->ConvertICTargetsFromAddressToObject();
538 }
539 object->Iterate(&v);
540 if (object->IsCode()) {
541 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
542 }
543 }
544 }
545#endif
546
547 gc_state_ = SCAVENGE;
548
549 // Implements Cheney's copying algorithm
550 LOG(ResourceEvent("scavenge", "begin"));
551
552 scavenge_count_++;
553 if (new_space_->Capacity() < new_space_->MaximumCapacity() &&
554 scavenge_count_ > new_space_growth_limit_) {
555 // Double the size of the new space, and double the limit. The next
556 // doubling attempt will occur after the current new_space_growth_limit_
557 // more collections.
558 // TODO(1240712): NewSpace::Double has a return value which is
559 // ignored here.
560 new_space_->Double();
561 new_space_growth_limit_ *= 2;
562 }
563
564 // Flip the semispaces. After flipping, to space is empty, from space has
565 // live objects.
566 new_space_->Flip();
567 new_space_->ResetAllocationInfo();
568
569 // We need to sweep newly copied objects which can be in either the to space
570 // or the old space. For to space objects, we use a mark. Newly copied
571 // objects lie between the mark and the allocation top. For objects
572 // promoted to old space, we write their addresses downward from the top of
573 // the new space. Sweeping newly promoted objects requires an allocation
574 // pointer and a mark. Note that the allocation pointer 'top' actually
575 // moves downward from the high address in the to space.
576 //
577 // There is guaranteed to be enough room at the top of the to space for the
578 // addresses of promoted objects: every object promoted frees up its size in
579 // bytes from the top of the new space, and objects are at least one pointer
580 // in size. Using the new space to record promoted addresses makes the
581 // scavenge collector agnostic to the allocation strategy (eg, linear or
582 // free-list) used in old space.
583 Address new_mark = new_space_->ToSpaceLow();
584 Address promoted_mark = new_space_->ToSpaceHigh();
585 promoted_top = new_space_->ToSpaceHigh();
586
587 CopyVisitor copy_visitor;
588 // Copy roots.
589 IterateRoots(&copy_visitor);
590
591 // Copy objects reachable from the old generation. By definition, there
592 // are no intergenerational pointers in code space.
593 IterateRSet(old_space_, &CopyObject);
594 IterateRSet(map_space_, &CopyObject);
595 lo_space_->IterateRSet(&CopyObject);
596
597 bool has_processed_weak_pointers = false;
598
599 while (true) {
600 ASSERT(new_mark <= new_space_->top());
601 ASSERT(promoted_mark >= promoted_top);
602
603 // Copy objects reachable from newly copied objects.
604 while (new_mark < new_space_->top() || promoted_mark > promoted_top) {
605 // Sweep newly copied objects in the to space. The allocation pointer
606 // can change during sweeping.
607 Address previous_top = new_space_->top();
608 SemiSpaceIterator new_it(new_space_, new_mark);
609 while (new_it.has_next()) {
610 new_it.next()->Iterate(&copy_visitor);
611 }
612 new_mark = previous_top;
613
614 // Sweep newly copied objects in the old space. The promotion 'top'
615 // pointer could change during sweeping.
616 previous_top = promoted_top;
617 for (Address current = promoted_mark - kPointerSize;
618 current >= previous_top;
619 current -= kPointerSize) {
620 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
621 object->Iterate(&copy_visitor);
622 UpdateRSet(object);
623 }
624 promoted_mark = previous_top;
625 }
626
627 if (has_processed_weak_pointers) break; // We are done.
628 // Copy objects reachable from weak pointers.
629 GlobalHandles::IterateWeakRoots(&copy_visitor);
630 has_processed_weak_pointers = true;
631 }
632
633 // Set age mark.
634 new_space_->set_age_mark(new_mark);
635
636 LOG(ResourceEvent("scavenge", "end"));
637
638 gc_state_ = NOT_IN_GC;
639}
640
641
642void Heap::ClearRSetRange(Address start, int size_in_bytes) {
643 uint32_t start_bit;
644 Address start_word_address =
645 Page::ComputeRSetBitPosition(start, 0, &start_bit);
646 uint32_t end_bit;
647 Address end_word_address =
648 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
649 0,
650 &end_bit);
651
652 // We want to clear the bits in the starting word starting with the
653 // first bit, and in the ending word up to and including the last
654 // bit. Build a pair of bitmasks to do that.
655 uint32_t start_bitmask = start_bit - 1;
656 uint32_t end_bitmask = ~((end_bit << 1) - 1);
657
658 // If the start address and end address are the same, we mask that
659 // word once, otherwise mask the starting and ending word
660 // separately and all the ones in between.
661 if (start_word_address == end_word_address) {
662 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
663 } else {
664 Memory::uint32_at(start_word_address) &= start_bitmask;
665 Memory::uint32_at(end_word_address) &= end_bitmask;
666 start_word_address += kIntSize;
667 memset(start_word_address, 0, end_word_address - start_word_address);
668 }
669}
670
671
672class UpdateRSetVisitor: public ObjectVisitor {
673 public:
674
675 void VisitPointer(Object** p) {
676 UpdateRSet(p);
677 }
678
679 void VisitPointers(Object** start, Object** end) {
680 // Update a store into slots [start, end), used (a) to update remembered
681 // set when promoting a young object to old space or (b) to rebuild
682 // remembered sets after a mark-compact collection.
683 for (Object** p = start; p < end; p++) UpdateRSet(p);
684 }
685 private:
686
687 void UpdateRSet(Object** p) {
688 // The remembered set should not be set. It should be clear for objects
689 // newly copied to old space, and it is cleared before rebuilding in the
690 // mark-compact collector.
691 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
692 if (Heap::InNewSpace(*p)) {
693 Page::SetRSet(reinterpret_cast<Address>(p), 0);
694 }
695 }
696};
697
698
699int Heap::UpdateRSet(HeapObject* obj) {
700 ASSERT(!InNewSpace(obj));
701 // Special handling of fixed arrays to iterate the body based on the start
702 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
703 // will not work because Page::SetRSet needs to have the start of the
704 // object.
705 if (obj->IsFixedArray()) {
706 FixedArray* array = FixedArray::cast(obj);
707 int length = array->length();
708 for (int i = 0; i < length; i++) {
709 int offset = FixedArray::kHeaderSize + i * kPointerSize;
710 ASSERT(!Page::IsRSetSet(obj->address(), offset));
711 if (Heap::InNewSpace(array->get(i))) {
712 Page::SetRSet(obj->address(), offset);
713 }
714 }
715 } else if (!obj->IsCode()) {
716 // Skip code object, we know it does not contain inter-generational
717 // pointers.
718 UpdateRSetVisitor v;
719 obj->Iterate(&v);
720 }
721 return obj->Size();
722}
723
724
725void Heap::RebuildRSets() {
726 // By definition, we do not care about remembered set bits in code space.
727 map_space_->ClearRSet();
728 RebuildRSets(map_space_);
729
730 old_space_->ClearRSet();
731 RebuildRSets(old_space_);
732
733 Heap::lo_space_->ClearRSet();
734 RebuildRSets(lo_space_);
735}
736
737
738void Heap::RebuildRSets(PagedSpace* space) {
739 HeapObjectIterator it(space);
740 while (it.has_next()) Heap::UpdateRSet(it.next());
741}
742
743
744void Heap::RebuildRSets(LargeObjectSpace* space) {
745 LargeObjectIterator it(space);
746 while (it.has_next()) Heap::UpdateRSet(it.next());
747}
748
749
750#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
751void Heap::RecordCopiedObject(HeapObject* obj) {
752 bool should_record = false;
753#ifdef DEBUG
754 should_record = FLAG_heap_stats;
755#endif
756#ifdef ENABLE_LOGGING_AND_PROFILING
757 should_record = should_record || FLAG_log_gc;
758#endif
759 if (should_record) {
760 if (new_space_->Contains(obj)) {
761 new_space_->RecordAllocation(obj);
762 } else {
763 new_space_->RecordPromotion(obj);
764 }
765 }
766}
767#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
768
769
770HeapObject* Heap::MigrateObject(HeapObject** source_p,
771 HeapObject* target,
772 int size) {
773 void** src = reinterpret_cast<void**>((*source_p)->address());
774 void** dst = reinterpret_cast<void**>(target->address());
775 int counter = size/kPointerSize - 1;
776 do {
777 *dst++ = *src++;
778 } while (counter-- > 0);
779
780 // Set forwarding pointers, cannot use Map::cast because it asserts
781 // the value type to be Map.
782 (*source_p)->set_map(reinterpret_cast<Map*>(target));
783
784 // Update NewSpace stats if necessary.
785#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
786 RecordCopiedObject(target);
787#endif
788
789 return target;
790}
791
792
793void Heap::CopyObject(HeapObject** p) {
794 ASSERT(InFromSpace(*p));
795
796 HeapObject* object = *p;
797
798 // We use the first word (where the map pointer usually is) of a
799 // HeapObject to record the forwarding pointer. A forwarding pointer can
800 // point to the old space, the code space, or the to space of the new
801 // generation.
802 HeapObject* first_word = object->map();
803
804 // If the first word (where the map pointer is) is not a map pointer, the
805 // object has already been copied. We do not use first_word->IsMap()
806 // because we know that first_word always has the heap object tag.
807 if (first_word->map()->instance_type() != MAP_TYPE) {
808 *p = first_word;
809 return;
810 }
811
812 // Optimization: Bypass ConsString objects where the right-hand side is
813 // Heap::empty_string(). We do not use object->IsConsString because we
814 // already know that object has the heap object tag.
815 InstanceType type = Map::cast(first_word)->instance_type();
816 if (type < FIRST_NONSTRING_TYPE &&
817 String::cast(object)->representation_tag() == kConsStringTag &&
818 ConsString::cast(object)->second() == Heap::empty_string()) {
819 object = HeapObject::cast(ConsString::cast(object)->first());
820 *p = object;
821 // After patching *p we have to repeat the checks that object is in the
822 // active semispace of the young generation and not already copied.
823 if (!InFromSpace(object)) return;
824 first_word = object->map();
825 if (first_word->map()->instance_type() != MAP_TYPE) {
826 *p = first_word;
827 return;
828 }
829 type = Map::cast(first_word)->instance_type();
830 }
831
832 int object_size = object->SizeFromMap(Map::cast(first_word));
833 Object* result;
834 // If the object should be promoted, we try to copy it to old space.
835 if (ShouldBePromoted(object->address(), object_size)) {
836 // Heap numbers and sequential strings are promoted to code space, all
837 // other object types are promoted to old space. We do not use
838 // object->IsHeapNumber() and object->IsSeqString() because we already
839 // know that object has the heap object tag.
840 bool has_pointers =
841 type != HEAP_NUMBER_TYPE &&
842 (type >= FIRST_NONSTRING_TYPE ||
843 String::cast(object)->representation_tag() != kSeqStringTag);
844 if (has_pointers) {
845 result = old_space_->AllocateRaw(object_size);
846 } else {
847 result = code_space_->AllocateRaw(object_size);
848 }
849
850 if (!result->IsFailure()) {
851 *p = MigrateObject(p, HeapObject::cast(result), object_size);
852 if (has_pointers) {
853 // Record the object's address at the top of the to space, to allow
854 // it to be swept by the scavenger.
855 promoted_top -= kPointerSize;
856 Memory::Object_at(promoted_top) = *p;
857 } else {
858#ifdef DEBUG
859 // Objects promoted to the code space should not have pointers to
860 // new space.
861 VerifyCodeSpacePointersVisitor v;
862 (*p)->Iterate(&v);
863#endif
864 }
865 return;
866 }
867 }
868
869 // The object should remain in new space or the old space allocation failed.
870 result = new_space_->AllocateRaw(object_size);
871 // Failed allocation at this point is utterly unexpected.
872 ASSERT(!result->IsFailure());
873 *p = MigrateObject(p, HeapObject::cast(result), object_size);
874}
875
876
877Object* Heap::AllocatePartialMap(InstanceType instance_type,
878 int instance_size) {
879 Object* result = AllocateRawMap(Map::kSize);
880 if (result->IsFailure()) return result;
881
882 // Map::cast cannot be used due to uninitialized map field.
883 reinterpret_cast<Map*>(result)->set_map(meta_map());
884 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
885 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
886 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
887 return result;
888}
889
890
891Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
892 Object* result = AllocateRawMap(Map::kSize);
893 if (result->IsFailure()) return result;
894
895 Map* map = reinterpret_cast<Map*>(result);
896 map->set_map(meta_map());
897 map->set_instance_type(instance_type);
898 map->set_prototype(null_value());
899 map->set_constructor(null_value());
900 map->set_instance_size(instance_size);
901 map->set_instance_descriptors(DescriptorArray::cast(empty_fixed_array()));
902 map->set_code_cache(empty_fixed_array());
903 map->set_unused_property_fields(0);
904 map->set_bit_field(0);
905 return map;
906}
907
908
909bool Heap::CreateInitialMaps() {
910 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
911 if (obj->IsFailure()) return false;
912
913 // Map::cast cannot be used due to uninitialized map field.
914 meta_map_ = reinterpret_cast<Map*>(obj);
915 meta_map()->set_map(meta_map());
916
917 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
918 if (obj->IsFailure()) return false;
919 fixed_array_map_ = Map::cast(obj);
920
921 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
922 if (obj->IsFailure()) return false;
923 oddball_map_ = Map::cast(obj);
924
925 // Allocate the empty array
926 obj = AllocateEmptyFixedArray();
927 if (obj->IsFailure()) return false;
928 empty_fixed_array_ = FixedArray::cast(obj);
929
930 obj = Allocate(oddball_map(), CODE_SPACE);
931 if (obj->IsFailure()) return false;
932 null_value_ = obj;
933
934 // Fix the instance_descriptors for the existing maps.
935 DescriptorArray* empty_descriptors =
936 DescriptorArray::cast(empty_fixed_array());
937
938 meta_map()->set_instance_descriptors(empty_descriptors);
939 meta_map()->set_code_cache(empty_fixed_array());
940
941 fixed_array_map()->set_instance_descriptors(empty_descriptors);
942 fixed_array_map()->set_code_cache(empty_fixed_array());
943
944 oddball_map()->set_instance_descriptors(empty_descriptors);
945 oddball_map()->set_code_cache(empty_fixed_array());
946
947 // Fix prototype object for existing maps.
948 meta_map()->set_prototype(null_value());
949 meta_map()->set_constructor(null_value());
950
951 fixed_array_map()->set_prototype(null_value());
952 fixed_array_map()->set_constructor(null_value());
953 oddball_map()->set_prototype(null_value());
954 oddball_map()->set_constructor(null_value());
955
956 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
957 if (obj->IsFailure()) return false;
958 heap_number_map_ = Map::cast(obj);
959
960 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
961 if (obj->IsFailure()) return false;
962 proxy_map_ = Map::cast(obj);
963
964#define ALLOCATE_STRING_MAP(type, size, name) \
965 obj = AllocateMap(type, size); \
966 if (obj->IsFailure()) return false; \
967 name##_map_ = Map::cast(obj);
968 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
969#undef ALLOCATE_STRING_MAP
970
971 obj = AllocateMap(SHORT_STRING_TYPE, TwoByteString::kHeaderSize);
972 if (obj->IsFailure()) return false;
973 undetectable_short_string_map_ = Map::cast(obj);
974 undetectable_short_string_map_->set_is_undetectable();
975
976 obj = AllocateMap(MEDIUM_STRING_TYPE, TwoByteString::kHeaderSize);
977 if (obj->IsFailure()) return false;
978 undetectable_medium_string_map_ = Map::cast(obj);
979 undetectable_medium_string_map_->set_is_undetectable();
980
981 obj = AllocateMap(LONG_STRING_TYPE, TwoByteString::kHeaderSize);
982 if (obj->IsFailure()) return false;
983 undetectable_long_string_map_ = Map::cast(obj);
984 undetectable_long_string_map_->set_is_undetectable();
985
986 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
987 if (obj->IsFailure()) return false;
988 undetectable_short_ascii_string_map_ = Map::cast(obj);
989 undetectable_short_ascii_string_map_->set_is_undetectable();
990
991 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
992 if (obj->IsFailure()) return false;
993 undetectable_medium_ascii_string_map_ = Map::cast(obj);
994 undetectable_medium_ascii_string_map_->set_is_undetectable();
995
996 obj = AllocateMap(LONG_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
997 if (obj->IsFailure()) return false;
998 undetectable_long_ascii_string_map_ = Map::cast(obj);
999 undetectable_long_ascii_string_map_->set_is_undetectable();
1000
1001 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
1002 if (obj->IsFailure()) return false;
1003 byte_array_map_ = Map::cast(obj);
1004
1005 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1006 if (obj->IsFailure()) return false;
1007 code_map_ = Map::cast(obj);
1008
1009 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1010 if (obj->IsFailure()) return false;
1011 one_word_filler_map_ = Map::cast(obj);
1012
1013 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1014 if (obj->IsFailure()) return false;
1015 two_word_filler_map_ = Map::cast(obj);
1016
1017#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1018 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1019 if (obj->IsFailure()) return false; \
1020 name##_map_ = Map::cast(obj);
1021 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1022#undef ALLOCATE_STRUCT_MAP
1023
1024 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
1025 if (obj->IsFailure()) return false;
1026 hash_table_map_ = Map::cast(obj);
1027
1028 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
1029 if (obj->IsFailure()) return false;
1030 context_map_ = Map::cast(obj);
1031
1032 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
1033 if (obj->IsFailure()) return false;
1034 global_context_map_ = Map::cast(obj);
1035
1036 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1037 if (obj->IsFailure()) return false;
1038 boilerplate_function_map_ = Map::cast(obj);
1039
1040 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1041 if (obj->IsFailure()) return false;
1042 shared_function_info_map_ = Map::cast(obj);
1043
1044 return true;
1045}
1046
1047
1048Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1049 // Statically ensure that it is safe to allocate heap numbers in paged
1050 // spaces.
1051 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1052 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
1053 Object* result = AllocateRaw(HeapNumber::kSize, space);
1054 if (result->IsFailure()) return result;
1055
1056 HeapObject::cast(result)->set_map(heap_number_map());
1057 HeapNumber::cast(result)->set_value(value);
1058 return result;
1059}
1060
1061
1062Object* Heap::AllocateHeapNumber(double value) {
1063 // This version of AllocateHeapNumber is optimized for
1064 // allocation in new space.
1065 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1066 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1067 Object* result = new_space_->AllocateRaw(HeapNumber::kSize);
1068 if (result->IsFailure()) return result;
1069 HeapObject::cast(result)->set_map(heap_number_map());
1070 HeapNumber::cast(result)->set_value(value);
1071 return result;
1072}
1073
1074
1075Object* Heap::CreateOddball(Map* map,
1076 const char* to_string,
1077 Object* to_number) {
1078 Object* result = Allocate(map, CODE_SPACE);
1079 if (result->IsFailure()) return result;
1080 return Oddball::cast(result)->Initialize(to_string, to_number);
1081}
1082
1083
1084bool Heap::CreateApiObjects() {
1085 Object* obj;
1086
1087 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1088 if (obj->IsFailure()) return false;
1089 neander_map_ = Map::cast(obj);
1090
1091 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1092 if (obj->IsFailure()) return false;
1093 Object* elements = AllocateFixedArray(2);
1094 if (elements->IsFailure()) return false;
1095 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1096 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1097 message_listeners_ = JSObject::cast(obj);
1098
1099 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1100 if (obj->IsFailure()) return false;
1101 elements = AllocateFixedArray(2);
1102 if (elements->IsFailure()) return false;
1103 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1104 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1105 debug_event_listeners_ = JSObject::cast(obj);
1106
1107 return true;
1108}
1109
1110void Heap::CreateFixedStubs() {
1111 // Here we create roots for fixed stubs. They are needed at GC
1112 // for cooking and uncooking (check out frames.cc).
1113 // The eliminates the need for doing dictionary lookup in the
1114 // stub cache for these stubs.
1115 HandleScope scope;
1116 {
1117 CEntryStub stub;
1118 c_entry_code_ = *stub.GetCode();
1119 }
1120 {
1121 CEntryDebugBreakStub stub;
1122 c_entry_debug_break_code_ = *stub.GetCode();
1123 }
1124 {
1125 JSEntryStub stub;
1126 js_entry_code_ = *stub.GetCode();
1127 }
1128 {
1129 JSConstructEntryStub stub;
1130 js_construct_entry_code_ = *stub.GetCode();
1131 }
1132}
1133
1134
1135bool Heap::CreateInitialObjects() {
1136 Object* obj;
1137
1138 // The -0 value must be set before NumberFromDouble works.
1139 obj = AllocateHeapNumber(-0.0, TENURED);
1140 if (obj->IsFailure()) return false;
1141 minus_zero_value_ = obj;
1142 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1143
1144 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1145 if (obj->IsFailure()) return false;
1146 nan_value_ = obj;
1147
1148 obj = NumberFromDouble(INFINITY, TENURED);
1149 if (obj->IsFailure()) return false;
1150 infinity_value_ = obj;
1151
1152 obj = NumberFromDouble(-INFINITY, TENURED);
1153 if (obj->IsFailure()) return false;
1154 negative_infinity_value_ = obj;
1155
1156 obj = NumberFromDouble(DBL_MAX, TENURED);
1157 if (obj->IsFailure()) return false;
1158 number_max_value_ = obj;
1159
1160 // C++ doesn't provide a constant for the smallest denormalized
1161 // double (approx. 5e-324) but only the smallest normalized one
1162 // which is somewhat bigger (approx. 2e-308). So we have to do
1163 // this raw conversion hack.
1164 uint64_t min_value_bits = 1L;
1165 double min_value = *reinterpret_cast<double*>(&min_value_bits);
1166 obj = NumberFromDouble(min_value, TENURED);
1167 if (obj->IsFailure()) return false;
1168 number_min_value_ = obj;
1169
1170 obj = Allocate(oddball_map(), CODE_SPACE);
1171 if (obj->IsFailure()) return false;
1172 undefined_value_ = obj;
1173 ASSERT(!InNewSpace(undefined_value()));
1174
1175 // Allocate initial symbol table.
1176 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1177 if (obj->IsFailure()) return false;
1178 symbol_table_ = obj;
1179
1180 // Assign the print strings for oddballs after creating symboltable.
1181 Object* symbol = LookupAsciiSymbol("undefined");
1182 if (symbol->IsFailure()) return false;
1183 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1184 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1185
1186 // Assign the print strings for oddballs after creating symboltable.
1187 symbol = LookupAsciiSymbol("null");
1188 if (symbol->IsFailure()) return false;
1189 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1190 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1191
1192 // Allocate the null_value
1193 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1194 if (obj->IsFailure()) return false;
1195
1196 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1197 if (obj->IsFailure()) return false;
1198 true_value_ = obj;
1199
1200 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1201 if (obj->IsFailure()) return false;
1202 false_value_ = obj;
1203
1204 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1205 if (obj->IsFailure()) return false;
1206 the_hole_value_ = obj;
1207
1208 // Allocate the empty string.
1209 obj = AllocateRawAsciiString(0, TENURED);
1210 if (obj->IsFailure()) return false;
1211 empty_string_ = String::cast(obj);
1212
1213#define SYMBOL_INITIALIZE(name, string) \
1214 obj = LookupAsciiSymbol(string); \
1215 if (obj->IsFailure()) return false; \
1216 (name##_) = String::cast(obj);
1217 SYMBOL_LIST(SYMBOL_INITIALIZE)
1218#undef SYMBOL_INITIALIZE
1219
1220 // Allocate the proxy for __proto__.
1221 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1222 if (obj->IsFailure()) return false;
1223 prototype_accessors_ = Proxy::cast(obj);
1224
1225 // Allocate the code_stubs dictionary.
1226 obj = Dictionary::Allocate(4);
1227 if (obj->IsFailure()) return false;
1228 code_stubs_ = Dictionary::cast(obj);
1229
1230 // Allocate the non_monomorphic_cache used in stub-cache.cc
1231 obj = Dictionary::Allocate(4);
1232 if (obj->IsFailure()) return false;
1233 non_monomorphic_cache_ = Dictionary::cast(obj);
1234
1235 CreateFixedStubs();
1236
1237 // Allocate the number->string conversion cache
1238 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1239 if (obj->IsFailure()) return false;
1240 number_string_cache_ = FixedArray::cast(obj);
1241
1242 // Allocate cache for single character strings.
1243 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1244 if (obj->IsFailure()) return false;
1245 single_character_string_cache_ = FixedArray::cast(obj);
1246
1247 // Allocate cache for external strings pointing to native source code.
1248 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1249 if (obj->IsFailure()) return false;
1250 natives_source_cache_ = FixedArray::cast(obj);
1251
1252 return true;
1253}
1254
1255
1256static inline int double_get_hash(double d) {
1257 DoubleRepresentation rep(d);
1258 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1259 (Heap::kNumberStringCacheSize - 1));
1260}
1261
1262
1263static inline int smi_get_hash(Smi* smi) {
1264 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1265}
1266
1267
1268
1269Object* Heap::GetNumberStringCache(Object* number) {
1270 int hash;
1271 if (number->IsSmi()) {
1272 hash = smi_get_hash(Smi::cast(number));
1273 } else {
1274 hash = double_get_hash(number->Number());
1275 }
1276 Object* key = number_string_cache_->get(hash * 2);
1277 if (key == number) {
1278 return String::cast(number_string_cache_->get(hash * 2 + 1));
1279 } else if (key->IsHeapNumber() &&
1280 number->IsHeapNumber() &&
1281 key->Number() == number->Number()) {
1282 return String::cast(number_string_cache_->get(hash * 2 + 1));
1283 }
1284 return undefined_value();
1285}
1286
1287
1288void Heap::SetNumberStringCache(Object* number, String* string) {
1289 int hash;
1290 if (number->IsSmi()) {
1291 hash = smi_get_hash(Smi::cast(number));
1292 number_string_cache_->set(hash * 2, number, FixedArray::SKIP_WRITE_BARRIER);
1293 } else {
1294 hash = double_get_hash(number->Number());
1295 number_string_cache_->set(hash * 2, number);
1296 }
1297 number_string_cache_->set(hash * 2 + 1, string);
1298}
1299
1300
1301Object* Heap::SmiOrNumberFromDouble(double value,
1302 bool new_object,
1303 PretenureFlag pretenure) {
1304 // We need to distinguish the minus zero value and this cannot be
1305 // done after conversion to int. Doing this by comparing bit
1306 // patterns is faster than using fpclassify() et al.
1307 static const DoubleRepresentation plus_zero(0.0);
1308 static const DoubleRepresentation minus_zero(-0.0);
1309 static const DoubleRepresentation nan(OS::nan_value());
1310 ASSERT(minus_zero_value_ != NULL);
1311 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1312
1313 DoubleRepresentation rep(value);
1314 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1315 if (rep.bits == minus_zero.bits) {
1316 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1317 : minus_zero_value_;
1318 }
1319 if (rep.bits == nan.bits) {
1320 return new_object
1321 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1322 : nan_value_;
1323 }
1324
1325 // Try to represent the value as a tagged small integer.
1326 int int_value = FastD2I(value);
1327 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1328 return Smi::FromInt(int_value);
1329 }
1330
1331 // Materialize the value in the heap.
1332 return AllocateHeapNumber(value, pretenure);
1333}
1334
1335
1336Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1337 return SmiOrNumberFromDouble(value,
1338 true /* number object must be new */,
1339 pretenure);
1340}
1341
1342
1343Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1344 return SmiOrNumberFromDouble(value,
1345 false /* use preallocated NaN, -0.0 */,
1346 pretenure);
1347}
1348
1349
1350Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1351 // Statically ensure that it is safe to allocate proxies in paged spaces.
1352 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
1353 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1354 Object* result = Allocate(proxy_map(), space);
1355 if (result->IsFailure()) return result;
1356
1357 Proxy::cast(result)->set_proxy(proxy);
1358 return result;
1359}
1360
1361
1362Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1363 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1364 if (result->IsFailure()) return result;
1365
1366 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1367 share->set_name(name);
1368 Code* illegal = Builtins::builtin(Builtins::Illegal);
1369 share->set_code(illegal);
1370 share->set_expected_nof_properties(0);
1371 share->set_length(0);
1372 share->set_formal_parameter_count(0);
1373 share->set_instance_class_name(Object_symbol());
1374 share->set_function_data(undefined_value());
1375 share->set_lazy_load_data(undefined_value());
1376 share->set_script(undefined_value());
1377 share->set_start_position_and_type(0);
1378 share->set_debug_info(undefined_value());
1379 return result;
1380}
1381
1382
1383Object* Heap::AllocateConsString(String* first, String* second) {
1384 int length = first->length() + second->length();
1385 bool is_ascii = first->is_ascii() && second->is_ascii();
1386
1387 // If the resulting string is small make a flat string.
1388 if (length < ConsString::kMinLength) {
1389 Object* result = is_ascii
1390 ? AllocateRawAsciiString(length)
1391 : AllocateRawTwoByteString(length);
1392 if (result->IsFailure()) return result;
1393 // Copy the characters into the new object.
1394 String* string_result = String::cast(result);
1395 int first_length = first->length();
1396 // Copy the content of the first string.
1397 for (int i = 0; i < first_length; i++) {
1398 string_result->Set(i, first->Get(i));
1399 }
1400 int second_length = second->length();
1401 // Copy the content of the first string.
1402 for (int i = 0; i < second_length; i++) {
1403 string_result->Set(first_length + i, second->Get(i));
1404 }
1405 return result;
1406 }
1407
1408 Map* map;
1409 if (length <= String::kMaxShortStringSize) {
1410 map = is_ascii ? short_cons_ascii_string_map()
1411 : short_cons_string_map();
1412 } else if (length <= String::kMaxMediumStringSize) {
1413 map = is_ascii ? medium_cons_ascii_string_map()
1414 : medium_cons_string_map();
1415 } else {
1416 map = is_ascii ? long_cons_ascii_string_map()
1417 : long_cons_string_map();
1418 }
1419
1420 Object* result = Allocate(map, NEW_SPACE);
1421 if (result->IsFailure()) return result;
1422
1423 ConsString* cons_string = ConsString::cast(result);
1424 cons_string->set_first(first);
1425 cons_string->set_second(second);
1426 cons_string->set_length(length);
1427
1428 return result;
1429}
1430
1431
1432Object* Heap::AllocateSlicedString(String* buffer, int start, int end) {
1433 int length = end - start;
1434
1435 // If the resulting string is small make a sub string.
1436 if (end - start <= SlicedString::kMinLength) {
1437 return Heap::AllocateSubString(buffer, start, end);
1438 }
1439
1440 Map* map;
1441 if (length <= String::kMaxShortStringSize) {
1442 map = buffer->is_ascii() ? short_sliced_ascii_string_map()
1443 : short_sliced_string_map();
1444 } else if (length <= String::kMaxMediumStringSize) {
1445 map = buffer->is_ascii() ? medium_sliced_ascii_string_map()
1446 : medium_sliced_string_map();
1447 } else {
1448 map = buffer->is_ascii() ? long_sliced_ascii_string_map()
1449 : long_sliced_string_map();
1450 }
1451
1452 Object* result = Allocate(map, NEW_SPACE);
1453 if (result->IsFailure()) return result;
1454
1455 SlicedString* sliced_string = SlicedString::cast(result);
1456 sliced_string->set_buffer(buffer);
1457 sliced_string->set_start(start);
1458 sliced_string->set_length(length);
1459
1460 return result;
1461}
1462
1463
1464Object* Heap::AllocateSubString(String* buffer, int start, int end) {
1465 int length = end - start;
1466
1467 // Make an attempt to flatten the buffer to reduce access time.
1468 buffer->TryFlatten();
1469
1470 Object* result = buffer->is_ascii()
1471 ? AllocateRawAsciiString(length)
1472 : AllocateRawTwoByteString(length);
1473 if (result->IsFailure()) return result;
1474
1475 // Copy the characters into the new object.
1476 String* string_result = String::cast(result);
1477 for (int i = 0; i < length; i++) {
1478 string_result->Set(i, buffer->Get(start + i));
1479 }
1480 return result;
1481}
1482
1483
1484Object* Heap::AllocateExternalStringFromAscii(
1485 ExternalAsciiString::Resource* resource) {
1486 Map* map;
1487 int length = resource->length();
1488 if (length <= String::kMaxShortStringSize) {
1489 map = short_external_ascii_string_map();
1490 } else if (length <= String::kMaxMediumStringSize) {
1491 map = medium_external_ascii_string_map();
1492 } else {
1493 map = long_external_ascii_string_map();
1494 }
1495
1496 Object* result = Allocate(map, NEW_SPACE);
1497 if (result->IsFailure()) return result;
1498
1499 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1500 external_string->set_length(length);
1501 external_string->set_resource(resource);
1502
1503 return result;
1504}
1505
1506
1507Object* Heap::AllocateExternalStringFromTwoByte(
1508 ExternalTwoByteString::Resource* resource) {
1509 Map* map;
1510 int length = resource->length();
1511 if (length <= String::kMaxShortStringSize) {
1512 map = short_external_string_map();
1513 } else if (length <= String::kMaxMediumStringSize) {
1514 map = medium_external_string_map();
1515 } else {
1516 map = long_external_string_map();
1517 }
1518
1519 Object* result = Allocate(map, NEW_SPACE);
1520 if (result->IsFailure()) return result;
1521
1522 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1523 external_string->set_length(length);
1524 external_string->set_resource(resource);
1525
1526 return result;
1527}
1528
1529
1530Object* Heap:: LookupSingleCharacterStringFromCode(uint16_t code) {
1531 if (code <= String::kMaxAsciiCharCode) {
1532 Object* value = Heap::single_character_string_cache()->get(code);
1533 if (value != Heap::undefined_value()) return value;
1534 Object* result = Heap::AllocateRawAsciiString(1);
1535 if (result->IsFailure()) return result;
1536 String::cast(result)->Set(0, code);
1537 Heap::single_character_string_cache()->set(code, result);
1538 return result;
1539 }
1540 Object* result = Heap::AllocateRawTwoByteString(1);
1541 if (result->IsFailure()) return result;
1542 String::cast(result)->Set(0, code);
1543 return result;
1544}
1545
1546
1547Object* Heap::AllocateByteArray(int length) {
1548 int size = ByteArray::SizeFor(length);
1549 AllocationSpace space = size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
1550
1551 Object* result = AllocateRaw(size, space);
1552 if (result->IsFailure()) return result;
1553
1554 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1555 reinterpret_cast<Array*>(result)->set_length(length);
1556 return result;
1557}
1558
1559
1560Object* Heap::CreateCode(const CodeDesc& desc,
1561 ScopeInfo<>* sinfo,
1562 Code::Flags flags) {
1563 // Compute size
1564 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1565 int sinfo_size = 0;
1566 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1567 int obj_size = Code::SizeFor(body_size, sinfo_size);
1568 AllocationSpace space =
1569 (obj_size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1570
1571 Object* result = AllocateRaw(obj_size, space);
1572 if (result->IsFailure()) return result;
1573
1574 // Initialize the object
1575 HeapObject::cast(result)->set_map(code_map());
1576 Code* code = Code::cast(result);
1577 code->set_instruction_size(desc.instr_size);
1578 code->set_relocation_size(desc.reloc_size);
1579 code->set_sinfo_size(sinfo_size);
1580 code->set_flags(flags);
1581 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
1582 code->CopyFrom(desc); // migrate generated code
1583 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1584
1585#ifdef DEBUG
1586 code->Verify();
1587#endif
1588
1589 CPU::FlushICache(code->instruction_start(), code->instruction_size());
1590
1591 return code;
1592}
1593
1594
1595Object* Heap::CopyCode(Code* code) {
1596 // Allocate an object the same size as the code object.
1597 int obj_size = code->Size();
1598 AllocationSpace space =
1599 (obj_size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1600 Object* result = AllocateRaw(obj_size, space);
1601 if (result->IsFailure()) return result;
1602
1603 // Copy code object.
1604 Address old_addr = code->address();
1605 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
1606 memcpy(new_addr, old_addr, obj_size);
1607
1608 // Relocate the copy.
1609 Code* new_code = Code::cast(result);
1610 new_code->Relocate(new_addr - old_addr);
1611
1612 CPU::FlushICache(new_code->instruction_start(), new_code->instruction_size());
1613
1614 return new_code;
1615}
1616
1617
1618Object* Heap::Allocate(Map* map, AllocationSpace space) {
1619 ASSERT(gc_state_ == NOT_IN_GC);
1620 ASSERT(map->instance_type() != MAP_TYPE);
1621 Object* result = AllocateRaw(map->instance_size(), space);
1622 if (result->IsFailure()) return result;
1623 HeapObject::cast(result)->set_map(map);
1624 return result;
1625}
1626
1627
1628Object* Heap::InitializeFunction(JSFunction* function,
1629 SharedFunctionInfo* shared,
1630 Object* prototype) {
1631 ASSERT(!prototype->IsMap());
1632 function->initialize_properties();
1633 function->initialize_elements();
1634 function->set_shared(shared);
1635 function->set_prototype_or_initial_map(prototype);
1636 function->set_context(undefined_value());
1637 function->set_literals(empty_fixed_array());
1638 return function;
1639}
1640
1641
1642Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1643 // Allocate the prototype.
1644 Object* prototype =
1645 AllocateJSObject(Top::context()->global_context()->object_function());
1646 if (prototype->IsFailure()) return prototype;
1647 // When creating the prototype for the function we must set its
1648 // constructor to the function.
1649 Object* result =
1650 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1651 function,
1652 DONT_ENUM);
1653 if (result->IsFailure()) return result;
1654 return prototype;
1655}
1656
1657
1658Object* Heap::AllocateFunction(Map* function_map,
1659 SharedFunctionInfo* shared,
1660 Object* prototype) {
1661 Object* result = Allocate(function_map, OLD_SPACE);
1662 if (result->IsFailure()) return result;
1663 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1664}
1665
1666
1667Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
1668 // This allocation is odd since allocate an argument object
1669 // based on the arguments_boilerplate.
1670 // We do this to ensure fast allocation and map sharing.
1671
1672 // This calls Copy directly rather than using Heap::AllocateRaw so we
1673 // duplicate the check here.
1674 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1675
1676 JSObject* boilerplate =
1677 Top::context()->global_context()->arguments_boilerplate();
1678 Object* result = boilerplate->Copy();
1679 if (result->IsFailure()) return result;
1680
1681 Object* obj = JSObject::cast(result)->properties();
1682 FixedArray::cast(obj)->set(arguments_callee_index, callee);
1683 FixedArray::cast(obj)->set(arguments_length_index, Smi::FromInt(length));
1684
1685 // Allocate the fixed array.
1686 obj = Heap::AllocateFixedArray(length);
1687 if (obj->IsFailure()) return obj;
1688 JSObject::cast(result)->set_elements(FixedArray::cast(obj));
1689
1690 // Check the state of the object
1691 ASSERT(JSObject::cast(result)->HasFastProperties());
1692 ASSERT(JSObject::cast(result)->HasFastElements());
1693
1694 return result;
1695}
1696
1697
1698Object* Heap::AllocateInitialMap(JSFunction* fun) {
1699 ASSERT(!fun->has_initial_map());
1700
1701 // First create a new map.
1702 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1703 if (map_obj->IsFailure()) return map_obj;
1704
1705 // Fetch or allocate prototype.
1706 Object* prototype;
1707 if (fun->has_instance_prototype()) {
1708 prototype = fun->instance_prototype();
1709 } else {
1710 prototype = AllocateFunctionPrototype(fun);
1711 if (prototype->IsFailure()) return prototype;
1712 }
1713 Map* map = Map::cast(map_obj);
1714 map->set_unused_property_fields(fun->shared()->expected_nof_properties());
1715 map->set_prototype(prototype);
1716 return map;
1717}
1718
1719
1720void Heap::InitializeJSObjectFromMap(JSObject* obj,
1721 FixedArray* properties,
1722 Map* map) {
1723 obj->set_properties(properties);
1724 obj->initialize_elements();
1725 // TODO(1240798): Initialize the object's body using valid initial values
1726 // according to the object's initial map. For example, if the map's
1727 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1728 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1729 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1730 // verification code has to cope with (temporarily) invalid objects. See
1731 // for example, JSArray::JSArrayVerify).
1732 obj->InitializeBody(map->instance_size());
1733}
1734
1735
1736Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1737 // JSFunctions should be allocated using AllocateFunction to be
1738 // properly initialized.
1739 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1740
1741 // Allocate the backing storage for the properties.
1742 Object* properties = AllocatePropertyStorageForMap(map);
1743 if (properties->IsFailure()) return properties;
1744
1745 // Allocate the JSObject.
1746 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1747 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1748 Object* obj = Allocate(map, space);
1749 if (obj->IsFailure()) return obj;
1750
1751 // Initialize the JSObject.
1752 InitializeJSObjectFromMap(JSObject::cast(obj),
1753 FixedArray::cast(properties),
1754 map);
1755 return obj;
1756}
1757
1758
1759Object* Heap::AllocateJSObject(JSFunction* constructor,
1760 PretenureFlag pretenure) {
1761 // Allocate the initial map if absent.
1762 if (!constructor->has_initial_map()) {
1763 Object* initial_map = AllocateInitialMap(constructor);
1764 if (initial_map->IsFailure()) return initial_map;
1765 constructor->set_initial_map(Map::cast(initial_map));
1766 Map::cast(initial_map)->set_constructor(constructor);
1767 }
1768 // Allocate the object based on the constructors initial map.
1769 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1770}
1771
1772
1773Object* Heap::ReinitializeJSGlobalObject(JSFunction* constructor,
1774 JSGlobalObject* object) {
1775 // Allocate initial map if absent.
1776 if (!constructor->has_initial_map()) {
1777 Object* initial_map = AllocateInitialMap(constructor);
1778 if (initial_map->IsFailure()) return initial_map;
1779 constructor->set_initial_map(Map::cast(initial_map));
1780 Map::cast(initial_map)->set_constructor(constructor);
1781 }
1782
1783 Map* map = constructor->initial_map();
1784
1785 // Check that the already allocated object has the same size as
1786 // objects allocated using the constructor.
1787 ASSERT(map->instance_size() == object->map()->instance_size());
1788
1789 // Allocate the backing storage for the properties.
1790 Object* properties = AllocatePropertyStorageForMap(map);
1791 if (properties->IsFailure()) return properties;
1792
1793 // Reset the map for the object.
1794 object->set_map(constructor->initial_map());
1795
1796 // Reinitialize the object from the constructor map.
1797 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1798 return object;
1799}
1800
1801
1802Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1803 PretenureFlag pretenure) {
1804 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1805 if (result->IsFailure()) return result;
1806
1807 // Copy the characters into the new object.
1808 AsciiString* string_result = AsciiString::cast(result);
1809 for (int i = 0; i < string.length(); i++) {
1810 string_result->AsciiStringSet(i, string[i]);
1811 }
1812 return result;
1813}
1814
1815
1816Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1817 PretenureFlag pretenure) {
1818 // Count the number of characters in the UTF-8 string and check if
1819 // it is an ASCII string.
1820 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1821 decoder->Reset(string.start(), string.length());
1822 int chars = 0;
1823 bool is_ascii = true;
1824 while (decoder->has_more()) {
1825 uc32 r = decoder->GetNext();
1826 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1827 chars++;
1828 }
1829
1830 // If the string is ascii, we do not need to convert the characters
1831 // since UTF8 is backwards compatible with ascii.
1832 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1833
1834 Object* result = AllocateRawTwoByteString(chars, pretenure);
1835 if (result->IsFailure()) return result;
1836
1837 // Convert and copy the characters into the new object.
1838 String* string_result = String::cast(result);
1839 decoder->Reset(string.start(), string.length());
1840 for (int i = 0; i < chars; i++) {
1841 uc32 r = decoder->GetNext();
1842 string_result->Set(i, r);
1843 }
1844 return result;
1845}
1846
1847
1848Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1849 PretenureFlag pretenure) {
1850 // Check if the string is an ASCII string.
1851 int i = 0;
1852 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1853
1854 Object* result;
1855 if (i == string.length()) { // It's an ASCII string.
1856 result = AllocateRawAsciiString(string.length(), pretenure);
1857 } else { // It's not an ASCII string.
1858 result = AllocateRawTwoByteString(string.length(), pretenure);
1859 }
1860 if (result->IsFailure()) return result;
1861
1862 // Copy the characters into the new object, which may be either ASCII or
1863 // UTF-16.
1864 String* string_result = String::cast(result);
1865 for (int i = 0; i < string.length(); i++) {
1866 string_result->Set(i, string[i]);
1867 }
1868 return result;
1869}
1870
1871
1872Map* Heap::SymbolMapForString(String* string) {
1873 // If the string is in new space it cannot be used as a symbol.
1874 if (InNewSpace(string)) return NULL;
1875
1876 // Find the corresponding symbol map for strings.
1877 Map* map = string->map();
1878
1879 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
1880 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
1881 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
1882
1883 if (map == short_string_map()) return short_symbol_map();
1884 if (map == medium_string_map()) return medium_symbol_map();
1885 if (map == long_string_map()) return long_symbol_map();
1886
1887 if (map == short_cons_string_map()) return short_cons_symbol_map();
1888 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
1889 if (map == long_cons_string_map()) return long_cons_symbol_map();
1890
1891 if (map == short_cons_ascii_string_map()) {
1892 return short_cons_ascii_symbol_map();
1893 }
1894 if (map == medium_cons_ascii_string_map()) {
1895 return medium_cons_ascii_symbol_map();
1896 }
1897 if (map == long_cons_ascii_string_map()) {
1898 return long_cons_ascii_symbol_map();
1899 }
1900
1901 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
1902 if (map == medium_sliced_string_map()) return short_sliced_symbol_map();
1903 if (map == long_sliced_string_map()) return short_sliced_symbol_map();
1904
1905 if (map == short_sliced_ascii_string_map()) {
1906 return short_sliced_ascii_symbol_map();
1907 }
1908 if (map == medium_sliced_ascii_string_map()) {
1909 return short_sliced_ascii_symbol_map();
1910 }
1911 if (map == long_sliced_ascii_string_map()) {
1912 return short_sliced_ascii_symbol_map();
1913 }
1914
1915 if (map == short_external_string_map()) return short_external_string_map();
1916 if (map == medium_external_string_map()) return medium_external_string_map();
1917 if (map == long_external_string_map()) return long_external_string_map();
1918
1919 if (map == short_external_ascii_string_map()) {
1920 return short_external_ascii_string_map();
1921 }
1922 if (map == medium_external_ascii_string_map()) {
1923 return medium_external_ascii_string_map();
1924 }
1925 if (map == long_external_ascii_string_map()) {
1926 return long_external_ascii_string_map();
1927 }
1928
1929 // No match found.
1930 return NULL;
1931}
1932
1933
1934Object* Heap::AllocateSymbol(unibrow::CharacterStream* buffer,
1935 int chars,
1936 int hash) {
1937 // Ensure the chars matches the number of characters in the buffer.
1938 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
1939 // Determine whether the string is ascii.
1940 bool is_ascii = true;
1941 while (buffer->has_more()) {
1942 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
1943 }
1944 buffer->Rewind();
1945
1946 // Compute map and object size.
1947 int size;
1948 Map* map;
1949
1950 if (is_ascii) {
1951 if (chars <= String::kMaxShortStringSize) {
1952 map = short_ascii_symbol_map();
1953 } else if (chars <= String::kMaxMediumStringSize) {
1954 map = medium_ascii_symbol_map();
1955 } else {
1956 map = long_ascii_symbol_map();
1957 }
1958 size = AsciiString::SizeFor(chars);
1959 } else {
1960 if (chars <= String::kMaxShortStringSize) {
1961 map = short_symbol_map();
1962 } else if (chars <= String::kMaxMediumStringSize) {
1963 map = medium_symbol_map();
1964 } else {
1965 map = long_symbol_map();
1966 }
1967 size = TwoByteString::SizeFor(chars);
1968 }
1969
1970 // Allocate string.
1971 AllocationSpace space = (size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1972 Object* result = AllocateRaw(size, space);
1973 if (result->IsFailure()) return result;
1974
1975 reinterpret_cast<HeapObject*>(result)->set_map(map);
1976 // The hash value contains the length of the string.
1977 String::cast(result)->set_length_field(hash);
1978
1979 ASSERT_EQ(size, String::cast(result)->Size());
1980
1981 // Fill in the characters.
1982 for (int i = 0; i < chars; i++) {
1983 String::cast(result)->Set(i, buffer->GetNext());
1984 }
1985 return result;
1986}
1987
1988
1989Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
1990 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
1991 int size = AsciiString::SizeFor(length);
1992 if (size > MaxHeapObjectSize()) {
1993 space = LO_SPACE;
1994 }
1995
1996 // Use AllocateRaw rather than Allocate because the object's size cannot be
1997 // determined from the map.
1998 Object* result = AllocateRaw(size, space);
1999 if (result->IsFailure()) return result;
2000
2001 // Determine the map based on the string's length.
2002 Map* map;
2003 if (length <= String::kMaxShortStringSize) {
2004 map = short_ascii_string_map();
2005 } else if (length <= String::kMaxMediumStringSize) {
2006 map = medium_ascii_string_map();
2007 } else {
2008 map = long_ascii_string_map();
2009 }
2010
2011 // Partially initialize the object.
2012 HeapObject::cast(result)->set_map(map);
2013 String::cast(result)->set_length(length);
2014 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2015 return result;
2016}
2017
2018
2019Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
2020 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
2021 int size = TwoByteString::SizeFor(length);
2022 if (size > MaxHeapObjectSize()) {
2023 space = LO_SPACE;
2024 }
2025
2026 // Use AllocateRaw rather than Allocate because the object's size cannot be
2027 // determined from the map.
2028 Object* result = AllocateRaw(size, space);
2029 if (result->IsFailure()) return result;
2030
2031 // Determine the map based on the string's length.
2032 Map* map;
2033 if (length <= String::kMaxShortStringSize) {
2034 map = short_string_map();
2035 } else if (length <= String::kMaxMediumStringSize) {
2036 map = medium_string_map();
2037 } else {
2038 map = long_string_map();
2039 }
2040
2041 // Partially initialize the object.
2042 HeapObject::cast(result)->set_map(map);
2043 String::cast(result)->set_length(length);
2044 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2045 return result;
2046}
2047
2048
2049Object* Heap::AllocateEmptyFixedArray() {
2050 int size = FixedArray::SizeFor(0);
2051 Object* result = AllocateRaw(size, CODE_SPACE);
2052 if (result->IsFailure()) return result;
2053 // Initialize the object.
2054 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2055 reinterpret_cast<Array*>(result)->set_length(0);
2056 return result;
2057}
2058
2059
2060Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2061 ASSERT(empty_fixed_array()->IsFixedArray());
2062 if (length == 0) return empty_fixed_array();
2063
2064 int size = FixedArray::SizeFor(length);
2065 Object* result;
2066 if (size > MaxHeapObjectSize()) {
2067 result = lo_space_->AllocateRawFixedArray(size);
2068 } else {
2069 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
2070 result = AllocateRaw(size, space);
2071 }
2072 if (result->IsFailure()) return result;
2073
2074 // Initialize the object.
2075 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2076 FixedArray* array = FixedArray::cast(result);
2077 array->set_length(length);
2078 for (int index = 0; index < length; index++) array->set_undefined(index);
2079 return array;
2080}
2081
2082
2083Object* Heap::AllocateFixedArrayWithHoles(int length) {
2084 if (length == 0) return empty_fixed_array();
2085 int size = FixedArray::SizeFor(length);
2086 Object* result = size > MaxHeapObjectSize()
2087 ? lo_space_->AllocateRawFixedArray(size)
2088 : AllocateRaw(size, NEW_SPACE);
2089 if (result->IsFailure()) return result;
2090
2091 // Initialize the object.
2092 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2093 FixedArray* array = FixedArray::cast(result);
2094 array->set_length(length);
2095 for (int index = 0; index < length; index++) array->set_the_hole(index);
2096 return array;
2097}
2098
2099
2100Object* Heap::AllocateHashTable(int length) {
2101 Object* result = Heap::AllocateFixedArray(length);
2102 if (result->IsFailure()) return result;
2103 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2104 ASSERT(result->IsDictionary());
2105 return result;
2106}
2107
2108
2109Object* Heap::AllocateGlobalContext() {
2110 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2111 if (result->IsFailure()) return result;
2112 Context* context = reinterpret_cast<Context*>(result);
2113 context->set_map(global_context_map());
2114 ASSERT(context->IsGlobalContext());
2115 ASSERT(result->IsContext());
2116 return result;
2117}
2118
2119
2120Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2121 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2122 Object* result = Heap::AllocateFixedArray(length);
2123 if (result->IsFailure()) return result;
2124 Context* context = reinterpret_cast<Context*>(result);
2125 context->set_map(context_map());
2126 context->set_closure(function);
2127 context->set_fcontext(context);
2128 context->set_previous(NULL);
2129 context->set_extension(NULL);
2130 context->set_global(function->context()->global());
2131 ASSERT(!context->IsGlobalContext());
2132 ASSERT(context->is_function_context());
2133 ASSERT(result->IsContext());
2134 return result;
2135}
2136
2137
2138Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2139 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2140 if (result->IsFailure()) return result;
2141 Context* context = reinterpret_cast<Context*>(result);
2142 context->set_map(context_map());
2143 context->set_closure(previous->closure());
2144 context->set_fcontext(previous->fcontext());
2145 context->set_previous(previous);
2146 context->set_extension(extension);
2147 context->set_global(previous->global());
2148 ASSERT(!context->IsGlobalContext());
2149 ASSERT(!context->is_function_context());
2150 ASSERT(result->IsContext());
2151 return result;
2152}
2153
2154
2155Object* Heap::AllocateStruct(InstanceType type) {
2156 Map* map;
2157 switch (type) {
2158#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2159STRUCT_LIST(MAKE_CASE)
2160#undef MAKE_CASE
2161 default:
2162 UNREACHABLE();
2163 return Failure::InternalError();
2164 }
2165 int size = map->instance_size();
2166 AllocationSpace space =
2167 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_SPACE;
2168 Object* result = Heap::Allocate(map, space);
2169 if (result->IsFailure()) return result;
2170 Struct::cast(result)->InitializeBody(size);
2171 return result;
2172}
2173
2174
2175#ifdef DEBUG
2176
2177void Heap::Print() {
2178 if (!HasBeenSetup()) return;
2179 Top::PrintStack();
2180 new_space_->Print();
2181 old_space_->Print();
2182 code_space_->Print();
2183 map_space_->Print();
2184 lo_space_->Print();
2185}
2186
2187
2188void Heap::ReportCodeStatistics(const char* title) {
2189 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2190 PagedSpace::ResetCodeStatistics();
2191 // We do not look for code in new space, map space, or old space. If code
2192 // somehow ends up in those spaces, we would miss it here.
2193 code_space_->CollectCodeStatistics();
2194 lo_space_->CollectCodeStatistics();
2195 PagedSpace::ReportCodeStatistics();
2196}
2197
2198
2199// This function expects that NewSpace's allocated objects histogram is
2200// populated (via a call to CollectStatistics or else as a side effect of a
2201// just-completed scavenge collection).
2202void Heap::ReportHeapStatistics(const char* title) {
2203 USE(title);
2204 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2205 title, gc_count_);
2206 PrintF("mark-compact GC : %d\n", mc_count_);
2207 PrintF("promoted_space_limit_ %d\n", promoted_space_limit_);
2208
2209 PrintF("\n");
2210 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2211 GlobalHandles::PrintStats();
2212 PrintF("\n");
2213
2214 PrintF("Heap statistics : ");
2215 MemoryAllocator::ReportStatistics();
2216 PrintF("To space : ");
2217 new_space_->ReportStatistics();
2218 PrintF("Old space : ");
2219 old_space_->ReportStatistics();
2220 PrintF("Code space : ");
2221 code_space_->ReportStatistics();
2222 PrintF("Map space : ");
2223 map_space_->ReportStatistics();
2224 PrintF("Large object space : ");
2225 lo_space_->ReportStatistics();
2226 PrintF(">>>>>> ========================================= >>>>>>\n");
2227}
2228
2229#endif // DEBUG
2230
2231bool Heap::Contains(HeapObject* value) {
2232 return Contains(value->address());
2233}
2234
2235
2236bool Heap::Contains(Address addr) {
2237 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2238 return HasBeenSetup() &&
2239 (new_space_->ToSpaceContains(addr) ||
2240 old_space_->Contains(addr) ||
2241 code_space_->Contains(addr) ||
2242 map_space_->Contains(addr) ||
2243 lo_space_->SlowContains(addr));
2244}
2245
2246
2247bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2248 return InSpace(value->address(), space);
2249}
2250
2251
2252bool Heap::InSpace(Address addr, AllocationSpace space) {
2253 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2254 if (!HasBeenSetup()) return false;
2255
2256 switch (space) {
2257 case NEW_SPACE:
2258 return new_space_->ToSpaceContains(addr);
2259 case OLD_SPACE:
2260 return old_space_->Contains(addr);
2261 case CODE_SPACE:
2262 return code_space_->Contains(addr);
2263 case MAP_SPACE:
2264 return map_space_->Contains(addr);
2265 case LO_SPACE:
2266 return lo_space_->SlowContains(addr);
2267 }
2268
2269 return false;
2270}
2271
2272
2273#ifdef DEBUG
2274void Heap::Verify() {
2275 ASSERT(HasBeenSetup());
2276
2277 VerifyPointersVisitor visitor;
2278 Heap::IterateRoots(&visitor);
2279
2280 Heap::new_space_->Verify();
2281 Heap::old_space_->Verify();
2282 Heap::code_space_->Verify();
2283 Heap::map_space_->Verify();
2284 Heap::lo_space_->Verify();
2285}
2286#endif // DEBUG
2287
2288
2289Object* Heap::LookupSymbol(Vector<const char> string) {
2290 Object* symbol = NULL;
2291 Object* new_table =
2292 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2293 if (new_table->IsFailure()) return new_table;
2294 symbol_table_ = new_table;
2295 ASSERT(symbol != NULL);
2296 return symbol;
2297}
2298
2299
2300Object* Heap::LookupSymbol(String* string) {
2301 if (string->IsSymbol()) return string;
2302 Object* symbol = NULL;
2303 Object* new_table =
2304 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2305 if (new_table->IsFailure()) return new_table;
2306 symbol_table_ = new_table;
2307 ASSERT(symbol != NULL);
2308 return symbol;
2309}
2310
2311
2312#ifdef DEBUG
2313void Heap::ZapFromSpace() {
2314 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
2315 for (Address a = new_space_->FromSpaceLow();
2316 a < new_space_->FromSpaceHigh();
2317 a += kPointerSize) {
2318 Memory::Address_at(a) = kFromSpaceZapValue;
2319 }
2320}
2321#endif // DEBUG
2322
2323
2324void Heap::IterateRSetRange(Address object_start,
2325 Address object_end,
2326 Address rset_start,
2327 ObjectSlotCallback copy_object_func) {
2328 Address object_address = object_start;
2329 Address rset_address = rset_start;
2330
2331 // Loop over all the pointers in [object_start, object_end).
2332 while (object_address < object_end) {
2333 uint32_t rset_word = Memory::uint32_at(rset_address);
2334
2335 if (rset_word != 0) {
2336 // Bits were set.
2337 uint32_t result_rset = rset_word;
2338
2339 // Loop over all the bits in the remembered set word. Though
2340 // remembered sets are sparse, faster (eg, binary) search for
2341 // set bits does not seem to help much here.
2342 for (int bit_offset = 0; bit_offset < kBitsPerInt; bit_offset++) {
2343 uint32_t bitmask = 1 << bit_offset;
2344 // Do not dereference pointers at or past object_end.
2345 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2346 Object** object_p = reinterpret_cast<Object**>(object_address);
2347 if (Heap::InFromSpace(*object_p)) {
2348 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2349 }
2350 // If this pointer does not need to be remembered anymore, clear
2351 // the remembered set bit.
2352 if (!Heap::InToSpace(*object_p)) result_rset &= ~bitmask;
2353 }
2354 object_address += kPointerSize;
2355 }
2356
2357 // Update the remembered set if it has changed.
2358 if (result_rset != rset_word) {
2359 Memory::uint32_at(rset_address) = result_rset;
2360 }
2361 } else {
2362 // No bits in the word were set. This is the common case.
2363 object_address += kPointerSize * kBitsPerInt;
2364 }
2365
2366 rset_address += kIntSize;
2367 }
2368}
2369
2370
2371void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2372 ASSERT(Page::is_rset_in_use());
2373 ASSERT(space == old_space_ || space == map_space_);
2374
2375 PageIterator it(space, PageIterator::PAGES_IN_USE);
2376 while (it.has_next()) {
2377 Page* page = it.next();
2378 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2379 page->RSetStart(), copy_object_func);
2380 }
2381}
2382
2383
2384#ifdef DEBUG
2385#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2386#else
2387#define SYNCHRONIZE_TAG(tag)
2388#endif
2389
2390void Heap::IterateRoots(ObjectVisitor* v) {
2391 IterateStrongRoots(v);
2392 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2393 SYNCHRONIZE_TAG("symbol_table");
2394}
2395
2396
2397void Heap::IterateStrongRoots(ObjectVisitor* v) {
2398#define ROOT_ITERATE(type, name) \
2399 v->VisitPointer(reinterpret_cast<Object**>(&name##_));
2400 STRONG_ROOT_LIST(ROOT_ITERATE);
2401#undef ROOT_ITERATE
2402 SYNCHRONIZE_TAG("strong_root_list");
2403
2404#define STRUCT_MAP_ITERATE(NAME, Name, name) \
2405 v->VisitPointer(reinterpret_cast<Object**>(&name##_map_));
2406 STRUCT_LIST(STRUCT_MAP_ITERATE);
2407#undef STRUCT_MAP_ITERATE
2408 SYNCHRONIZE_TAG("struct_map");
2409
2410#define SYMBOL_ITERATE(name, string) \
2411 v->VisitPointer(reinterpret_cast<Object**>(&name##_));
2412 SYMBOL_LIST(SYMBOL_ITERATE)
2413#undef SYMBOL_ITERATE
2414 SYNCHRONIZE_TAG("symbol");
2415
2416 Bootstrapper::Iterate(v);
2417 SYNCHRONIZE_TAG("bootstrapper");
2418 Top::Iterate(v);
2419 SYNCHRONIZE_TAG("top");
2420 Debug::Iterate(v);
2421 SYNCHRONIZE_TAG("debug");
2422
2423 // Iterate over local handles in handle scopes.
2424 HandleScopeImplementer::Iterate(v);
2425 SYNCHRONIZE_TAG("handlescope");
2426
2427 // Iterate over the builtin code objects and code stubs in the heap. Note
2428 // that it is not strictly necessary to iterate over code objects on
2429 // scavenge collections. We still do it here because this same function
2430 // is used by the mark-sweep collector and the deserializer.
2431 Builtins::IterateBuiltins(v);
2432 SYNCHRONIZE_TAG("builtins");
2433
2434 // Iterate over global handles.
2435 GlobalHandles::IterateRoots(v);
2436 SYNCHRONIZE_TAG("globalhandles");
2437
2438 // Iterate over pointers being held by inactive threads.
2439 ThreadManager::Iterate(v);
2440 SYNCHRONIZE_TAG("threadmanager");
2441}
2442#undef SYNCHRONIZE_TAG
2443
2444
2445// Flag is set when the heap has been configured. The heap can be repeatedly
2446// configured through the API until it is setup.
2447static bool heap_configured = false;
2448
2449// TODO(1236194): Since the heap size is configurable on the command line
2450// and through the API, we should gracefully handle the case that the heap
2451// size is not big enough to fit all the initial objects.
2452bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2453 if (HasBeenSetup()) return false;
2454
2455 if (semispace_size > 0) semispace_size_ = semispace_size;
2456 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2457
2458 // The new space size must be a power of two to support single-bit testing
2459 // for containment.
2460 semispace_size_ = NextPowerOf2(semispace_size_);
2461 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2462 young_generation_size_ = 2 * semispace_size_;
2463
2464 // The old generation is paged.
2465 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2466
2467 heap_configured = true;
2468 return true;
2469}
2470
2471
2472int Heap::PromotedSpaceSize() {
2473 return old_space_->Size()
2474 + code_space_->Size()
2475 + map_space_->Size()
2476 + lo_space_->Size();
2477}
2478
2479
2480bool Heap::Setup(bool create_heap_objects) {
2481 // Initialize heap spaces and initial maps and objects. Whenever something
2482 // goes wrong, just return false. The caller should check the results and
2483 // call Heap::TearDown() to release allocated memory.
2484 //
2485 // If the heap is not yet configured (eg, through the API), configure it.
2486 // Configuration is based on the flags new-space-size (really the semispace
2487 // size) and old-space-size if set or the initial values of semispace_size_
2488 // and old_generation_size_ otherwise.
2489 if (!heap_configured) {
2490 if (!ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size)) return false;
2491 }
2492
2493 // Setup memory allocator and allocate an initial chunk of memory. The
2494 // initial chunk is double the size of the new space to ensure that we can
2495 // find a pair of semispaces that are contiguous and aligned to their size.
2496 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2497 void* chunk
2498 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2499 if (chunk == NULL) return false;
2500
2501 // Put the initial chunk of the old space at the start of the initial
2502 // chunk, then the two new space semispaces, then the initial chunk of
2503 // code space. Align the pair of semispaces to their size, which must be
2504 // a power of 2.
2505 ASSERT(IsPowerOf2(young_generation_size_));
2506 Address old_space_start = reinterpret_cast<Address>(chunk);
2507 Address new_space_start = RoundUp(old_space_start, young_generation_size_);
2508 Address code_space_start = new_space_start + young_generation_size_;
2509 int old_space_size = new_space_start - old_space_start;
2510 int code_space_size = young_generation_size_ - old_space_size;
2511
2512 // Initialize new space.
2513 new_space_ = new NewSpace(initial_semispace_size_, semispace_size_);
2514 if (new_space_ == NULL) return false;
2515 if (!new_space_->Setup(new_space_start, young_generation_size_)) return false;
2516
2517 // Initialize old space, set the maximum capacity to the old generation
2518 // size.
2519 old_space_ = new OldSpace(old_generation_size_, OLD_SPACE);
2520 if (old_space_ == NULL) return false;
2521 if (!old_space_->Setup(old_space_start, old_space_size)) return false;
2522
2523 // Initialize the code space, set its maximum capacity to the old
2524 // generation size.
2525 code_space_ = new OldSpace(old_generation_size_, CODE_SPACE);
2526 if (code_space_ == NULL) return false;
2527 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2528
2529 // Initialize map space.
2530 map_space_ = new MapSpace(kMaxMapSpaceSize);
2531 if (map_space_ == NULL) return false;
2532 // Setting up a paged space without giving it a virtual memory range big
2533 // enough to hold at least a page will cause it to allocate.
2534 if (!map_space_->Setup(NULL, 0)) return false;
2535
2536 lo_space_ = new LargeObjectSpace();
2537 if (lo_space_ == NULL) return false;
2538 if (!lo_space_->Setup()) return false;
2539
2540 if (create_heap_objects) {
2541 // Create initial maps.
2542 if (!CreateInitialMaps()) return false;
2543 if (!CreateApiObjects()) return false;
2544
2545 // Create initial objects
2546 if (!CreateInitialObjects()) return false;
2547 }
2548
2549 LOG(IntEvent("heap-capacity", Capacity()));
2550 LOG(IntEvent("heap-available", Available()));
2551
2552 return true;
2553}
2554
2555
2556void Heap::TearDown() {
2557 GlobalHandles::TearDown();
2558
2559 if (new_space_ != NULL) {
2560 new_space_->TearDown();
2561 delete new_space_;
2562 new_space_ = NULL;
2563 }
2564
2565 if (old_space_ != NULL) {
2566 old_space_->TearDown();
2567 delete old_space_;
2568 old_space_ = NULL;
2569 }
2570
2571 if (code_space_ != NULL) {
2572 code_space_->TearDown();
2573 delete code_space_;
2574 code_space_ = NULL;
2575 }
2576
2577 if (map_space_ != NULL) {
2578 map_space_->TearDown();
2579 delete map_space_;
2580 map_space_ = NULL;
2581 }
2582
2583 if (lo_space_ != NULL) {
2584 lo_space_->TearDown();
2585 delete lo_space_;
2586 lo_space_ = NULL;
2587 }
2588
2589 MemoryAllocator::TearDown();
2590}
2591
2592
2593void Heap::Shrink() {
2594 // Try to shrink map, old, and code spaces.
2595 map_space_->Shrink();
2596 old_space_->Shrink();
2597 code_space_->Shrink();
2598}
2599
2600
2601#ifdef DEBUG
2602
2603class PrintHandleVisitor: public ObjectVisitor {
2604 public:
2605 void VisitPointers(Object** start, Object** end) {
2606 for (Object** p = start; p < end; p++)
2607 PrintF(" handle %p to %p\n", p, *p);
2608 }
2609};
2610
2611void Heap::PrintHandles() {
2612 PrintF("Handles:\n");
2613 PrintHandleVisitor v;
2614 HandleScopeImplementer::Iterate(&v);
2615}
2616
2617#endif
2618
2619
2620HeapIterator::HeapIterator() {
2621 Init();
2622}
2623
2624
2625HeapIterator::~HeapIterator() {
2626 Shutdown();
2627}
2628
2629
2630void HeapIterator::Init() {
2631 // Start the iteration.
2632 space_iterator_ = new SpaceIterator();
2633 object_iterator_ = space_iterator_->next();
2634}
2635
2636
2637void HeapIterator::Shutdown() {
2638 // Make sure the last iterator is deallocated.
2639 delete space_iterator_;
2640 space_iterator_ = NULL;
2641 object_iterator_ = NULL;
2642}
2643
2644
2645bool HeapIterator::has_next() {
2646 // No iterator means we are done.
2647 if (object_iterator_ == NULL) return false;
2648
2649 if (object_iterator_->has_next_object()) {
2650 // If the current iterator has more objects we are fine.
2651 return true;
2652 } else {
2653 // Go though the spaces looking for one that has objects.
2654 while (space_iterator_->has_next()) {
2655 object_iterator_ = space_iterator_->next();
2656 if (object_iterator_->has_next_object()) {
2657 return true;
2658 }
2659 }
2660 }
2661 // Done with the last space.
2662 object_iterator_ = NULL;
2663 return false;
2664}
2665
2666
2667HeapObject* HeapIterator::next() {
2668 if (has_next()) {
2669 return object_iterator_->next_object();
2670 } else {
2671 return NULL;
2672 }
2673}
2674
2675
2676void HeapIterator::reset() {
2677 // Restart the iterator.
2678 Shutdown();
2679 Init();
2680}
2681
2682
2683//
2684// HeapProfiler class implementation.
2685//
2686#ifdef ENABLE_LOGGING_AND_PROFILING
2687void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
2688 InstanceType type = obj->map()->instance_type();
2689 ASSERT(0 <= type && type <= LAST_TYPE);
2690 info[type].increment_number(1);
2691 info[type].increment_bytes(obj->Size());
2692}
2693#endif
2694
2695
2696#ifdef ENABLE_LOGGING_AND_PROFILING
2697void HeapProfiler::WriteSample() {
2698 LOG(HeapSampleBeginEvent("Heap", "allocated"));
2699
2700 HistogramInfo info[LAST_TYPE+1];
2701#define DEF_TYPE_NAME(name) info[name].set_name(#name);
2702 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
2703#undef DEF_TYPE_NAME
2704
2705 HeapIterator iterator;
2706 while (iterator.has_next()) {
2707 CollectStats(iterator.next(), info);
2708 }
2709
2710 // Lump all the string types together.
2711 int string_number = 0;
2712 int string_bytes = 0;
2713#define INCREMENT_SIZE(type, size, name) \
2714 string_number += info[type].number(); \
2715 string_bytes += info[type].bytes();
2716 STRING_TYPE_LIST(INCREMENT_SIZE)
2717#undef INCREMENT_SIZE
2718 if (string_bytes > 0) {
2719 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
2720 }
2721
2722 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
2723 if (info[i].bytes() > 0) {
2724 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
2725 info[i].bytes()));
2726 }
2727 }
2728
2729 LOG(HeapSampleEndEvent("Heap", "allocated"));
2730}
2731
2732
2733#endif
2734
2735
2736
2737#ifdef DEBUG
2738
2739static bool search_for_any_global;
2740static Object* search_target;
2741static bool found_target;
2742static List<Object*> object_stack(20);
2743
2744
2745// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2746static const int kMarkTag = 2;
2747
2748static void MarkObjectRecursively(Object** p);
2749class MarkObjectVisitor : public ObjectVisitor {
2750 public:
2751 void VisitPointers(Object** start, Object** end) {
2752 // Copy all HeapObject pointers in [start, end)
2753 for (Object** p = start; p < end; p++) {
2754 if ((*p)->IsHeapObject())
2755 MarkObjectRecursively(p);
2756 }
2757 }
2758};
2759
2760static MarkObjectVisitor mark_visitor;
2761
2762static void MarkObjectRecursively(Object** p) {
2763 if (!(*p)->IsHeapObject()) return;
2764
2765 HeapObject* obj = HeapObject::cast(*p);
2766
2767 Object* map = obj->map();
2768
2769 if (!map->IsHeapObject()) return; // visited before
2770
2771 if (found_target) return; // stop if target found
2772 object_stack.Add(obj);
2773 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
2774 (!search_for_any_global && (obj == search_target))) {
2775 found_target = true;
2776 return;
2777 }
2778
2779 if (obj->IsCode()) {
2780 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
2781 }
2782
2783 // not visited yet
2784 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
2785
2786 Address map_addr = map_p->address();
2787
2788 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
2789
2790 MarkObjectRecursively(&map);
2791
2792 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
2793 &mark_visitor);
2794
2795 if (!found_target) // don't pop if found the target
2796 object_stack.RemoveLast();
2797}
2798
2799
2800static void UnmarkObjectRecursively(Object** p);
2801class UnmarkObjectVisitor : public ObjectVisitor {
2802 public:
2803 void VisitPointers(Object** start, Object** end) {
2804 // Copy all HeapObject pointers in [start, end)
2805 for (Object** p = start; p < end; p++) {
2806 if ((*p)->IsHeapObject())
2807 UnmarkObjectRecursively(p);
2808 }
2809 }
2810};
2811
2812static UnmarkObjectVisitor unmark_visitor;
2813
2814static void UnmarkObjectRecursively(Object** p) {
2815 if (!(*p)->IsHeapObject()) return;
2816
2817 HeapObject* obj = HeapObject::cast(*p);
2818
2819 Object* map = obj->map();
2820
2821 if (map->IsHeapObject()) return; // unmarked already
2822
2823 Address map_addr = reinterpret_cast<Address>(map);
2824
2825 map_addr -= kMarkTag;
2826
2827 ASSERT_TAG_ALIGNED(map_addr);
2828
2829 HeapObject* map_p = HeapObject::FromAddress(map_addr);
2830
2831 obj->set_map(reinterpret_cast<Map*>(map_p));
2832
2833 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
2834
2835 obj->IterateBody(Map::cast(map_p)->instance_type(),
2836 obj->SizeFromMap(Map::cast(map_p)),
2837 &unmark_visitor);
2838
2839 if (obj->IsCode()) {
2840 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
2841 }
2842}
2843
2844
2845static void MarkRootObjectRecursively(Object** root) {
2846 if (search_for_any_global) {
2847 ASSERT(search_target == NULL);
2848 } else {
2849 ASSERT(search_target->IsHeapObject());
2850 }
2851 found_target = false;
2852 object_stack.Clear();
2853
2854 MarkObjectRecursively(root);
2855 UnmarkObjectRecursively(root);
2856
2857 if (found_target) {
2858 PrintF("=====================================\n");
2859 PrintF("==== Path to object ====\n");
2860 PrintF("=====================================\n\n");
2861
2862 ASSERT(!object_stack.is_empty());
2863 for (int i = 0; i < object_stack.length(); i++) {
2864 if (i > 0) PrintF("\n |\n |\n V\n\n");
2865 Object* obj = object_stack[i];
2866 obj->Print();
2867 }
2868 PrintF("=====================================\n");
2869 }
2870}
2871
2872
2873// Helper class for visiting HeapObjects recursively.
2874class MarkRootVisitor: public ObjectVisitor {
2875 public:
2876 void VisitPointers(Object** start, Object** end) {
2877 // Visit all HeapObject pointers in [start, end)
2878 for (Object** p = start; p < end; p++) {
2879 if ((*p)->IsHeapObject())
2880 MarkRootObjectRecursively(p);
2881 }
2882 }
2883};
2884
2885
2886// Triggers a depth-first traversal of reachable objects from roots
2887// and finds a path to a specific heap object and prints it.
2888void Heap::TracePathToObject() {
2889 search_target = NULL;
2890 search_for_any_global = false;
2891
2892 MarkRootVisitor root_visitor;
2893 IterateRoots(&root_visitor);
2894}
2895
2896
2897// Triggers a depth-first traversal of reachable objects from roots
2898// and finds a path to any global object and prints it. Useful for
2899// determining the source for leaks of global objects.
2900void Heap::TracePathToGlobal() {
2901 search_target = NULL;
2902 search_for_any_global = true;
2903
2904 MarkRootVisitor root_visitor;
2905 IterateRoots(&root_visitor);
2906}
2907#endif
2908
2909
2910} } // namespace v8::internal