blob: 7894f247f2e5f73c692f866cae5456433bf686ce [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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 "macro-assembler.h"
31#include "mark-compact.h"
32#include "platform.h"
33
34namespace v8 { namespace internal {
35
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036// For contiguous spaces, top should be in the space (or at the end) and limit
37// should be the end of the space.
38#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000039 ASSERT((space).low() <= (info).top \
40 && (info).top <= (space).high() \
41 && (info).limit == (space).high())
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000042
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
44// ----------------------------------------------------------------------------
45// HeapObjectIterator
46
47HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
48 Initialize(space->bottom(), space->top(), NULL);
49}
50
51
52HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
53 HeapObjectCallback size_func) {
54 Initialize(space->bottom(), space->top(), size_func);
55}
56
57
58HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start) {
59 Initialize(start, space->top(), NULL);
60}
61
62
63HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start,
64 HeapObjectCallback size_func) {
65 Initialize(start, space->top(), size_func);
66}
67
68
69void HeapObjectIterator::Initialize(Address cur, Address end,
70 HeapObjectCallback size_f) {
71 cur_addr_ = cur;
72 end_addr_ = end;
73 end_page_ = Page::FromAllocationTop(end);
74 size_func_ = size_f;
75 Page* p = Page::FromAllocationTop(cur_addr_);
76 cur_limit_ = (p == end_page_) ? end_addr_ : p->AllocationTop();
77
78#ifdef DEBUG
79 Verify();
80#endif
81}
82
83
84bool HeapObjectIterator::HasNextInNextPage() {
85 if (cur_addr_ == end_addr_) return false;
86
87 Page* cur_page = Page::FromAllocationTop(cur_addr_);
88 cur_page = cur_page->next_page();
89 ASSERT(cur_page->is_valid());
90
91 cur_addr_ = cur_page->ObjectAreaStart();
92 cur_limit_ = (cur_page == end_page_) ? end_addr_ : cur_page->AllocationTop();
93
94 ASSERT(cur_addr_ < cur_limit_);
95#ifdef DEBUG
96 Verify();
97#endif
98 return true;
99}
100
101
102#ifdef DEBUG
103void HeapObjectIterator::Verify() {
104 Page* p = Page::FromAllocationTop(cur_addr_);
105 ASSERT(p == Page::FromAllocationTop(cur_limit_));
106 ASSERT(p->Offset(cur_addr_) <= p->Offset(cur_limit_));
107}
108#endif
109
110
111// -----------------------------------------------------------------------------
112// PageIterator
113
114PageIterator::PageIterator(PagedSpace* space, Mode mode) {
115 cur_page_ = space->first_page_;
116 switch (mode) {
117 case PAGES_IN_USE:
118 stop_page_ = space->AllocationTopPage()->next_page();
119 break;
120 case PAGES_USED_BY_MC:
121 stop_page_ = space->MCRelocationTopPage()->next_page();
122 break;
123 case ALL_PAGES:
124 stop_page_ = Page::FromAddress(NULL);
125 break;
126 default:
127 UNREACHABLE();
128 }
129}
130
131
132// -----------------------------------------------------------------------------
133// Page
134
135#ifdef DEBUG
136Page::RSetState Page::rset_state_ = Page::IN_USE;
137#endif
138
139// -----------------------------------------------------------------------------
140// MemoryAllocator
141//
142int MemoryAllocator::capacity_ = 0;
143int MemoryAllocator::size_ = 0;
144
145VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
146
147// 270 is an estimate based on the static default heap size of a pair of 256K
148// semispaces and a 64M old generation.
149const int kEstimatedNumberOfChunks = 270;
150List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
151 kEstimatedNumberOfChunks);
152List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
153int MemoryAllocator::max_nof_chunks_ = 0;
154int MemoryAllocator::top_ = 0;
155
156
157void MemoryAllocator::Push(int free_chunk_id) {
158 ASSERT(max_nof_chunks_ > 0);
159 ASSERT(top_ < max_nof_chunks_);
160 free_chunk_ids_[top_++] = free_chunk_id;
161}
162
163
164int MemoryAllocator::Pop() {
165 ASSERT(top_ > 0);
166 return free_chunk_ids_[--top_];
167}
168
169
170bool MemoryAllocator::Setup(int capacity) {
171 capacity_ = RoundUp(capacity, Page::kPageSize);
172
173 // Over-estimate the size of chunks_ array. It assumes the expansion of old
174 // space is always in the unit of a chunk (kChunkSize) except the last
175 // expansion.
176 //
177 // Due to alignment, allocated space might be one page less than required
178 // number (kPagesPerChunk) of pages for old spaces.
179 //
kasper.lund7276f142008-07-30 08:49:36 +0000180 // Reserve two chunk ids for semispaces, one for map space, one for old
181 // space, and one for code space.
182 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000183 if (max_nof_chunks_ > kMaxNofChunks) return false;
184
185 size_ = 0;
186 ChunkInfo info; // uninitialized element.
187 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
188 chunks_.Add(info);
189 free_chunk_ids_.Add(i);
190 }
191 top_ = max_nof_chunks_;
192 return true;
193}
194
195
196void MemoryAllocator::TearDown() {
197 for (int i = 0; i < max_nof_chunks_; i++) {
198 if (chunks_[i].address() != NULL) DeleteChunk(i);
199 }
200 chunks_.Clear();
201 free_chunk_ids_.Clear();
202
203 if (initial_chunk_ != NULL) {
204 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
205 delete initial_chunk_;
206 initial_chunk_ = NULL;
207 }
208
209 ASSERT(top_ == max_nof_chunks_); // all chunks are free
210 top_ = 0;
211 capacity_ = 0;
212 size_ = 0;
213 max_nof_chunks_ = 0;
214}
215
216
217void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000218 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000219 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000220 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
221
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000222 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000223 int alloced = *allocated;
224 size_ += alloced;
225 Counters::memory_allocated.Increment(alloced);
226 return mem;
227}
228
229
230void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
231 OS::Free(mem, length);
232 Counters::memory_allocated.Decrement(length);
233 size_ -= length;
234 ASSERT(size_ >= 0);
235}
236
237
238void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
239 ASSERT(initial_chunk_ == NULL);
240
241 initial_chunk_ = new VirtualMemory(requested);
242 CHECK(initial_chunk_ != NULL);
243 if (!initial_chunk_->IsReserved()) {
244 delete initial_chunk_;
245 initial_chunk_ = NULL;
246 return NULL;
247 }
248
249 // We are sure that we have mapped a block of requested addresses.
250 ASSERT(initial_chunk_->size() == requested);
251 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
252 size_ += requested;
253 return initial_chunk_->address();
254}
255
256
257static int PagesInChunk(Address start, size_t size) {
258 // The first page starts on the first page-aligned address from start onward
259 // and the last page ends on the last page-aligned address before
260 // start+size. Page::kPageSize is a power of two so we can divide by
261 // shifting.
262 return (RoundDown(start + size, Page::kPageSize)
263 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
264}
265
266
267Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
268 PagedSpace* owner) {
269 if (requested_pages <= 0) return Page::FromAddress(NULL);
270 size_t chunk_size = requested_pages * Page::kPageSize;
271
272 // There is not enough space to guarantee the desired number pages can be
273 // allocated.
274 if (size_ + static_cast<int>(chunk_size) > capacity_) {
275 // Request as many pages as we can.
276 chunk_size = capacity_ - size_;
277 requested_pages = chunk_size >> Page::kPageSizeBits;
278
279 if (requested_pages <= 0) return Page::FromAddress(NULL);
280 }
kasper.lund7276f142008-07-30 08:49:36 +0000281 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282 if (chunk == NULL) return Page::FromAddress(NULL);
283 LOG(NewEvent("PagedChunk", chunk, chunk_size));
284
285 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
286 if (*allocated_pages == 0) {
287 FreeRawMemory(chunk, chunk_size);
288 LOG(DeleteEvent("PagedChunk", chunk));
289 return Page::FromAddress(NULL);
290 }
291
292 int chunk_id = Pop();
293 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
294
295 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
296}
297
298
299Page* MemoryAllocator::CommitPages(Address start, size_t size,
300 PagedSpace* owner, int* num_pages) {
301 ASSERT(start != NULL);
302 *num_pages = PagesInChunk(start, size);
303 ASSERT(*num_pages > 0);
304 ASSERT(initial_chunk_ != NULL);
305 ASSERT(initial_chunk_->address() <= start);
306 ASSERT(start + size <= reinterpret_cast<Address>(initial_chunk_->address())
307 + initial_chunk_->size());
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000308 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309 return Page::FromAddress(NULL);
310 }
311 Counters::memory_allocated.Increment(size);
312
313 // So long as we correctly overestimated the number of chunks we should not
314 // run out of chunk ids.
315 CHECK(!OutOfChunkIds());
316 int chunk_id = Pop();
317 chunks_[chunk_id].init(start, size, owner);
318 return InitializePagesInChunk(chunk_id, *num_pages, owner);
319}
320
321
kasper.lund7276f142008-07-30 08:49:36 +0000322bool MemoryAllocator::CommitBlock(Address start,
323 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000324 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000325 ASSERT(start != NULL);
326 ASSERT(size > 0);
327 ASSERT(initial_chunk_ != NULL);
328 ASSERT(initial_chunk_->address() <= start);
329 ASSERT(start + size <= reinterpret_cast<Address>(initial_chunk_->address())
330 + initial_chunk_->size());
331
kasper.lund7276f142008-07-30 08:49:36 +0000332 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333 Counters::memory_allocated.Increment(size);
334 return true;
335}
336
337
338Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
339 PagedSpace* owner) {
340 ASSERT(IsValidChunk(chunk_id));
341 ASSERT(pages_in_chunk > 0);
342
343 Address chunk_start = chunks_[chunk_id].address();
344
345 Address low = RoundUp(chunk_start, Page::kPageSize);
346
347#ifdef DEBUG
348 size_t chunk_size = chunks_[chunk_id].size();
349 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
350 ASSERT(pages_in_chunk <=
351 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
352#endif
353
354 Address page_addr = low;
355 for (int i = 0; i < pages_in_chunk; i++) {
356 Page* p = Page::FromAddress(page_addr);
357 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
358 p->is_normal_page = 1;
359 page_addr += Page::kPageSize;
360 }
361
362 // Set the next page of the last page to 0.
363 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
364 last_page->opaque_header = OffsetFrom(0) | chunk_id;
365
366 return Page::FromAddress(low);
367}
368
369
370Page* MemoryAllocator::FreePages(Page* p) {
371 if (!p->is_valid()) return p;
372
373 // Find the first page in the same chunk as 'p'
374 Page* first_page = FindFirstPageInSameChunk(p);
375 Page* page_to_return = Page::FromAddress(NULL);
376
377 if (p != first_page) {
378 // Find the last page in the same chunk as 'prev'.
379 Page* last_page = FindLastPageInSameChunk(p);
380 first_page = GetNextPage(last_page); // first page in next chunk
381
382 // set the next_page of last_page to NULL
383 SetNextPage(last_page, Page::FromAddress(NULL));
384 page_to_return = p; // return 'p' when exiting
385 }
386
387 while (first_page->is_valid()) {
388 int chunk_id = GetChunkId(first_page);
389 ASSERT(IsValidChunk(chunk_id));
390
391 // Find the first page of the next chunk before deleting this chunk.
392 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
393
394 // Free the current chunk.
395 DeleteChunk(chunk_id);
396 }
397
398 return page_to_return;
399}
400
401
402void MemoryAllocator::DeleteChunk(int chunk_id) {
403 ASSERT(IsValidChunk(chunk_id));
404
405 ChunkInfo& c = chunks_[chunk_id];
406
407 // We cannot free a chunk contained in the initial chunk because it was not
408 // allocated with AllocateRawMemory. Instead we uncommit the virtual
409 // memory.
410 bool in_initial_chunk = false;
411 if (initial_chunk_ != NULL) {
412 Address start = static_cast<Address>(initial_chunk_->address());
413 Address end = start + initial_chunk_->size();
414 in_initial_chunk = (start <= c.address()) && (c.address() < end);
415 }
416
417 if (in_initial_chunk) {
418 // TODO(1240712): VirtualMemory::Uncommit has a return value which
419 // is ignored here.
420 initial_chunk_->Uncommit(c.address(), c.size());
421 Counters::memory_allocated.Decrement(c.size());
422 } else {
423 LOG(DeleteEvent("PagedChunk", c.address()));
424 FreeRawMemory(c.address(), c.size());
425 }
426 c.init(NULL, 0, NULL);
427 Push(chunk_id);
428}
429
430
431Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
432 int chunk_id = GetChunkId(p);
433 ASSERT(IsValidChunk(chunk_id));
434
435 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
436 return Page::FromAddress(low);
437}
438
439
440Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
441 int chunk_id = GetChunkId(p);
442 ASSERT(IsValidChunk(chunk_id));
443
444 Address chunk_start = chunks_[chunk_id].address();
445 size_t chunk_size = chunks_[chunk_id].size();
446
447 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
448 ASSERT(chunk_start <= p->address() && p->address() < high);
449
450 return Page::FromAddress(high - Page::kPageSize);
451}
452
453
454#ifdef DEBUG
455void MemoryAllocator::ReportStatistics() {
456 float pct = static_cast<float>(capacity_ - size_) / capacity_;
457 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
458 capacity_, size_, static_cast<int>(pct*100));
459}
460#endif
461
462
463// -----------------------------------------------------------------------------
464// PagedSpace implementation
465
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000466PagedSpace::PagedSpace(int max_capacity,
467 AllocationSpace id,
468 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000469 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
471 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472 accounting_stats_.Clear();
473
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474 allocation_info_.top = NULL;
475 allocation_info_.limit = NULL;
476
477 mc_forwarding_info_.top = NULL;
478 mc_forwarding_info_.limit = NULL;
479}
480
481
482bool PagedSpace::Setup(Address start, size_t size) {
483 if (HasBeenSetup()) return false;
484
485 int num_pages = 0;
486 // Try to use the virtual memory range passed to us. If it is too small to
487 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000488 int pages_in_chunk = PagesInChunk(start, size);
489 if (pages_in_chunk > 0) {
490 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
491 Page::kPageSize * pages_in_chunk,
492 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000493 } else {
494 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
495 max_capacity_ / Page::kObjectAreaSize);
496 first_page_ =
497 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
498 if (!first_page_->is_valid()) return false;
499 }
500
501 // We are sure that the first page is valid and that we have at least one
502 // page.
503 ASSERT(first_page_->is_valid());
504 ASSERT(num_pages > 0);
505 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
506 ASSERT(Capacity() <= max_capacity_);
507
508 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
509 p->ClearRSet();
510 }
511
512 // Use first_page_ for allocation.
513 SetAllocationInfo(&allocation_info_, first_page_);
514
515 return true;
516}
517
518
519bool PagedSpace::HasBeenSetup() {
520 return (Capacity() > 0);
521}
522
523
524void PagedSpace::TearDown() {
525 first_page_ = MemoryAllocator::FreePages(first_page_);
526 ASSERT(!first_page_->is_valid());
527
528 accounting_stats_.Clear();
529}
530
531
532void PagedSpace::ClearRSet() {
533 PageIterator it(this, PageIterator::ALL_PAGES);
534 while (it.has_next()) {
535 it.next()->ClearRSet();
536 }
537}
538
539
540Object* PagedSpace::FindObject(Address addr) {
541#ifdef DEBUG
542 // Note: this function can only be called before or after mark-compact GC
543 // because it accesses map pointers.
544 ASSERT(!MarkCompactCollector::in_use());
545#endif
546
547 if (!Contains(addr)) return Failure::Exception();
548
549 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000550 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551 Address cur = p->ObjectAreaStart();
552 Address end = p->AllocationTop();
553 while (cur < end) {
554 HeapObject* obj = HeapObject::FromAddress(cur);
555 Address next = cur + obj->Size();
556 if ((cur <= addr) && (addr < next)) return obj;
557 cur = next;
558 }
559
kasper.lund7276f142008-07-30 08:49:36 +0000560 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000561 return Failure::Exception();
562}
563
564
kasper.lund7276f142008-07-30 08:49:36 +0000565bool PagedSpace::IsUsed(Page* page) {
566 PageIterator it(this, PageIterator::PAGES_IN_USE);
567 while (it.has_next()) {
568 if (page == it.next()) return true;
569 }
570 return false;
571}
572
573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000574void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
575 alloc_info->top = p->ObjectAreaStart();
576 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000577 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578}
579
580
581void PagedSpace::MCResetRelocationInfo() {
582 // Set page indexes.
583 int i = 0;
584 PageIterator it(this, PageIterator::ALL_PAGES);
585 while (it.has_next()) {
586 Page* p = it.next();
587 p->mc_page_index = i++;
588 }
589
590 // Set mc_forwarding_info_ to the first page in the space.
591 SetAllocationInfo(&mc_forwarding_info_, first_page_);
592 // All the bytes in the space are 'available'. We will rediscover
593 // allocated and wasted bytes during GC.
594 accounting_stats_.Reset();
595}
596
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
599#ifdef DEBUG
600 // The Contains function considers the address at the beginning of a
601 // page in the page, MCSpaceOffsetForAddress considers it is in the
602 // previous page.
603 if (Page::IsAlignedToPageSize(addr)) {
604 ASSERT(Contains(addr - kPointerSize));
605 } else {
606 ASSERT(Contains(addr));
607 }
608#endif
609
610 // If addr is at the end of a page, it belongs to previous page
611 Page* p = Page::IsAlignedToPageSize(addr)
612 ? Page::FromAllocationTop(addr)
613 : Page::FromAddress(addr);
614 int index = p->mc_page_index;
615 return (index * Page::kPageSize) + p->Offset(addr);
616}
617
618
kasper.lund7276f142008-07-30 08:49:36 +0000619// Slow case for reallocating and promoting objects during a compacting
620// collection. This function is not space-specific.
621HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
622 Page* current_page = TopPageOf(mc_forwarding_info_);
623 if (!current_page->next_page()->is_valid()) {
624 if (!Expand(current_page)) {
625 return NULL;
626 }
627 }
628
629 // There are surely more pages in the space now.
630 ASSERT(current_page->next_page()->is_valid());
631 // We do not add the top of page block for current page to the space's
632 // free list---the block may contain live objects so we cannot write
633 // bookkeeping information to it. Instead, we will recover top of page
634 // blocks when we move objects to their new locations.
635 //
636 // We do however write the allocation pointer to the page. The encoding
637 // of forwarding addresses is as an offset in terms of live bytes, so we
638 // need quick access to the allocation top of each page to decode
639 // forwarding addresses.
640 current_page->mc_relocation_top = mc_forwarding_info_.top;
641 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
642 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
643}
644
645
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646bool PagedSpace::Expand(Page* last_page) {
647 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
648 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
649
650 if (Capacity() == max_capacity_) return false;
651
652 ASSERT(Capacity() < max_capacity_);
653 // Last page must be valid and its next page is invalid.
654 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
655
656 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
657 if (available_pages <= 0) return false;
658
659 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
660 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
661 if (!p->is_valid()) return false;
662
663 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
664 ASSERT(Capacity() <= max_capacity_);
665
666 MemoryAllocator::SetNextPage(last_page, p);
667
668 // Clear remembered set of new pages.
669 while (p->is_valid()) {
670 p->ClearRSet();
671 p = p->next_page();
672 }
673
674 return true;
675}
676
677
678#ifdef DEBUG
679int PagedSpace::CountTotalPages() {
680 int count = 0;
681 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
682 count++;
683 }
684 return count;
685}
686#endif
687
688
689void PagedSpace::Shrink() {
690 // Release half of free pages.
691 Page* top_page = AllocationTopPage();
692 ASSERT(top_page->is_valid());
693
694 // Loop over the pages from the top page to the end of the space to count
695 // the number of pages to keep and find the last page to keep.
696 int free_pages = 0;
697 int pages_to_keep = 0; // Of the free pages.
698 Page* last_page_to_keep = top_page;
699 Page* current_page = top_page->next_page();
700 // Loop over the pages to the end of the space.
701 while (current_page->is_valid()) {
kasper.lund7276f142008-07-30 08:49:36 +0000702 // Advance last_page_to_keep every other step to end up at the midpoint.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703 if ((free_pages & 0x1) == 1) {
704 pages_to_keep++;
705 last_page_to_keep = last_page_to_keep->next_page();
706 }
707 free_pages++;
708 current_page = current_page->next_page();
709 }
710
711 // Free pages after last_page_to_keep, and adjust the next_page link.
712 Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
713 MemoryAllocator::SetNextPage(last_page_to_keep, p);
714
715 // Since pages are only freed in whole chunks, we may have kept more than
716 // pages_to_keep.
717 while (p->is_valid()) {
718 pages_to_keep++;
719 p = p->next_page();
720 }
721
722 // The difference between free_pages and pages_to_keep is the number of
723 // pages actually freed.
724 ASSERT(pages_to_keep <= free_pages);
725 int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
726 accounting_stats_.ShrinkSpace(bytes_freed);
727
728 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
729}
730
731
732bool PagedSpace::EnsureCapacity(int capacity) {
733 if (Capacity() >= capacity) return true;
734
735 // Start from the allocation top and loop to the last page in the space.
736 Page* last_page = AllocationTopPage();
737 Page* next_page = last_page->next_page();
738 while (next_page->is_valid()) {
739 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
740 next_page = last_page->next_page();
741 }
742
743 // Expand the space until it has the required capacity or expansion fails.
744 do {
745 if (!Expand(last_page)) return false;
746 ASSERT(last_page->next_page()->is_valid());
747 last_page =
748 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
749 } while (Capacity() < capacity);
750
751 return true;
752}
753
754
755#ifdef DEBUG
756void PagedSpace::Print() { }
757#endif
758
759
760// -----------------------------------------------------------------------------
761// NewSpace implementation
762
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000763
764bool NewSpace::Setup(Address start, int size) {
765 // Setup new space based on the preallocated memory block defined by
766 // start and size. The provided space is divided into two semi-spaces.
767 // To support fast containment testing in the new space, the size of
768 // this chunk must be a power of two and it must be aligned to its size.
769 int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
770 int maximum_semispace_capacity = Heap::SemiSpaceSize();
771
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000772 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
773 ASSERT(IsPowerOf2(maximum_semispace_capacity));
774 maximum_capacity_ = maximum_semispace_capacity;
775 capacity_ = initial_semispace_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000776
777 // Allocate and setup the histogram arrays if necessary.
778#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
779 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
780 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
781
782#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
783 promoted_histogram_[name].set_name(#name);
784 INSTANCE_TYPE_LIST(SET_NAME)
785#undef SET_NAME
786#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000787
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000788 ASSERT(size == 2 * maximum_capacity_);
789 ASSERT(IsAddressAligned(start, size, 0));
790
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000791 if (!to_space_.Setup(start, capacity_, maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000792 return false;
793 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000794 if (!from_space_.Setup(start + maximum_capacity_,
795 capacity_,
796 maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 return false;
798 }
799
800 start_ = start;
801 address_mask_ = ~(size - 1);
802 object_mask_ = address_mask_ | kHeapObjectTag;
803 object_expected_ = reinterpret_cast<uint32_t>(start) | kHeapObjectTag;
804
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000805 allocation_info_.top = to_space_.low();
806 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 mc_forwarding_info_.top = NULL;
808 mc_forwarding_info_.limit = NULL;
809
810 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
811 return true;
812}
813
814
815void NewSpace::TearDown() {
816#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
817 if (allocated_histogram_) {
818 DeleteArray(allocated_histogram_);
819 allocated_histogram_ = NULL;
820 }
821 if (promoted_histogram_) {
822 DeleteArray(promoted_histogram_);
823 promoted_histogram_ = NULL;
824 }
825#endif
826
827 start_ = NULL;
828 capacity_ = 0;
829 allocation_info_.top = NULL;
830 allocation_info_.limit = NULL;
831 mc_forwarding_info_.top = NULL;
832 mc_forwarding_info_.limit = NULL;
833
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000834 to_space_.TearDown();
835 from_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836}
837
838
839void NewSpace::Flip() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000840 SemiSpace tmp = from_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000841 from_space_ = to_space_;
842 to_space_ = tmp;
843}
844
845
846bool NewSpace::Double() {
847 ASSERT(capacity_ <= maximum_capacity_ / 2);
848 // TODO(1240712): Failure to double the from space can result in
849 // semispaces of different sizes. In the event of that failure, the
850 // to space doubling should be rolled back before returning false.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000851 if (!to_space_.Double() || !from_space_.Double()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000852 capacity_ *= 2;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000853 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000854 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
855 return true;
856}
857
858
859void NewSpace::ResetAllocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000860 allocation_info_.top = to_space_.low();
861 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000862 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
863}
864
865
866void NewSpace::MCResetRelocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000867 mc_forwarding_info_.top = from_space_.low();
868 mc_forwarding_info_.limit = from_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000869 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
870}
871
872
873void NewSpace::MCCommitRelocationInfo() {
874 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
875 // valid allocation info for the to space.
876 allocation_info_.top = mc_forwarding_info_.top;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000877 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
879}
880
881
882#ifdef DEBUG
883// We do not use the SemispaceIterator because verification doesn't assume
884// that it works (it depends on the invariants we are checking).
885void NewSpace::Verify() {
886 // The allocation pointer should be in the space or at the very end.
887 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
888
889 // There should be objects packed in from the low address up to the
890 // allocation pointer.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000891 Address current = to_space_.low();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000892 while (current < top()) {
893 HeapObject* object = HeapObject::FromAddress(current);
894
895 // The first word should be a map, and we expect all map pointers to
896 // be in map space.
897 Map* map = object->map();
898 ASSERT(map->IsMap());
899 ASSERT(Heap::map_space()->Contains(map));
900
901 // The object should not be code or a map.
902 ASSERT(!object->IsMap());
903 ASSERT(!object->IsCode());
904
905 // The object itself should look OK.
906 object->Verify();
907
908 // All the interior pointers should be contained in the heap.
909 VerifyPointersVisitor visitor;
910 int size = object->Size();
911 object->IterateBody(map->instance_type(), size, &visitor);
912
913 current += size;
914 }
915
916 // The allocation pointer should not be in the middle of an object.
917 ASSERT(current == top());
918}
919#endif
920
921
922// -----------------------------------------------------------------------------
923// SemiSpace implementation
924
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000925bool SemiSpace::Setup(Address start,
926 int initial_capacity,
927 int maximum_capacity) {
928 // Creates a space in the young generation. The constructor does not
929 // allocate memory from the OS. A SemiSpace is given a contiguous chunk of
930 // memory of size 'capacity' when set up, and does not grow or shrink
931 // otherwise. In the mark-compact collector, the memory region of the from
932 // space is used as the marking stack. It requires contiguous memory
933 // addresses.
934 capacity_ = initial_capacity;
935 maximum_capacity_ = maximum_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000936
kasper.lund7276f142008-07-30 08:49:36 +0000937 if (!MemoryAllocator::CommitBlock(start, capacity_, executable())) {
938 return false;
939 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000940
941 start_ = start;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000942 address_mask_ = ~(maximum_capacity - 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000943 object_mask_ = address_mask_ | kHeapObjectTag;
944 object_expected_ = reinterpret_cast<uint32_t>(start) | kHeapObjectTag;
945
946 age_mark_ = start_;
947 return true;
948}
949
950
951void SemiSpace::TearDown() {
952 start_ = NULL;
953 capacity_ = 0;
954}
955
956
957bool SemiSpace::Double() {
kasper.lund7276f142008-07-30 08:49:36 +0000958 if (!MemoryAllocator::CommitBlock(high(), capacity_, executable())) {
959 return false;
960 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000961 capacity_ *= 2;
962 return true;
963}
964
965
966#ifdef DEBUG
967void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000968
969
970void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000971#endif
972
973
974// -----------------------------------------------------------------------------
975// SemiSpaceIterator implementation.
976SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
977 Initialize(space, space->bottom(), space->top(), NULL);
978}
979
980
981SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
982 HeapObjectCallback size_func) {
983 Initialize(space, space->bottom(), space->top(), size_func);
984}
985
986
987SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
988 Initialize(space, start, space->top(), NULL);
989}
990
991
992void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
993 Address end,
994 HeapObjectCallback size_func) {
995 ASSERT(space->ToSpaceContains(start));
996 ASSERT(space->ToSpaceLow() <= end
997 && end <= space->ToSpaceHigh());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000998 space_ = &space->to_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000999 current_ = start;
1000 limit_ = end;
1001 size_func_ = size_func;
1002}
1003
1004
1005#ifdef DEBUG
1006// A static array of histogram info for each type.
1007static HistogramInfo heap_histograms[LAST_TYPE+1];
1008static JSObject::SpillInformation js_spill_information;
1009
1010// heap_histograms is shared, always clear it before using it.
1011static void ClearHistograms() {
1012 // We reset the name each time, though it hasn't changed.
1013#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1014 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1015#undef DEF_TYPE_NAME
1016
1017#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1018 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1019#undef CLEAR_HISTOGRAM
1020
1021 js_spill_information.Clear();
1022}
1023
1024
1025static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1026
1027
1028static void ClearCodeKindStatistics() {
1029 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1030 code_kind_statistics[i] = 0;
1031 }
1032}
1033
1034
1035static void ReportCodeKindStatistics() {
1036 const char* table[Code::NUMBER_OF_KINDS];
1037
1038#define CASE(name) \
1039 case Code::name: table[Code::name] = #name; \
1040 break
1041
1042 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1043 switch (static_cast<Code::Kind>(i)) {
1044 CASE(FUNCTION);
1045 CASE(STUB);
1046 CASE(BUILTIN);
1047 CASE(LOAD_IC);
1048 CASE(KEYED_LOAD_IC);
1049 CASE(STORE_IC);
1050 CASE(KEYED_STORE_IC);
1051 CASE(CALL_IC);
1052 }
1053 }
1054
1055#undef CASE
1056
1057 PrintF("\n Code kind histograms: \n");
1058 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1059 if (code_kind_statistics[i] > 0) {
1060 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1061 }
1062 }
1063 PrintF("\n");
1064}
1065
1066
1067static int CollectHistogramInfo(HeapObject* obj) {
1068 InstanceType type = obj->map()->instance_type();
1069 ASSERT(0 <= type && type <= LAST_TYPE);
1070 ASSERT(heap_histograms[type].name() != NULL);
1071 heap_histograms[type].increment_number(1);
1072 heap_histograms[type].increment_bytes(obj->Size());
1073
1074 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1075 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1076 }
1077
1078 return obj->Size();
1079}
1080
1081
1082static void ReportHistogram(bool print_spill) {
1083 PrintF("\n Object Histogram:\n");
1084 for (int i = 0; i <= LAST_TYPE; i++) {
1085 if (heap_histograms[i].number() > 0) {
1086 PrintF(" %-33s%10d (%10d bytes)\n",
1087 heap_histograms[i].name(),
1088 heap_histograms[i].number(),
1089 heap_histograms[i].bytes());
1090 }
1091 }
1092 PrintF("\n");
1093
1094 // Summarize string types.
1095 int string_number = 0;
1096 int string_bytes = 0;
1097#define INCREMENT(type, size, name) \
1098 string_number += heap_histograms[type].number(); \
1099 string_bytes += heap_histograms[type].bytes();
1100 STRING_TYPE_LIST(INCREMENT)
1101#undef INCREMENT
1102 if (string_number > 0) {
1103 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1104 string_bytes);
1105 }
1106
1107 if (FLAG_collect_heap_spill_statistics && print_spill) {
1108 js_spill_information.Print();
1109 }
1110}
1111#endif // DEBUG
1112
1113
1114// Support for statistics gathering for --heap-stats and --log-gc.
1115#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1116void NewSpace::ClearHistograms() {
1117 for (int i = 0; i <= LAST_TYPE; i++) {
1118 allocated_histogram_[i].clear();
1119 promoted_histogram_[i].clear();
1120 }
1121}
1122
1123// Because the copying collector does not touch garbage objects, we iterate
1124// the new space before a collection to get a histogram of allocated objects.
1125// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1126// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1127// flag is set.
1128void NewSpace::CollectStatistics() {
1129 ClearHistograms();
1130 SemiSpaceIterator it(this);
1131 while (it.has_next()) RecordAllocation(it.next());
1132}
1133
1134
1135#ifdef ENABLE_LOGGING_AND_PROFILING
1136static void DoReportStatistics(HistogramInfo* info, const char* description) {
1137 LOG(HeapSampleBeginEvent("NewSpace", description));
1138 // Lump all the string types together.
1139 int string_number = 0;
1140 int string_bytes = 0;
1141#define INCREMENT(type, size, name) \
1142 string_number += info[type].number(); \
1143 string_bytes += info[type].bytes();
1144 STRING_TYPE_LIST(INCREMENT)
1145#undef INCREMENT
1146 if (string_number > 0) {
1147 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1148 }
1149
1150 // Then do the other types.
1151 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1152 if (info[i].number() > 0) {
1153 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1154 info[i].bytes()));
1155 }
1156 }
1157 LOG(HeapSampleEndEvent("NewSpace", description));
1158}
1159#endif // ENABLE_LOGGING_AND_PROFILING
1160
1161
1162void NewSpace::ReportStatistics() {
1163#ifdef DEBUG
1164 if (FLAG_heap_stats) {
1165 float pct = static_cast<float>(Available()) / Capacity();
1166 PrintF(" capacity: %d, available: %d, %%%d\n",
1167 Capacity(), Available(), static_cast<int>(pct*100));
1168 PrintF("\n Object Histogram:\n");
1169 for (int i = 0; i <= LAST_TYPE; i++) {
1170 if (allocated_histogram_[i].number() > 0) {
1171 PrintF(" %-33s%10d (%10d bytes)\n",
1172 allocated_histogram_[i].name(),
1173 allocated_histogram_[i].number(),
1174 allocated_histogram_[i].bytes());
1175 }
1176 }
1177 PrintF("\n");
1178 }
1179#endif // DEBUG
1180
1181#ifdef ENABLE_LOGGING_AND_PROFILING
1182 if (FLAG_log_gc) {
1183 DoReportStatistics(allocated_histogram_, "allocated");
1184 DoReportStatistics(promoted_histogram_, "promoted");
1185 }
1186#endif // ENABLE_LOGGING_AND_PROFILING
1187}
1188
1189
1190void NewSpace::RecordAllocation(HeapObject* obj) {
1191 InstanceType type = obj->map()->instance_type();
1192 ASSERT(0 <= type && type <= LAST_TYPE);
1193 allocated_histogram_[type].increment_number(1);
1194 allocated_histogram_[type].increment_bytes(obj->Size());
1195}
1196
1197
1198void NewSpace::RecordPromotion(HeapObject* obj) {
1199 InstanceType type = obj->map()->instance_type();
1200 ASSERT(0 <= type && type <= LAST_TYPE);
1201 promoted_histogram_[type].increment_number(1);
1202 promoted_histogram_[type].increment_bytes(obj->Size());
1203}
1204#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1205
1206
1207// -----------------------------------------------------------------------------
1208// Free lists for old object spaces implementation
1209
1210void FreeListNode::set_size(int size_in_bytes) {
1211 ASSERT(size_in_bytes > 0);
1212 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1213
1214 // We write a map and possibly size information to the block. If the block
1215 // is big enough to be a ByteArray with at least one extra word (the next
1216 // pointer), we set its map to be the byte array map and its size to an
1217 // appropriate array length for the desired size from HeapObject::Size().
1218 // If the block is too small (eg, one or two words), to hold both a size
1219 // field and a next pointer, we give it a filler map that gives it the
1220 // correct size.
1221 if (size_in_bytes > Array::kHeaderSize) {
1222 set_map(Heap::byte_array_map());
1223 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1224 } else if (size_in_bytes == kPointerSize) {
1225 set_map(Heap::one_word_filler_map());
1226 } else if (size_in_bytes == 2 * kPointerSize) {
1227 set_map(Heap::two_word_filler_map());
1228 } else {
1229 UNREACHABLE();
1230 }
kasper.lund7276f142008-07-30 08:49:36 +00001231 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001232}
1233
1234
1235Address FreeListNode::next() {
1236 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001237 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001238 return Memory::Address_at(address() + kNextOffset);
1239}
1240
1241
1242void FreeListNode::set_next(Address next) {
1243 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001244 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001245 Memory::Address_at(address() + kNextOffset) = next;
1246}
1247
1248
1249OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1250 Reset();
1251}
1252
1253
1254void OldSpaceFreeList::Reset() {
1255 available_ = 0;
1256 for (int i = 0; i < kFreeListsLength; i++) {
1257 free_[i].head_node_ = NULL;
1258 }
1259 needs_rebuild_ = false;
1260 finger_ = kHead;
1261 free_[kHead].next_size_ = kEnd;
1262}
1263
1264
1265void OldSpaceFreeList::RebuildSizeList() {
1266 ASSERT(needs_rebuild_);
1267 int cur = kHead;
1268 for (int i = cur + 1; i < kFreeListsLength; i++) {
1269 if (free_[i].head_node_ != NULL) {
1270 free_[cur].next_size_ = i;
1271 cur = i;
1272 }
1273 }
1274 free_[cur].next_size_ = kEnd;
1275 needs_rebuild_ = false;
1276}
1277
1278
1279int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1280#ifdef DEBUG
1281 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1282 Memory::Address_at(start + i) = kZapValue;
1283 }
1284#endif
1285 FreeListNode* node = FreeListNode::FromAddress(start);
1286 node->set_size(size_in_bytes);
1287
1288 // Early return to drop too-small blocks on the floor (one or two word
1289 // blocks cannot hold a map pointer, a size field, and a pointer to the
1290 // next block in the free list).
1291 if (size_in_bytes < kMinBlockSize) {
1292 return size_in_bytes;
1293 }
1294
1295 // Insert other blocks at the head of an exact free list.
1296 int index = size_in_bytes >> kPointerSizeLog2;
1297 node->set_next(free_[index].head_node_);
1298 free_[index].head_node_ = node->address();
1299 available_ += size_in_bytes;
1300 needs_rebuild_ = true;
1301 return 0;
1302}
1303
1304
1305Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1306 ASSERT(0 < size_in_bytes);
1307 ASSERT(size_in_bytes <= kMaxBlockSize);
1308 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1309
1310 if (needs_rebuild_) RebuildSizeList();
1311 int index = size_in_bytes >> kPointerSizeLog2;
1312 // Check for a perfect fit.
1313 if (free_[index].head_node_ != NULL) {
1314 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1315 // If this was the last block of its size, remove the size.
1316 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1317 available_ -= size_in_bytes;
1318 *wasted_bytes = 0;
1319 return node;
1320 }
1321 // Search the size list for the best fit.
1322 int prev = finger_ < index ? finger_ : kHead;
1323 int cur = FindSize(index, &prev);
1324 ASSERT(index < cur);
1325 if (cur == kEnd) {
1326 // No large enough size in list.
1327 *wasted_bytes = 0;
1328 return Failure::RetryAfterGC(size_in_bytes, owner_);
1329 }
1330 int rem = cur - index;
1331 int rem_bytes = rem << kPointerSizeLog2;
1332 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001333 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001334 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1335 size_in_bytes);
1336 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1337 // to avoid many redundant tests and calls to Insert/RemoveSize.
1338 if (prev < rem) {
1339 // Simple case: insert rem between prev and cur.
1340 finger_ = prev;
1341 free_[prev].next_size_ = rem;
1342 // If this was the last block of size cur, remove the size.
1343 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1344 free_[rem].next_size_ = free_[cur].next_size_;
1345 } else {
1346 free_[rem].next_size_ = cur;
1347 }
1348 // Add the remainder block.
1349 rem_node->set_size(rem_bytes);
1350 rem_node->set_next(free_[rem].head_node_);
1351 free_[rem].head_node_ = rem_node->address();
1352 } else {
1353 // If this was the last block of size cur, remove the size.
1354 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1355 finger_ = prev;
1356 free_[prev].next_size_ = free_[cur].next_size_;
1357 }
1358 if (rem_bytes < kMinBlockSize) {
1359 // Too-small remainder is wasted.
1360 rem_node->set_size(rem_bytes);
1361 available_ -= size_in_bytes + rem_bytes;
1362 *wasted_bytes = rem_bytes;
1363 return cur_node;
1364 }
1365 // Add the remainder block and, if needed, insert its size.
1366 rem_node->set_size(rem_bytes);
1367 rem_node->set_next(free_[rem].head_node_);
1368 free_[rem].head_node_ = rem_node->address();
1369 if (rem_node->next() == NULL) InsertSize(rem);
1370 }
1371 available_ -= size_in_bytes;
1372 *wasted_bytes = 0;
1373 return cur_node;
1374}
1375
1376
kasper.lund7276f142008-07-30 08:49:36 +00001377#ifdef DEBUG
1378bool OldSpaceFreeList::Contains(FreeListNode* node) {
1379 for (int i = 0; i < kFreeListsLength; i++) {
1380 Address cur_addr = free_[i].head_node_;
1381 while (cur_addr != NULL) {
1382 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1383 if (cur_node == node) return true;
1384 cur_addr = cur_node->next();
1385 }
1386 }
1387 return false;
1388}
1389#endif
1390
1391
1392MapSpaceFreeList::MapSpaceFreeList(AllocationSpace owner) {
1393 owner_ = owner;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001394 Reset();
1395}
1396
1397
1398void MapSpaceFreeList::Reset() {
1399 available_ = 0;
1400 head_ = NULL;
1401}
1402
1403
1404void MapSpaceFreeList::Free(Address start) {
1405#ifdef DEBUG
1406 for (int i = 0; i < Map::kSize; i += kPointerSize) {
1407 Memory::Address_at(start + i) = kZapValue;
1408 }
1409#endif
1410 FreeListNode* node = FreeListNode::FromAddress(start);
1411 node->set_size(Map::kSize);
1412 node->set_next(head_);
1413 head_ = node->address();
1414 available_ += Map::kSize;
1415}
1416
1417
1418Object* MapSpaceFreeList::Allocate() {
1419 if (head_ == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00001420 return Failure::RetryAfterGC(Map::kSize, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 }
1422
1423 FreeListNode* node = FreeListNode::FromAddress(head_);
1424 head_ = node->next();
1425 available_ -= Map::kSize;
1426 return node;
1427}
1428
1429
1430// -----------------------------------------------------------------------------
1431// OldSpace implementation
1432
1433void OldSpace::PrepareForMarkCompact(bool will_compact) {
1434 if (will_compact) {
1435 // Reset relocation info. During a compacting collection, everything in
1436 // the space is considered 'available' and we will rediscover live data
1437 // and waste during the collection.
1438 MCResetRelocationInfo();
1439 mc_end_of_relocation_ = bottom();
1440 ASSERT(Available() == Capacity());
1441 } else {
1442 // During a non-compacting collection, everything below the linear
1443 // allocation pointer is considered allocated (everything above is
1444 // available) and we will rediscover available and wasted bytes during
1445 // the collection.
1446 accounting_stats_.AllocateBytes(free_list_.available());
1447 accounting_stats_.FillWastedBytes(Waste());
1448 }
1449
kasper.lund7276f142008-07-30 08:49:36 +00001450 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001451 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001452}
1453
1454
1455void OldSpace::MCAdjustRelocationEnd(Address address, int size_in_bytes) {
1456 ASSERT(Contains(address));
1457 Address current_top = mc_end_of_relocation_;
1458 Page* current_page = Page::FromAllocationTop(current_top);
1459
1460 // No more objects relocated to this page? Move to the next.
1461 ASSERT(current_top <= current_page->mc_relocation_top);
1462 if (current_top == current_page->mc_relocation_top) {
1463 // The space should already be properly expanded.
1464 Page* next_page = current_page->next_page();
1465 CHECK(next_page->is_valid());
1466 mc_end_of_relocation_ = next_page->ObjectAreaStart();
1467 }
1468 ASSERT(mc_end_of_relocation_ == address);
1469 mc_end_of_relocation_ += size_in_bytes;
1470}
1471
1472
1473void OldSpace::MCCommitRelocationInfo() {
1474 // Update fast allocation info.
1475 allocation_info_.top = mc_forwarding_info_.top;
1476 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001477 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001478
1479 // The space is compacted and we haven't yet built free lists or
1480 // wasted any space.
1481 ASSERT(Waste() == 0);
1482 ASSERT(AvailableFree() == 0);
1483
1484 // Build the free list for the space.
1485 int computed_size = 0;
1486 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1487 while (it.has_next()) {
1488 Page* p = it.next();
1489 // Space below the relocation pointer is allocated.
1490 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1491 if (it.has_next()) {
1492 // Free the space at the top of the page. We cannot use
1493 // p->mc_relocation_top after the call to Free (because Free will clear
1494 // remembered set bits).
1495 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1496 if (extra_size > 0) {
1497 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1498 // The bytes we have just "freed" to add to the free list were
1499 // already accounted as available.
1500 accounting_stats_.WasteBytes(wasted_bytes);
1501 }
1502 }
1503 }
1504
1505 // Make sure the computed size - based on the used portion of the pages in
1506 // use - matches the size obtained while computing forwarding addresses.
1507 ASSERT(computed_size == Size());
1508}
1509
1510
kasper.lund7276f142008-07-30 08:49:36 +00001511// Slow case for normal allocation. Try in order: (1) allocate in the next
1512// page in the space, (2) allocate off the space's free list, (3) expand the
1513// space, (4) fail.
1514HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1515 // Linear allocation in this space has failed. If there is another page
1516 // in the space, move to that page and allocate there. This allocation
1517 // should succeed (size_in_bytes should not be greater than a page's
1518 // object area size).
1519 Page* current_page = TopPageOf(allocation_info_);
1520 if (current_page->next_page()->is_valid()) {
1521 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522 }
kasper.lund7276f142008-07-30 08:49:36 +00001523
1524 // There is no next page in this space. Try free list allocation.
1525 int wasted_bytes;
1526 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1527 accounting_stats_.WasteBytes(wasted_bytes);
1528 if (!result->IsFailure()) {
1529 accounting_stats_.AllocateBytes(size_in_bytes);
1530 return HeapObject::cast(result);
1531 }
1532
1533 // Free list allocation failed and there is no next page. Try to expand
1534 // the space and allocate in the new next page.
1535 ASSERT(!current_page->next_page()->is_valid());
1536 if (Expand(current_page)) {
1537 return AllocateInNextPage(current_page, size_in_bytes);
1538 }
1539
1540 // Finally, fail.
1541 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001542}
1543
1544
kasper.lund7276f142008-07-30 08:49:36 +00001545// Add the block at the top of the page to the space's free list, set the
1546// allocation info to the next page (assumed to be one), and allocate
1547// linearly there.
1548HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1549 int size_in_bytes) {
1550 ASSERT(current_page->next_page()->is_valid());
1551 // Add the block at the top of this page to the free list.
1552 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1553 if (free_size > 0) {
1554 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1555 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001556 }
kasper.lund7276f142008-07-30 08:49:36 +00001557 SetAllocationInfo(&allocation_info_, current_page->next_page());
1558 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559}
1560
1561
1562#ifdef DEBUG
1563// We do not assume that the PageIterator works, because it depends on the
1564// invariants we are checking during verification.
1565void OldSpace::Verify() {
1566 // The allocation pointer should be valid, and it should be in a page in the
1567 // space.
kasper.lund7276f142008-07-30 08:49:36 +00001568 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001569 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
1570 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
1571
1572 // Loop over all the pages.
1573 bool above_allocation_top = false;
1574 Page* current_page = first_page_;
1575 while (current_page->is_valid()) {
1576 if (above_allocation_top) {
1577 // We don't care what's above the allocation top.
1578 } else {
1579 // Unless this is the last page in the space containing allocated
1580 // objects, the allocation top should be at the object area end.
1581 Address top = current_page->AllocationTop();
1582 if (current_page == top_page) {
1583 ASSERT(top == allocation_info_.top);
1584 // The next page will be above the allocation top.
1585 above_allocation_top = true;
1586 } else {
1587 ASSERT(top == current_page->ObjectAreaEnd());
1588 }
1589
1590 // It should be packed with objects from the bottom to the top.
1591 Address current = current_page->ObjectAreaStart();
1592 while (current < top) {
1593 HeapObject* object = HeapObject::FromAddress(current);
1594
1595 // The first word should be a map, and we expect all map pointers to
1596 // be in map space.
1597 Map* map = object->map();
1598 ASSERT(map->IsMap());
1599 ASSERT(Heap::map_space()->Contains(map));
1600
1601 // The object should not be a map.
1602 ASSERT(!object->IsMap());
1603
1604 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001605 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001606
1607 // All the interior pointers should be contained in the heap and have
1608 // their remembered set bits set if they point to new space. Code
1609 // objects do not have remembered set bits that we care about.
1610 VerifyPointersAndRSetVisitor rset_visitor;
1611 VerifyPointersVisitor no_rset_visitor;
1612 int size = object->Size();
1613 if (object->IsCode()) {
1614 Code::cast(object)->ConvertICTargetsFromAddressToObject();
1615 object->IterateBody(map->instance_type(), size, &no_rset_visitor);
1616 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
1617 } else {
1618 object->IterateBody(map->instance_type(), size, &rset_visitor);
1619 }
1620
1621 current += size;
1622 }
1623
1624 // The allocation pointer should not be in the middle of an object.
1625 ASSERT(current == top);
1626 }
1627
1628 current_page = current_page->next_page();
1629 }
1630}
1631
1632
1633struct CommentStatistic {
1634 const char* comment;
1635 int size;
1636 int count;
1637 void Clear() {
1638 comment = NULL;
1639 size = 0;
1640 count = 0;
1641 }
1642};
1643
1644
1645// must be small, since an iteration is used for lookup
1646const int kMaxComments = 64;
1647static CommentStatistic comments_statistics[kMaxComments+1];
1648
1649
1650void PagedSpace::ReportCodeStatistics() {
1651 ReportCodeKindStatistics();
1652 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1653 "count (average)\"):\n");
1654 for (int i = 0; i <= kMaxComments; i++) {
1655 const CommentStatistic& cs = comments_statistics[i];
1656 if (cs.size > 0) {
1657 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1658 cs.size/cs.count);
1659 }
1660 }
1661 PrintF("\n");
1662}
1663
1664
1665void PagedSpace::ResetCodeStatistics() {
1666 ClearCodeKindStatistics();
1667 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1668 comments_statistics[kMaxComments].comment = "Unknown";
1669 comments_statistics[kMaxComments].size = 0;
1670 comments_statistics[kMaxComments].count = 0;
1671}
1672
1673
1674// Adds comment to 'comment_statistics' table. Performance OK sa long as
1675// 'kMaxComments' is small
1676static void EnterComment(const char* comment, int delta) {
1677 // Do not count empty comments
1678 if (delta <= 0) return;
1679 CommentStatistic* cs = &comments_statistics[kMaxComments];
1680 // Search for a free or matching entry in 'comments_statistics': 'cs'
1681 // points to result.
1682 for (int i = 0; i < kMaxComments; i++) {
1683 if (comments_statistics[i].comment == NULL) {
1684 cs = &comments_statistics[i];
1685 cs->comment = comment;
1686 break;
1687 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1688 cs = &comments_statistics[i];
1689 break;
1690 }
1691 }
1692 // Update entry for 'comment'
1693 cs->size += delta;
1694 cs->count += 1;
1695}
1696
1697
1698// Call for each nested comment start (start marked with '[ xxx', end marked
1699// with ']'. RelocIterator 'it' must point to a comment reloc info.
1700static void CollectCommentStatistics(RelocIterator* it) {
1701 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001702 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001703 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1704 if (tmp[0] != '[') {
1705 // Not a nested comment; skip
1706 return;
1707 }
1708
1709 // Search for end of nested comment or a new nested comment
1710 const char* const comment_txt =
1711 reinterpret_cast<const char*>(it->rinfo()->data());
1712 const byte* prev_pc = it->rinfo()->pc();
1713 int flat_delta = 0;
1714 it->next();
1715 while (true) {
1716 // All nested comments must be terminated properly, and therefore exit
1717 // from loop.
1718 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001719 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720 const char* const txt =
1721 reinterpret_cast<const char*>(it->rinfo()->data());
1722 flat_delta += it->rinfo()->pc() - prev_pc;
1723 if (txt[0] == ']') break; // End of nested comment
1724 // A new comment
1725 CollectCommentStatistics(it);
1726 // Skip code that was covered with previous comment
1727 prev_pc = it->rinfo()->pc();
1728 }
1729 it->next();
1730 }
1731 EnterComment(comment_txt, flat_delta);
1732}
1733
1734
1735// Collects code size statistics:
1736// - by code kind
1737// - by code comment
1738void PagedSpace::CollectCodeStatistics() {
1739 HeapObjectIterator obj_it(this);
1740 while (obj_it.has_next()) {
1741 HeapObject* obj = obj_it.next();
1742 if (obj->IsCode()) {
1743 Code* code = Code::cast(obj);
1744 code_kind_statistics[code->kind()] += code->Size();
1745 RelocIterator it(code);
1746 int delta = 0;
1747 const byte* prev_pc = code->instruction_start();
1748 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001749 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001750 delta += it.rinfo()->pc() - prev_pc;
1751 CollectCommentStatistics(&it);
1752 prev_pc = it.rinfo()->pc();
1753 }
1754 it.next();
1755 }
1756
1757 ASSERT(code->instruction_start() <= prev_pc &&
1758 prev_pc <= code->relocation_start());
1759 delta += code->relocation_start() - prev_pc;
1760 EnterComment("NoComment", delta);
1761 }
1762 }
1763}
1764
1765
1766void OldSpace::ReportStatistics() {
1767 int pct = Available() * 100 / Capacity();
1768 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1769 Capacity(), Waste(), Available(), pct);
1770
1771 // Report remembered set statistics.
1772 int rset_marked_pointers = 0;
1773 int rset_marked_arrays = 0;
1774 int rset_marked_array_elements = 0;
1775 int cross_gen_pointers = 0;
1776 int cross_gen_array_elements = 0;
1777
1778 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1779 while (page_it.has_next()) {
1780 Page* p = page_it.next();
1781
1782 for (Address rset_addr = p->RSetStart();
1783 rset_addr < p->RSetEnd();
1784 rset_addr += kIntSize) {
1785 int rset = Memory::int_at(rset_addr);
1786 if (rset != 0) {
1787 // Bits were set
1788 int intoff = rset_addr - p->address();
1789 int bitoff = 0;
1790 for (; bitoff < kBitsPerInt; ++bitoff) {
1791 if ((rset & (1 << bitoff)) != 0) {
1792 int bitpos = intoff*kBitsPerByte + bitoff;
1793 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1794 Object** obj = reinterpret_cast<Object**>(slot);
1795 if (*obj == Heap::fixed_array_map()) {
1796 rset_marked_arrays++;
1797 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1798
1799 rset_marked_array_elements += fa->length();
1800 // Manually inline FixedArray::IterateBody
1801 Address elm_start = slot + FixedArray::kHeaderSize;
1802 Address elm_stop = elm_start + fa->length() * kPointerSize;
1803 for (Address elm_addr = elm_start;
1804 elm_addr < elm_stop; elm_addr += kPointerSize) {
1805 // Filter non-heap-object pointers
1806 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1807 if (Heap::InNewSpace(*elm_p))
1808 cross_gen_array_elements++;
1809 }
1810 } else {
1811 rset_marked_pointers++;
1812 if (Heap::InNewSpace(*obj))
1813 cross_gen_pointers++;
1814 }
1815 }
1816 }
1817 }
1818 }
1819 }
1820
1821 pct = rset_marked_pointers == 0 ?
1822 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1823 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1824 rset_marked_pointers, cross_gen_pointers, pct);
1825 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1826 PrintF(" elements %d, ", rset_marked_array_elements);
1827 pct = rset_marked_array_elements == 0 ? 0
1828 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1829 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1830 PrintF(" total rset-marked bits %d\n",
1831 (rset_marked_pointers + rset_marked_arrays));
1832 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1833 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1834 (rset_marked_pointers + rset_marked_array_elements);
1835 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1836 (rset_marked_pointers + rset_marked_array_elements),
1837 (cross_gen_pointers + cross_gen_array_elements),
1838 pct);
1839
1840 ClearHistograms();
1841 HeapObjectIterator obj_it(this);
1842 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1843 ReportHistogram(true);
1844}
1845
1846
1847// Dump the range of remembered set words between [start, end) corresponding
1848// to the pointers starting at object_p. The allocation_top is an object
1849// pointer which should not be read past. This is important for large object
1850// pages, where some bits in the remembered set range do not correspond to
1851// allocated addresses.
1852static void PrintRSetRange(Address start, Address end, Object** object_p,
1853 Address allocation_top) {
1854 Address rset_address = start;
1855
1856 // If the range starts on on odd numbered word (eg, for large object extra
1857 // remembered set ranges), print some spaces.
1858 if ((reinterpret_cast<uint32_t>(start) / kIntSize) % 2 == 1) {
1859 PrintF(" ");
1860 }
1861
1862 // Loop over all the words in the range.
1863 while (rset_address < end) {
1864 uint32_t rset_word = Memory::uint32_at(rset_address);
1865 int bit_position = 0;
1866
1867 // Loop over all the bits in the word.
1868 while (bit_position < kBitsPerInt) {
1869 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1870 // Print a bar at the allocation pointer.
1871 PrintF("|");
1872 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1873 // Do not dereference object_p past the allocation pointer.
1874 PrintF("#");
1875 } else if ((rset_word & (1 << bit_position)) == 0) {
1876 // Print a dot for zero bits.
1877 PrintF(".");
1878 } else if (Heap::InNewSpace(*object_p)) {
1879 // Print an X for one bits for pointers to new space.
1880 PrintF("X");
1881 } else {
1882 // Print a circle for one bits for pointers to old space.
1883 PrintF("o");
1884 }
1885
1886 // Print a space after every 8th bit except the last.
1887 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1888 PrintF(" ");
1889 }
1890
1891 // Advance to next bit.
1892 bit_position++;
1893 object_p++;
1894 }
1895
1896 // Print a newline after every odd numbered word, otherwise a space.
1897 if ((reinterpret_cast<uint32_t>(rset_address) / kIntSize) % 2 == 1) {
1898 PrintF("\n");
1899 } else {
1900 PrintF(" ");
1901 }
1902
1903 // Advance to next remembered set word.
1904 rset_address += kIntSize;
1905 }
1906}
1907
1908
1909void PagedSpace::DoPrintRSet(const char* space_name) {
1910 PageIterator it(this, PageIterator::PAGES_IN_USE);
1911 while (it.has_next()) {
1912 Page* p = it.next();
1913 PrintF("%s page 0x%x:\n", space_name, p);
1914 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
1915 reinterpret_cast<Object**>(p->ObjectAreaStart()),
1916 p->AllocationTop());
1917 PrintF("\n");
1918 }
1919}
1920
1921
1922void OldSpace::PrintRSet() { DoPrintRSet("old"); }
1923#endif
1924
1925// -----------------------------------------------------------------------------
1926// MapSpace implementation
1927
1928void MapSpace::PrepareForMarkCompact(bool will_compact) {
1929 if (will_compact) {
1930 // Reset relocation info.
1931 MCResetRelocationInfo();
1932
1933 // Initialize map index entry.
1934 int page_count = 0;
1935 PageIterator it(this, PageIterator::ALL_PAGES);
1936 while (it.has_next()) {
1937 ASSERT_MAP_PAGE_INDEX(page_count);
1938
1939 Page* p = it.next();
1940 ASSERT(p->mc_page_index == page_count);
1941
1942 page_addresses_[page_count++] = p->address();
1943 }
1944
1945 // During a compacting collection, everything in the space is considered
1946 // 'available' (set by the call to MCResetRelocationInfo) and we will
1947 // rediscover live and wasted bytes during the collection.
1948 ASSERT(Available() == Capacity());
1949 } else {
1950 // During a non-compacting collection, everything below the linear
1951 // allocation pointer except wasted top-of-page blocks is considered
1952 // allocated and we will rediscover available bytes during the
1953 // collection.
1954 accounting_stats_.AllocateBytes(free_list_.available());
1955 }
1956
kasper.lund7276f142008-07-30 08:49:36 +00001957 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001958 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001959}
1960
1961
1962void MapSpace::MCCommitRelocationInfo() {
1963 // Update fast allocation info.
1964 allocation_info_.top = mc_forwarding_info_.top;
1965 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001966 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001967
1968 // The space is compacted and we haven't yet wasted any space.
1969 ASSERT(Waste() == 0);
1970
1971 // Update allocation_top of each page in use and compute waste.
1972 int computed_size = 0;
1973 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1974 while (it.has_next()) {
1975 Page* page = it.next();
1976 Address page_top = page->AllocationTop();
1977 computed_size += page_top - page->ObjectAreaStart();
1978 if (it.has_next()) {
1979 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
1980 }
1981 }
1982
1983 // Make sure the computed size - based on the used portion of the
1984 // pages in use - matches the size we adjust during allocation.
1985 ASSERT(computed_size == Size());
1986}
1987
1988
kasper.lund7276f142008-07-30 08:49:36 +00001989// Slow case for normal allocation. Try in order: (1) allocate in the next
1990// page in the space, (2) allocate off the space's free list, (3) expand the
1991// space, (4) fail.
1992HeapObject* MapSpace::SlowAllocateRaw(int size_in_bytes) {
1993 // Linear allocation in this space has failed. If there is another page
1994 // in the space, move to that page and allocate there. This allocation
1995 // should succeed.
1996 Page* current_page = TopPageOf(allocation_info_);
1997 if (current_page->next_page()->is_valid()) {
1998 return AllocateInNextPage(current_page, size_in_bytes);
1999 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002000
kasper.lund7276f142008-07-30 08:49:36 +00002001 // There is no next page in this space. Try free list allocation. The
2002 // map space free list implicitly assumes that all free blocks are map
2003 // sized.
2004 if (size_in_bytes == Map::kSize) {
2005 Object* result = free_list_.Allocate();
2006 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002007 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002008 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002009 }
2010 }
kasper.lund7276f142008-07-30 08:49:36 +00002011
2012 // Free list allocation failed and there is no next page. Try to expand
2013 // the space and allocate in the new next page.
2014 ASSERT(!current_page->next_page()->is_valid());
2015 if (Expand(current_page)) {
2016 return AllocateInNextPage(current_page, size_in_bytes);
2017 }
2018
2019 // Finally, fail.
2020 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002021}
2022
2023
kasper.lund7276f142008-07-30 08:49:36 +00002024// Move to the next page (there is assumed to be one) and allocate there.
2025// The top of page block is always wasted, because it is too small to hold a
2026// map.
2027HeapObject* MapSpace::AllocateInNextPage(Page* current_page,
2028 int size_in_bytes) {
2029 ASSERT(current_page->next_page()->is_valid());
2030 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == kPageExtra);
2031 accounting_stats_.WasteBytes(kPageExtra);
2032 SetAllocationInfo(&allocation_info_, current_page->next_page());
2033 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002034}
2035
2036
2037#ifdef DEBUG
2038// We do not assume that the PageIterator works, because it depends on the
2039// invariants we are checking during verification.
2040void MapSpace::Verify() {
2041 // The allocation pointer should be valid, and it should be in a page in the
2042 // space.
kasper.lund7276f142008-07-30 08:49:36 +00002043 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002044 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
2045 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
2046
2047 // Loop over all the pages.
2048 bool above_allocation_top = false;
2049 Page* current_page = first_page_;
2050 while (current_page->is_valid()) {
2051 if (above_allocation_top) {
2052 // We don't care what's above the allocation top.
2053 } else {
2054 // Unless this is the last page in the space containing allocated
2055 // objects, the allocation top should be at a constant offset from the
2056 // object area end.
2057 Address top = current_page->AllocationTop();
2058 if (current_page == top_page) {
2059 ASSERT(top == allocation_info_.top);
2060 // The next page will be above the allocation top.
2061 above_allocation_top = true;
2062 } else {
2063 ASSERT(top == current_page->ObjectAreaEnd() - kPageExtra);
2064 }
2065
2066 // It should be packed with objects from the bottom to the top.
2067 Address current = current_page->ObjectAreaStart();
2068 while (current < top) {
2069 HeapObject* object = HeapObject::FromAddress(current);
2070
2071 // The first word should be a map, and we expect all map pointers to
2072 // be in map space.
2073 Map* map = object->map();
2074 ASSERT(map->IsMap());
2075 ASSERT(Heap::map_space()->Contains(map));
2076
2077 // The object should be a map or a byte array.
2078 ASSERT(object->IsMap() || object->IsByteArray());
2079
2080 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002081 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002082
2083 // All the interior pointers should be contained in the heap and
2084 // have their remembered set bits set if they point to new space.
2085 VerifyPointersAndRSetVisitor visitor;
2086 int size = object->Size();
2087 object->IterateBody(map->instance_type(), size, &visitor);
2088
2089 current += size;
2090 }
2091
2092 // The allocation pointer should not be in the middle of an object.
2093 ASSERT(current == top);
2094 }
2095
2096 current_page = current_page->next_page();
2097 }
2098}
2099
2100
2101void MapSpace::ReportStatistics() {
2102 int pct = Available() * 100 / Capacity();
2103 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2104 Capacity(), Waste(), Available(), pct);
2105
2106 // Report remembered set statistics.
2107 int rset_marked_pointers = 0;
2108 int cross_gen_pointers = 0;
2109
2110 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2111 while (page_it.has_next()) {
2112 Page* p = page_it.next();
2113
2114 for (Address rset_addr = p->RSetStart();
2115 rset_addr < p->RSetEnd();
2116 rset_addr += kIntSize) {
2117 int rset = Memory::int_at(rset_addr);
2118 if (rset != 0) {
2119 // Bits were set
2120 int intoff = rset_addr - p->address();
2121 int bitoff = 0;
2122 for (; bitoff < kBitsPerInt; ++bitoff) {
2123 if ((rset & (1 << bitoff)) != 0) {
2124 int bitpos = intoff*kBitsPerByte + bitoff;
2125 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2126 Object** obj = reinterpret_cast<Object**>(slot);
2127 rset_marked_pointers++;
2128 if (Heap::InNewSpace(*obj))
2129 cross_gen_pointers++;
2130 }
2131 }
2132 }
2133 }
2134 }
2135
2136 pct = rset_marked_pointers == 0 ?
2137 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2138 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2139 rset_marked_pointers, cross_gen_pointers, pct);
2140
2141 ClearHistograms();
2142 HeapObjectIterator obj_it(this);
2143 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2144 ReportHistogram(false);
2145}
2146
2147
2148void MapSpace::PrintRSet() { DoPrintRSet("map"); }
2149#endif
2150
2151
2152// -----------------------------------------------------------------------------
2153// LargeObjectIterator
2154
2155LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2156 current_ = space->first_chunk_;
2157 size_func_ = NULL;
2158}
2159
2160
2161LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2162 HeapObjectCallback size_func) {
2163 current_ = space->first_chunk_;
2164 size_func_ = size_func;
2165}
2166
2167
2168HeapObject* LargeObjectIterator::next() {
2169 ASSERT(has_next());
2170 HeapObject* object = current_->GetObject();
2171 current_ = current_->next();
2172 return object;
2173}
2174
2175
2176// -----------------------------------------------------------------------------
2177// LargeObjectChunk
2178
2179LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002180 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002181 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002182 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002183 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2184 chunk_size,
2185 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002186 if (mem == NULL) return NULL;
2187 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2188 if (*chunk_size < requested) {
2189 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2190 LOG(DeleteEvent("LargeObjectChunk", mem));
2191 return NULL;
2192 }
2193 return reinterpret_cast<LargeObjectChunk*>(mem);
2194}
2195
2196
2197int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2198 int os_alignment = OS::AllocateAlignment();
2199 if (os_alignment < Page::kPageSize)
2200 size_in_bytes += (Page::kPageSize - os_alignment);
2201 return size_in_bytes + Page::kObjectStartOffset;
2202}
2203
2204// -----------------------------------------------------------------------------
2205// LargeObjectSpace
2206
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002207LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2208 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002209 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002210 size_(0),
2211 page_count_(0) {}
2212
2213
2214bool LargeObjectSpace::Setup() {
2215 first_chunk_ = NULL;
2216 size_ = 0;
2217 page_count_ = 0;
2218 return true;
2219}
2220
2221
2222void LargeObjectSpace::TearDown() {
2223 while (first_chunk_ != NULL) {
2224 LargeObjectChunk* chunk = first_chunk_;
2225 first_chunk_ = first_chunk_->next();
2226 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2227 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2228 }
2229
2230 size_ = 0;
2231 page_count_ = 0;
2232}
2233
2234
2235Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002236 int object_size,
2237 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002238 ASSERT(0 < object_size && object_size <= requested_size);
2239 size_t chunk_size;
2240 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002241 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002242 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002243 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002244 }
2245
2246 size_ += chunk_size;
2247 page_count_++;
2248 chunk->set_next(first_chunk_);
2249 chunk->set_size(chunk_size);
2250 first_chunk_ = chunk;
2251
2252 // Set the object address and size in the page header and clear its
2253 // remembered set.
2254 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2255 Address object_address = page->ObjectAreaStart();
2256 // Clear the low order bit of the second word in the page to flag it as a
2257 // large object page. If the chunk_size happened to be written there, its
2258 // low order bit should already be clear.
2259 ASSERT((chunk_size & 0x1) == 0);
2260 page->is_normal_page &= ~0x1;
2261 page->ClearRSet();
2262 int extra_bytes = requested_size - object_size;
2263 if (extra_bytes > 0) {
2264 // The extra memory for the remembered set should be cleared.
2265 memset(object_address + object_size, 0, extra_bytes);
2266 }
2267
2268 return HeapObject::FromAddress(object_address);
2269}
2270
2271
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002272Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002273 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002274 return AllocateRawInternal(size_in_bytes,
2275 size_in_bytes,
2276 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002277}
2278
2279
2280Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002281 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002282 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002283 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2284 size_in_bytes,
2285 NOT_EXECUTABLE);
2286}
2287
2288
2289Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2290 ASSERT(0 < size_in_bytes);
2291 return AllocateRawInternal(size_in_bytes,
2292 size_in_bytes,
2293 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002294}
2295
2296
2297// GC support
2298Object* LargeObjectSpace::FindObject(Address a) {
2299 for (LargeObjectChunk* chunk = first_chunk_;
2300 chunk != NULL;
2301 chunk = chunk->next()) {
2302 Address chunk_address = chunk->address();
2303 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2304 return chunk->GetObject();
2305 }
2306 }
2307 return Failure::Exception();
2308}
2309
2310
2311void LargeObjectSpace::ClearRSet() {
2312 ASSERT(Page::is_rset_in_use());
2313
2314 LargeObjectIterator it(this);
2315 while (it.has_next()) {
2316 HeapObject* object = it.next();
2317 // We only have code, sequential strings, or fixed arrays in large
2318 // object space, and only fixed arrays need remembered set support.
2319 if (object->IsFixedArray()) {
2320 // Clear the normal remembered set region of the page;
2321 Page* page = Page::FromAddress(object->address());
2322 page->ClearRSet();
2323
2324 // Clear the extra remembered set.
2325 int size = object->Size();
2326 int extra_rset_bytes = ExtraRSetBytesFor(size);
2327 memset(object->address() + size, 0, extra_rset_bytes);
2328 }
2329 }
2330}
2331
2332
2333void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2334 ASSERT(Page::is_rset_in_use());
2335
2336 LargeObjectIterator it(this);
2337 while (it.has_next()) {
2338 // We only have code, sequential strings, or fixed arrays in large
2339 // object space, and only fixed arrays can possibly contain pointers to
2340 // the young generation.
2341 HeapObject* object = it.next();
2342 if (object->IsFixedArray()) {
2343 // Iterate the normal page remembered set range.
2344 Page* page = Page::FromAddress(object->address());
2345 Address object_end = object->address() + object->Size();
2346 Heap::IterateRSetRange(page->ObjectAreaStart(),
2347 Min(page->ObjectAreaEnd(), object_end),
2348 page->RSetStart(),
2349 copy_object_func);
2350
2351 // Iterate the extra array elements.
2352 if (object_end > page->ObjectAreaEnd()) {
2353 Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2354 object_end, copy_object_func);
2355 }
2356 }
2357 }
2358}
2359
2360
2361void LargeObjectSpace::FreeUnmarkedObjects() {
2362 LargeObjectChunk* previous = NULL;
2363 LargeObjectChunk* current = first_chunk_;
2364 while (current != NULL) {
2365 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002366 if (object->IsMarked()) {
2367 object->ClearMark();
2368 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002369 previous = current;
2370 current = current->next();
2371 } else {
2372 Address chunk_address = current->address();
2373 size_t chunk_size = current->size();
2374
2375 // Cut the chunk out from the chunk list.
2376 current = current->next();
2377 if (previous == NULL) {
2378 first_chunk_ = current;
2379 } else {
2380 previous->set_next(current);
2381 }
2382
2383 // Free the chunk.
2384 if (object->IsCode()) {
2385 LOG(CodeDeleteEvent(object->address()));
2386 }
2387 size_ -= chunk_size;
2388 page_count_--;
2389 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2390 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2391 }
2392 }
2393}
2394
2395
2396bool LargeObjectSpace::Contains(HeapObject* object) {
2397 Address address = object->address();
2398 Page* page = Page::FromAddress(address);
2399
2400 SLOW_ASSERT(!page->IsLargeObjectPage()
2401 || !FindObject(address)->IsFailure());
2402
2403 return page->IsLargeObjectPage();
2404}
2405
2406
2407#ifdef DEBUG
2408// We do not assume that the large object iterator works, because it depends
2409// on the invariants we are checking during verification.
2410void LargeObjectSpace::Verify() {
2411 for (LargeObjectChunk* chunk = first_chunk_;
2412 chunk != NULL;
2413 chunk = chunk->next()) {
2414 // Each chunk contains an object that starts at the large object page's
2415 // object area start.
2416 HeapObject* object = chunk->GetObject();
2417 Page* page = Page::FromAddress(object->address());
2418 ASSERT(object->address() == page->ObjectAreaStart());
2419
2420 // The first word should be a map, and we expect all map pointers to be
2421 // in map space.
2422 Map* map = object->map();
2423 ASSERT(map->IsMap());
2424 ASSERT(Heap::map_space()->Contains(map));
2425
2426 // We have only code, sequential strings, fixed arrays, and byte arrays
2427 // in large object space.
2428 ASSERT(object->IsCode() || object->IsSeqString()
2429 || object->IsFixedArray() || object->IsByteArray());
2430
2431 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002432 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002433
2434 // Byte arrays and strings don't have interior pointers.
2435 if (object->IsCode()) {
2436 VerifyPointersVisitor code_visitor;
2437 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2438 object->IterateBody(map->instance_type(),
2439 object->Size(),
2440 &code_visitor);
2441 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2442 } else if (object->IsFixedArray()) {
2443 // We loop over fixed arrays ourselves, rather then using the visitor,
2444 // because the visitor doesn't support the start/offset iteration
2445 // needed for IsRSetSet.
2446 FixedArray* array = FixedArray::cast(object);
2447 for (int j = 0; j < array->length(); j++) {
2448 Object* element = array->get(j);
2449 if (element->IsHeapObject()) {
2450 HeapObject* element_object = HeapObject::cast(element);
2451 ASSERT(Heap::Contains(element_object));
2452 ASSERT(element_object->map()->IsMap());
2453 if (Heap::InNewSpace(element_object)) {
2454 ASSERT(Page::IsRSetSet(object->address(),
2455 FixedArray::kHeaderSize + j * kPointerSize));
2456 }
2457 }
2458 }
2459 }
2460 }
2461}
2462
2463
2464void LargeObjectSpace::Print() {
2465 LargeObjectIterator it(this);
2466 while (it.has_next()) {
2467 it.next()->Print();
2468 }
2469}
2470
2471
2472void LargeObjectSpace::ReportStatistics() {
2473 PrintF(" size: %d\n", size_);
2474 int num_objects = 0;
2475 ClearHistograms();
2476 LargeObjectIterator it(this);
2477 while (it.has_next()) {
2478 num_objects++;
2479 CollectHistogramInfo(it.next());
2480 }
2481
2482 PrintF(" number of objects %d\n", num_objects);
2483 if (num_objects > 0) ReportHistogram(false);
2484}
2485
2486
2487void LargeObjectSpace::CollectCodeStatistics() {
2488 LargeObjectIterator obj_it(this);
2489 while (obj_it.has_next()) {
2490 HeapObject* obj = obj_it.next();
2491 if (obj->IsCode()) {
2492 Code* code = Code::cast(obj);
2493 code_kind_statistics[code->kind()] += code->Size();
2494 }
2495 }
2496}
2497
2498
2499void LargeObjectSpace::PrintRSet() {
2500 LargeObjectIterator it(this);
2501 while (it.has_next()) {
2502 HeapObject* object = it.next();
2503 if (object->IsFixedArray()) {
2504 Page* page = Page::FromAddress(object->address());
2505
2506 Address allocation_top = object->address() + object->Size();
2507 PrintF("large page 0x%x:\n", page);
2508 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2509 reinterpret_cast<Object**>(object->address()),
2510 allocation_top);
2511 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2512 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2513 kBitsPerInt);
2514 PrintF("------------------------------------------------------------"
2515 "-----------\n");
2516 PrintRSetRange(allocation_top,
2517 allocation_top + extra_rset_bits / kBitsPerByte,
2518 reinterpret_cast<Object**>(object->address()
2519 + Page::kObjectAreaSize),
2520 allocation_top);
2521 PrintF("\n");
2522 }
2523 }
2524}
2525#endif // DEBUG
2526
2527} } // namespace v8::internal