blob: e61c6adf60eb01237912e1fe448ef4269863269f [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
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034namespace v8 {
35namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037// For contiguous spaces, top should be in the space (or at the end) and limit
38// should be the end of the space.
39#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000040 ASSERT((space).low() <= (info).top \
41 && (info).top <= (space).high() \
42 && (info).limit == (space).high())
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044
45// ----------------------------------------------------------------------------
46// HeapObjectIterator
47
48HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
49 Initialize(space->bottom(), space->top(), NULL);
50}
51
52
53HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
54 HeapObjectCallback size_func) {
55 Initialize(space->bottom(), space->top(), size_func);
56}
57
58
59HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start) {
60 Initialize(start, space->top(), NULL);
61}
62
63
64HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start,
65 HeapObjectCallback size_func) {
66 Initialize(start, space->top(), size_func);
67}
68
69
70void HeapObjectIterator::Initialize(Address cur, Address end,
71 HeapObjectCallback size_f) {
72 cur_addr_ = cur;
73 end_addr_ = end;
74 end_page_ = Page::FromAllocationTop(end);
75 size_func_ = size_f;
76 Page* p = Page::FromAllocationTop(cur_addr_);
77 cur_limit_ = (p == end_page_) ? end_addr_ : p->AllocationTop();
78
79#ifdef DEBUG
80 Verify();
81#endif
82}
83
84
85bool HeapObjectIterator::HasNextInNextPage() {
86 if (cur_addr_ == end_addr_) return false;
87
88 Page* cur_page = Page::FromAllocationTop(cur_addr_);
89 cur_page = cur_page->next_page();
90 ASSERT(cur_page->is_valid());
91
92 cur_addr_ = cur_page->ObjectAreaStart();
93 cur_limit_ = (cur_page == end_page_) ? end_addr_ : cur_page->AllocationTop();
94
95 ASSERT(cur_addr_ < cur_limit_);
96#ifdef DEBUG
97 Verify();
98#endif
99 return true;
100}
101
102
103#ifdef DEBUG
104void HeapObjectIterator::Verify() {
105 Page* p = Page::FromAllocationTop(cur_addr_);
106 ASSERT(p == Page::FromAllocationTop(cur_limit_));
107 ASSERT(p->Offset(cur_addr_) <= p->Offset(cur_limit_));
108}
109#endif
110
111
112// -----------------------------------------------------------------------------
113// PageIterator
114
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000115PageIterator::PageIterator(PagedSpace* space, Mode mode) : space_(space) {
116 prev_page_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 switch (mode) {
118 case PAGES_IN_USE:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000119 stop_page_ = space->AllocationTopPage();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000120 break;
121 case PAGES_USED_BY_MC:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000122 stop_page_ = space->MCRelocationTopPage();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 break;
124 case ALL_PAGES:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000125#ifdef DEBUG
126 // Verify that the cached last page in the space is actually the
127 // last page.
128 for (Page* p = space->first_page_; p->is_valid(); p = p->next_page()) {
129 if (!p->next_page()->is_valid()) {
130 ASSERT(space->last_page_ == p);
131 }
132 }
133#endif
134 stop_page_ = space->last_page_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000135 break;
136 default:
137 UNREACHABLE();
138 }
139}
140
141
142// -----------------------------------------------------------------------------
143// Page
144
145#ifdef DEBUG
146Page::RSetState Page::rset_state_ = Page::IN_USE;
147#endif
148
149// -----------------------------------------------------------------------------
150// MemoryAllocator
151//
152int MemoryAllocator::capacity_ = 0;
153int MemoryAllocator::size_ = 0;
154
155VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
156
157// 270 is an estimate based on the static default heap size of a pair of 256K
158// semispaces and a 64M old generation.
159const int kEstimatedNumberOfChunks = 270;
160List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
161 kEstimatedNumberOfChunks);
162List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
163int MemoryAllocator::max_nof_chunks_ = 0;
164int MemoryAllocator::top_ = 0;
165
166
167void MemoryAllocator::Push(int free_chunk_id) {
168 ASSERT(max_nof_chunks_ > 0);
169 ASSERT(top_ < max_nof_chunks_);
170 free_chunk_ids_[top_++] = free_chunk_id;
171}
172
173
174int MemoryAllocator::Pop() {
175 ASSERT(top_ > 0);
176 return free_chunk_ids_[--top_];
177}
178
179
180bool MemoryAllocator::Setup(int capacity) {
181 capacity_ = RoundUp(capacity, Page::kPageSize);
182
183 // Over-estimate the size of chunks_ array. It assumes the expansion of old
184 // space is always in the unit of a chunk (kChunkSize) except the last
185 // expansion.
186 //
187 // Due to alignment, allocated space might be one page less than required
188 // number (kPagesPerChunk) of pages for old spaces.
189 //
kasper.lund7276f142008-07-30 08:49:36 +0000190 // Reserve two chunk ids for semispaces, one for map space, one for old
191 // space, and one for code space.
192 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193 if (max_nof_chunks_ > kMaxNofChunks) return false;
194
195 size_ = 0;
196 ChunkInfo info; // uninitialized element.
197 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
198 chunks_.Add(info);
199 free_chunk_ids_.Add(i);
200 }
201 top_ = max_nof_chunks_;
202 return true;
203}
204
205
206void MemoryAllocator::TearDown() {
207 for (int i = 0; i < max_nof_chunks_; i++) {
208 if (chunks_[i].address() != NULL) DeleteChunk(i);
209 }
210 chunks_.Clear();
211 free_chunk_ids_.Clear();
212
213 if (initial_chunk_ != NULL) {
214 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
215 delete initial_chunk_;
216 initial_chunk_ = NULL;
217 }
218
219 ASSERT(top_ == max_nof_chunks_); // all chunks are free
220 top_ = 0;
221 capacity_ = 0;
222 size_ = 0;
223 max_nof_chunks_ = 0;
224}
225
226
227void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000228 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000229 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000230 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
231
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000232 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233 int alloced = *allocated;
234 size_ += alloced;
235 Counters::memory_allocated.Increment(alloced);
236 return mem;
237}
238
239
240void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
241 OS::Free(mem, length);
242 Counters::memory_allocated.Decrement(length);
243 size_ -= length;
244 ASSERT(size_ >= 0);
245}
246
247
248void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
249 ASSERT(initial_chunk_ == NULL);
250
251 initial_chunk_ = new VirtualMemory(requested);
252 CHECK(initial_chunk_ != NULL);
253 if (!initial_chunk_->IsReserved()) {
254 delete initial_chunk_;
255 initial_chunk_ = NULL;
256 return NULL;
257 }
258
259 // We are sure that we have mapped a block of requested addresses.
260 ASSERT(initial_chunk_->size() == requested);
261 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
262 size_ += requested;
263 return initial_chunk_->address();
264}
265
266
267static int PagesInChunk(Address start, size_t size) {
268 // The first page starts on the first page-aligned address from start onward
269 // and the last page ends on the last page-aligned address before
270 // start+size. Page::kPageSize is a power of two so we can divide by
271 // shifting.
272 return (RoundDown(start + size, Page::kPageSize)
273 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
274}
275
276
277Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
278 PagedSpace* owner) {
279 if (requested_pages <= 0) return Page::FromAddress(NULL);
280 size_t chunk_size = requested_pages * Page::kPageSize;
281
282 // There is not enough space to guarantee the desired number pages can be
283 // allocated.
284 if (size_ + static_cast<int>(chunk_size) > capacity_) {
285 // Request as many pages as we can.
286 chunk_size = capacity_ - size_;
287 requested_pages = chunk_size >> Page::kPageSizeBits;
288
289 if (requested_pages <= 0) return Page::FromAddress(NULL);
290 }
kasper.lund7276f142008-07-30 08:49:36 +0000291 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000292 if (chunk == NULL) return Page::FromAddress(NULL);
293 LOG(NewEvent("PagedChunk", chunk, chunk_size));
294
295 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
296 if (*allocated_pages == 0) {
297 FreeRawMemory(chunk, chunk_size);
298 LOG(DeleteEvent("PagedChunk", chunk));
299 return Page::FromAddress(NULL);
300 }
301
302 int chunk_id = Pop();
303 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
304
305 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
306}
307
308
309Page* MemoryAllocator::CommitPages(Address start, size_t size,
310 PagedSpace* owner, int* num_pages) {
311 ASSERT(start != NULL);
312 *num_pages = PagesInChunk(start, size);
313 ASSERT(*num_pages > 0);
314 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000315 ASSERT(InInitialChunk(start));
316 ASSERT(InInitialChunk(start + size - 1));
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000317 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318 return Page::FromAddress(NULL);
319 }
320 Counters::memory_allocated.Increment(size);
321
322 // So long as we correctly overestimated the number of chunks we should not
323 // run out of chunk ids.
324 CHECK(!OutOfChunkIds());
325 int chunk_id = Pop();
326 chunks_[chunk_id].init(start, size, owner);
327 return InitializePagesInChunk(chunk_id, *num_pages, owner);
328}
329
330
kasper.lund7276f142008-07-30 08:49:36 +0000331bool MemoryAllocator::CommitBlock(Address start,
332 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000333 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 ASSERT(start != NULL);
335 ASSERT(size > 0);
336 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000337 ASSERT(InInitialChunk(start));
338 ASSERT(InInitialChunk(start + size - 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339
kasper.lund7276f142008-07-30 08:49:36 +0000340 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 Counters::memory_allocated.Increment(size);
342 return true;
343}
344
345
346Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
347 PagedSpace* owner) {
348 ASSERT(IsValidChunk(chunk_id));
349 ASSERT(pages_in_chunk > 0);
350
351 Address chunk_start = chunks_[chunk_id].address();
352
353 Address low = RoundUp(chunk_start, Page::kPageSize);
354
355#ifdef DEBUG
356 size_t chunk_size = chunks_[chunk_id].size();
357 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
358 ASSERT(pages_in_chunk <=
359 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
360#endif
361
362 Address page_addr = low;
363 for (int i = 0; i < pages_in_chunk; i++) {
364 Page* p = Page::FromAddress(page_addr);
365 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
366 p->is_normal_page = 1;
367 page_addr += Page::kPageSize;
368 }
369
370 // Set the next page of the last page to 0.
371 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
372 last_page->opaque_header = OffsetFrom(0) | chunk_id;
373
374 return Page::FromAddress(low);
375}
376
377
378Page* MemoryAllocator::FreePages(Page* p) {
379 if (!p->is_valid()) return p;
380
381 // Find the first page in the same chunk as 'p'
382 Page* first_page = FindFirstPageInSameChunk(p);
383 Page* page_to_return = Page::FromAddress(NULL);
384
385 if (p != first_page) {
386 // Find the last page in the same chunk as 'prev'.
387 Page* last_page = FindLastPageInSameChunk(p);
388 first_page = GetNextPage(last_page); // first page in next chunk
389
390 // set the next_page of last_page to NULL
391 SetNextPage(last_page, Page::FromAddress(NULL));
392 page_to_return = p; // return 'p' when exiting
393 }
394
395 while (first_page->is_valid()) {
396 int chunk_id = GetChunkId(first_page);
397 ASSERT(IsValidChunk(chunk_id));
398
399 // Find the first page of the next chunk before deleting this chunk.
400 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
401
402 // Free the current chunk.
403 DeleteChunk(chunk_id);
404 }
405
406 return page_to_return;
407}
408
409
410void MemoryAllocator::DeleteChunk(int chunk_id) {
411 ASSERT(IsValidChunk(chunk_id));
412
413 ChunkInfo& c = chunks_[chunk_id];
414
415 // We cannot free a chunk contained in the initial chunk because it was not
416 // allocated with AllocateRawMemory. Instead we uncommit the virtual
417 // memory.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000418 if (InInitialChunk(c.address())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419 // TODO(1240712): VirtualMemory::Uncommit has a return value which
420 // is ignored here.
421 initial_chunk_->Uncommit(c.address(), c.size());
422 Counters::memory_allocated.Decrement(c.size());
423 } else {
424 LOG(DeleteEvent("PagedChunk", c.address()));
425 FreeRawMemory(c.address(), c.size());
426 }
427 c.init(NULL, 0, NULL);
428 Push(chunk_id);
429}
430
431
432Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
433 int chunk_id = GetChunkId(p);
434 ASSERT(IsValidChunk(chunk_id));
435
436 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
437 return Page::FromAddress(low);
438}
439
440
441Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
442 int chunk_id = GetChunkId(p);
443 ASSERT(IsValidChunk(chunk_id));
444
445 Address chunk_start = chunks_[chunk_id].address();
446 size_t chunk_size = chunks_[chunk_id].size();
447
448 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
449 ASSERT(chunk_start <= p->address() && p->address() < high);
450
451 return Page::FromAddress(high - Page::kPageSize);
452}
453
454
455#ifdef DEBUG
456void MemoryAllocator::ReportStatistics() {
457 float pct = static_cast<float>(capacity_ - size_) / capacity_;
458 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
459 capacity_, size_, static_cast<int>(pct*100));
460}
461#endif
462
463
464// -----------------------------------------------------------------------------
465// PagedSpace implementation
466
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000467PagedSpace::PagedSpace(int max_capacity,
468 AllocationSpace id,
469 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000470 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
472 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 accounting_stats_.Clear();
474
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475 allocation_info_.top = NULL;
476 allocation_info_.limit = NULL;
477
478 mc_forwarding_info_.top = NULL;
479 mc_forwarding_info_.limit = NULL;
480}
481
482
483bool PagedSpace::Setup(Address start, size_t size) {
484 if (HasBeenSetup()) return false;
485
486 int num_pages = 0;
487 // Try to use the virtual memory range passed to us. If it is too small to
488 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000489 int pages_in_chunk = PagesInChunk(start, size);
490 if (pages_in_chunk > 0) {
491 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
492 Page::kPageSize * pages_in_chunk,
493 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000494 } else {
495 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
496 max_capacity_ / Page::kObjectAreaSize);
497 first_page_ =
498 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
499 if (!first_page_->is_valid()) return false;
500 }
501
502 // We are sure that the first page is valid and that we have at least one
503 // page.
504 ASSERT(first_page_->is_valid());
505 ASSERT(num_pages > 0);
506 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
507 ASSERT(Capacity() <= max_capacity_);
508
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000509 // Sequentially initialize remembered sets in the newly allocated
510 // pages and cache the current last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000511 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
512 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000513 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514 }
515
516 // Use first_page_ for allocation.
517 SetAllocationInfo(&allocation_info_, first_page_);
518
519 return true;
520}
521
522
523bool PagedSpace::HasBeenSetup() {
524 return (Capacity() > 0);
525}
526
527
528void PagedSpace::TearDown() {
529 first_page_ = MemoryAllocator::FreePages(first_page_);
530 ASSERT(!first_page_->is_valid());
531
532 accounting_stats_.Clear();
533}
534
535
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000536#ifdef ENABLE_HEAP_PROTECTION
537
538void PagedSpace::Protect() {
539 Page* page = first_page_;
540 while (page->is_valid()) {
541 MemoryAllocator::ProtectChunkFromPage(page);
542 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
543 }
544}
545
546
547void PagedSpace::Unprotect() {
548 Page* page = first_page_;
549 while (page->is_valid()) {
550 MemoryAllocator::UnprotectChunkFromPage(page);
551 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
552 }
553}
554
555#endif
556
557
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558void PagedSpace::ClearRSet() {
559 PageIterator it(this, PageIterator::ALL_PAGES);
560 while (it.has_next()) {
561 it.next()->ClearRSet();
562 }
563}
564
565
566Object* PagedSpace::FindObject(Address addr) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000567 // Note: this function can only be called before or after mark-compact GC
568 // because it accesses map pointers.
569 ASSERT(!MarkCompactCollector::in_use());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570
571 if (!Contains(addr)) return Failure::Exception();
572
573 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000574 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000575 Address cur = p->ObjectAreaStart();
576 Address end = p->AllocationTop();
577 while (cur < end) {
578 HeapObject* obj = HeapObject::FromAddress(cur);
579 Address next = cur + obj->Size();
580 if ((cur <= addr) && (addr < next)) return obj;
581 cur = next;
582 }
583
kasper.lund7276f142008-07-30 08:49:36 +0000584 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 return Failure::Exception();
586}
587
588
kasper.lund7276f142008-07-30 08:49:36 +0000589bool PagedSpace::IsUsed(Page* page) {
590 PageIterator it(this, PageIterator::PAGES_IN_USE);
591 while (it.has_next()) {
592 if (page == it.next()) return true;
593 }
594 return false;
595}
596
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
599 alloc_info->top = p->ObjectAreaStart();
600 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000601 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602}
603
604
605void PagedSpace::MCResetRelocationInfo() {
606 // Set page indexes.
607 int i = 0;
608 PageIterator it(this, PageIterator::ALL_PAGES);
609 while (it.has_next()) {
610 Page* p = it.next();
611 p->mc_page_index = i++;
612 }
613
614 // Set mc_forwarding_info_ to the first page in the space.
615 SetAllocationInfo(&mc_forwarding_info_, first_page_);
616 // All the bytes in the space are 'available'. We will rediscover
617 // allocated and wasted bytes during GC.
618 accounting_stats_.Reset();
619}
620
621
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
623#ifdef DEBUG
624 // The Contains function considers the address at the beginning of a
625 // page in the page, MCSpaceOffsetForAddress considers it is in the
626 // previous page.
627 if (Page::IsAlignedToPageSize(addr)) {
628 ASSERT(Contains(addr - kPointerSize));
629 } else {
630 ASSERT(Contains(addr));
631 }
632#endif
633
634 // If addr is at the end of a page, it belongs to previous page
635 Page* p = Page::IsAlignedToPageSize(addr)
636 ? Page::FromAllocationTop(addr)
637 : Page::FromAddress(addr);
638 int index = p->mc_page_index;
639 return (index * Page::kPageSize) + p->Offset(addr);
640}
641
642
kasper.lund7276f142008-07-30 08:49:36 +0000643// Slow case for reallocating and promoting objects during a compacting
644// collection. This function is not space-specific.
645HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
646 Page* current_page = TopPageOf(mc_forwarding_info_);
647 if (!current_page->next_page()->is_valid()) {
648 if (!Expand(current_page)) {
649 return NULL;
650 }
651 }
652
653 // There are surely more pages in the space now.
654 ASSERT(current_page->next_page()->is_valid());
655 // We do not add the top of page block for current page to the space's
656 // free list---the block may contain live objects so we cannot write
657 // bookkeeping information to it. Instead, we will recover top of page
658 // blocks when we move objects to their new locations.
659 //
660 // We do however write the allocation pointer to the page. The encoding
661 // of forwarding addresses is as an offset in terms of live bytes, so we
662 // need quick access to the allocation top of each page to decode
663 // forwarding addresses.
664 current_page->mc_relocation_top = mc_forwarding_info_.top;
665 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
666 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
667}
668
669
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000670bool PagedSpace::Expand(Page* last_page) {
671 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
672 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
673
674 if (Capacity() == max_capacity_) return false;
675
676 ASSERT(Capacity() < max_capacity_);
677 // Last page must be valid and its next page is invalid.
678 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
679
680 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
681 if (available_pages <= 0) return false;
682
683 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
684 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
685 if (!p->is_valid()) return false;
686
687 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
688 ASSERT(Capacity() <= max_capacity_);
689
690 MemoryAllocator::SetNextPage(last_page, p);
691
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000692 // Sequentially clear remembered set of new pages and and cache the
693 // new last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000694 while (p->is_valid()) {
695 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000696 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 p = p->next_page();
698 }
699
700 return true;
701}
702
703
704#ifdef DEBUG
705int PagedSpace::CountTotalPages() {
706 int count = 0;
707 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
708 count++;
709 }
710 return count;
711}
712#endif
713
714
715void PagedSpace::Shrink() {
716 // Release half of free pages.
717 Page* top_page = AllocationTopPage();
718 ASSERT(top_page->is_valid());
719
720 // Loop over the pages from the top page to the end of the space to count
721 // the number of pages to keep and find the last page to keep.
722 int free_pages = 0;
723 int pages_to_keep = 0; // Of the free pages.
724 Page* last_page_to_keep = top_page;
725 Page* current_page = top_page->next_page();
726 // Loop over the pages to the end of the space.
727 while (current_page->is_valid()) {
kasper.lund7276f142008-07-30 08:49:36 +0000728 // Advance last_page_to_keep every other step to end up at the midpoint.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729 if ((free_pages & 0x1) == 1) {
730 pages_to_keep++;
731 last_page_to_keep = last_page_to_keep->next_page();
732 }
733 free_pages++;
734 current_page = current_page->next_page();
735 }
736
737 // Free pages after last_page_to_keep, and adjust the next_page link.
738 Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
739 MemoryAllocator::SetNextPage(last_page_to_keep, p);
740
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000741 // Since pages are only freed in whole chunks, we may have kept more
742 // than pages_to_keep. Count the extra pages and cache the new last
743 // page in the space.
744 last_page_ = last_page_to_keep;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 while (p->is_valid()) {
746 pages_to_keep++;
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000747 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000748 p = p->next_page();
749 }
750
751 // The difference between free_pages and pages_to_keep is the number of
752 // pages actually freed.
753 ASSERT(pages_to_keep <= free_pages);
754 int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
755 accounting_stats_.ShrinkSpace(bytes_freed);
756
757 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
758}
759
760
761bool PagedSpace::EnsureCapacity(int capacity) {
762 if (Capacity() >= capacity) return true;
763
764 // Start from the allocation top and loop to the last page in the space.
765 Page* last_page = AllocationTopPage();
766 Page* next_page = last_page->next_page();
767 while (next_page->is_valid()) {
768 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
769 next_page = last_page->next_page();
770 }
771
772 // Expand the space until it has the required capacity or expansion fails.
773 do {
774 if (!Expand(last_page)) return false;
775 ASSERT(last_page->next_page()->is_valid());
776 last_page =
777 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
778 } while (Capacity() < capacity);
779
780 return true;
781}
782
783
784#ifdef DEBUG
785void PagedSpace::Print() { }
786#endif
787
788
789// -----------------------------------------------------------------------------
790// NewSpace implementation
791
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000792
793bool NewSpace::Setup(Address start, int size) {
794 // Setup new space based on the preallocated memory block defined by
795 // start and size. The provided space is divided into two semi-spaces.
796 // To support fast containment testing in the new space, the size of
797 // this chunk must be a power of two and it must be aligned to its size.
798 int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
799 int maximum_semispace_capacity = Heap::SemiSpaceSize();
800
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
802 ASSERT(IsPowerOf2(maximum_semispace_capacity));
803 maximum_capacity_ = maximum_semispace_capacity;
804 capacity_ = initial_semispace_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000805
806 // Allocate and setup the histogram arrays if necessary.
807#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
808 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
809 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
810
811#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
812 promoted_histogram_[name].set_name(#name);
813 INSTANCE_TYPE_LIST(SET_NAME)
814#undef SET_NAME
815#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 ASSERT(size == 2 * maximum_capacity_);
818 ASSERT(IsAddressAligned(start, size, 0));
819
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000820 if (!to_space_.Setup(start, capacity_, maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000821 return false;
822 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000823 if (!from_space_.Setup(start + maximum_capacity_,
824 capacity_,
825 maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 return false;
827 }
828
829 start_ = start;
830 address_mask_ = ~(size - 1);
831 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000832 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000834 allocation_info_.top = to_space_.low();
835 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 mc_forwarding_info_.top = NULL;
837 mc_forwarding_info_.limit = NULL;
838
839 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
840 return true;
841}
842
843
844void NewSpace::TearDown() {
845#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
846 if (allocated_histogram_) {
847 DeleteArray(allocated_histogram_);
848 allocated_histogram_ = NULL;
849 }
850 if (promoted_histogram_) {
851 DeleteArray(promoted_histogram_);
852 promoted_histogram_ = NULL;
853 }
854#endif
855
856 start_ = NULL;
857 capacity_ = 0;
858 allocation_info_.top = NULL;
859 allocation_info_.limit = NULL;
860 mc_forwarding_info_.top = NULL;
861 mc_forwarding_info_.limit = NULL;
862
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000863 to_space_.TearDown();
864 from_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000865}
866
867
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000868#ifdef ENABLE_HEAP_PROTECTION
869
870void NewSpace::Protect() {
871 MemoryAllocator::Protect(ToSpaceLow(), Capacity());
872 MemoryAllocator::Protect(FromSpaceLow(), Capacity());
873}
874
875
876void NewSpace::Unprotect() {
877 MemoryAllocator::Unprotect(ToSpaceLow(), Capacity(),
878 to_space_.executable());
879 MemoryAllocator::Unprotect(FromSpaceLow(), Capacity(),
880 from_space_.executable());
881}
882
883#endif
884
885
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886void NewSpace::Flip() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000887 SemiSpace tmp = from_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000888 from_space_ = to_space_;
889 to_space_ = tmp;
890}
891
892
893bool NewSpace::Double() {
894 ASSERT(capacity_ <= maximum_capacity_ / 2);
895 // TODO(1240712): Failure to double the from space can result in
896 // semispaces of different sizes. In the event of that failure, the
897 // to space doubling should be rolled back before returning false.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000898 if (!to_space_.Double() || !from_space_.Double()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000899 capacity_ *= 2;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000900 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000901 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
902 return true;
903}
904
905
906void NewSpace::ResetAllocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000907 allocation_info_.top = to_space_.low();
908 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000909 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
910}
911
912
913void NewSpace::MCResetRelocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000914 mc_forwarding_info_.top = from_space_.low();
915 mc_forwarding_info_.limit = from_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000916 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
917}
918
919
920void NewSpace::MCCommitRelocationInfo() {
921 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
922 // valid allocation info for the to space.
923 allocation_info_.top = mc_forwarding_info_.top;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000924 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
926}
927
928
929#ifdef DEBUG
930// We do not use the SemispaceIterator because verification doesn't assume
931// that it works (it depends on the invariants we are checking).
932void NewSpace::Verify() {
933 // The allocation pointer should be in the space or at the very end.
934 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
935
936 // There should be objects packed in from the low address up to the
937 // allocation pointer.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000938 Address current = to_space_.low();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939 while (current < top()) {
940 HeapObject* object = HeapObject::FromAddress(current);
941
942 // The first word should be a map, and we expect all map pointers to
943 // be in map space.
944 Map* map = object->map();
945 ASSERT(map->IsMap());
946 ASSERT(Heap::map_space()->Contains(map));
947
948 // The object should not be code or a map.
949 ASSERT(!object->IsMap());
950 ASSERT(!object->IsCode());
951
952 // The object itself should look OK.
953 object->Verify();
954
955 // All the interior pointers should be contained in the heap.
956 VerifyPointersVisitor visitor;
957 int size = object->Size();
958 object->IterateBody(map->instance_type(), size, &visitor);
959
960 current += size;
961 }
962
963 // The allocation pointer should not be in the middle of an object.
964 ASSERT(current == top());
965}
966#endif
967
968
969// -----------------------------------------------------------------------------
970// SemiSpace implementation
971
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000972bool SemiSpace::Setup(Address start,
973 int initial_capacity,
974 int maximum_capacity) {
975 // Creates a space in the young generation. The constructor does not
976 // allocate memory from the OS. A SemiSpace is given a contiguous chunk of
977 // memory of size 'capacity' when set up, and does not grow or shrink
978 // otherwise. In the mark-compact collector, the memory region of the from
979 // space is used as the marking stack. It requires contiguous memory
980 // addresses.
981 capacity_ = initial_capacity;
982 maximum_capacity_ = maximum_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983
kasper.lund7276f142008-07-30 08:49:36 +0000984 if (!MemoryAllocator::CommitBlock(start, capacity_, executable())) {
985 return false;
986 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000987
988 start_ = start;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000989 address_mask_ = ~(maximum_capacity - 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000990 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000991 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000992
993 age_mark_ = start_;
994 return true;
995}
996
997
998void SemiSpace::TearDown() {
999 start_ = NULL;
1000 capacity_ = 0;
1001}
1002
1003
1004bool SemiSpace::Double() {
kasper.lund7276f142008-07-30 08:49:36 +00001005 if (!MemoryAllocator::CommitBlock(high(), capacity_, executable())) {
1006 return false;
1007 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001008 capacity_ *= 2;
1009 return true;
1010}
1011
1012
1013#ifdef DEBUG
1014void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001015
1016
1017void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001018#endif
1019
1020
1021// -----------------------------------------------------------------------------
1022// SemiSpaceIterator implementation.
1023SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
1024 Initialize(space, space->bottom(), space->top(), NULL);
1025}
1026
1027
1028SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
1029 HeapObjectCallback size_func) {
1030 Initialize(space, space->bottom(), space->top(), size_func);
1031}
1032
1033
1034SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
1035 Initialize(space, start, space->top(), NULL);
1036}
1037
1038
1039void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
1040 Address end,
1041 HeapObjectCallback size_func) {
1042 ASSERT(space->ToSpaceContains(start));
1043 ASSERT(space->ToSpaceLow() <= end
1044 && end <= space->ToSpaceHigh());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001045 space_ = &space->to_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046 current_ = start;
1047 limit_ = end;
1048 size_func_ = size_func;
1049}
1050
1051
1052#ifdef DEBUG
1053// A static array of histogram info for each type.
1054static HistogramInfo heap_histograms[LAST_TYPE+1];
1055static JSObject::SpillInformation js_spill_information;
1056
1057// heap_histograms is shared, always clear it before using it.
1058static void ClearHistograms() {
1059 // We reset the name each time, though it hasn't changed.
1060#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1061 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1062#undef DEF_TYPE_NAME
1063
1064#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1065 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1066#undef CLEAR_HISTOGRAM
1067
1068 js_spill_information.Clear();
1069}
1070
1071
1072static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1073
1074
1075static void ClearCodeKindStatistics() {
1076 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1077 code_kind_statistics[i] = 0;
1078 }
1079}
1080
1081
1082static void ReportCodeKindStatistics() {
1083 const char* table[Code::NUMBER_OF_KINDS];
1084
1085#define CASE(name) \
1086 case Code::name: table[Code::name] = #name; \
1087 break
1088
1089 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1090 switch (static_cast<Code::Kind>(i)) {
1091 CASE(FUNCTION);
1092 CASE(STUB);
1093 CASE(BUILTIN);
1094 CASE(LOAD_IC);
1095 CASE(KEYED_LOAD_IC);
1096 CASE(STORE_IC);
1097 CASE(KEYED_STORE_IC);
1098 CASE(CALL_IC);
1099 }
1100 }
1101
1102#undef CASE
1103
1104 PrintF("\n Code kind histograms: \n");
1105 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1106 if (code_kind_statistics[i] > 0) {
1107 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1108 }
1109 }
1110 PrintF("\n");
1111}
1112
1113
1114static int CollectHistogramInfo(HeapObject* obj) {
1115 InstanceType type = obj->map()->instance_type();
1116 ASSERT(0 <= type && type <= LAST_TYPE);
1117 ASSERT(heap_histograms[type].name() != NULL);
1118 heap_histograms[type].increment_number(1);
1119 heap_histograms[type].increment_bytes(obj->Size());
1120
1121 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1122 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1123 }
1124
1125 return obj->Size();
1126}
1127
1128
1129static void ReportHistogram(bool print_spill) {
1130 PrintF("\n Object Histogram:\n");
1131 for (int i = 0; i <= LAST_TYPE; i++) {
1132 if (heap_histograms[i].number() > 0) {
1133 PrintF(" %-33s%10d (%10d bytes)\n",
1134 heap_histograms[i].name(),
1135 heap_histograms[i].number(),
1136 heap_histograms[i].bytes());
1137 }
1138 }
1139 PrintF("\n");
1140
1141 // Summarize string types.
1142 int string_number = 0;
1143 int string_bytes = 0;
1144#define INCREMENT(type, size, name) \
1145 string_number += heap_histograms[type].number(); \
1146 string_bytes += heap_histograms[type].bytes();
1147 STRING_TYPE_LIST(INCREMENT)
1148#undef INCREMENT
1149 if (string_number > 0) {
1150 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1151 string_bytes);
1152 }
1153
1154 if (FLAG_collect_heap_spill_statistics && print_spill) {
1155 js_spill_information.Print();
1156 }
1157}
1158#endif // DEBUG
1159
1160
1161// Support for statistics gathering for --heap-stats and --log-gc.
1162#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1163void NewSpace::ClearHistograms() {
1164 for (int i = 0; i <= LAST_TYPE; i++) {
1165 allocated_histogram_[i].clear();
1166 promoted_histogram_[i].clear();
1167 }
1168}
1169
1170// Because the copying collector does not touch garbage objects, we iterate
1171// the new space before a collection to get a histogram of allocated objects.
1172// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1173// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1174// flag is set.
1175void NewSpace::CollectStatistics() {
1176 ClearHistograms();
1177 SemiSpaceIterator it(this);
1178 while (it.has_next()) RecordAllocation(it.next());
1179}
1180
1181
1182#ifdef ENABLE_LOGGING_AND_PROFILING
1183static void DoReportStatistics(HistogramInfo* info, const char* description) {
1184 LOG(HeapSampleBeginEvent("NewSpace", description));
1185 // Lump all the string types together.
1186 int string_number = 0;
1187 int string_bytes = 0;
1188#define INCREMENT(type, size, name) \
1189 string_number += info[type].number(); \
1190 string_bytes += info[type].bytes();
1191 STRING_TYPE_LIST(INCREMENT)
1192#undef INCREMENT
1193 if (string_number > 0) {
1194 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1195 }
1196
1197 // Then do the other types.
1198 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1199 if (info[i].number() > 0) {
1200 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1201 info[i].bytes()));
1202 }
1203 }
1204 LOG(HeapSampleEndEvent("NewSpace", description));
1205}
1206#endif // ENABLE_LOGGING_AND_PROFILING
1207
1208
1209void NewSpace::ReportStatistics() {
1210#ifdef DEBUG
1211 if (FLAG_heap_stats) {
1212 float pct = static_cast<float>(Available()) / Capacity();
1213 PrintF(" capacity: %d, available: %d, %%%d\n",
1214 Capacity(), Available(), static_cast<int>(pct*100));
1215 PrintF("\n Object Histogram:\n");
1216 for (int i = 0; i <= LAST_TYPE; i++) {
1217 if (allocated_histogram_[i].number() > 0) {
1218 PrintF(" %-33s%10d (%10d bytes)\n",
1219 allocated_histogram_[i].name(),
1220 allocated_histogram_[i].number(),
1221 allocated_histogram_[i].bytes());
1222 }
1223 }
1224 PrintF("\n");
1225 }
1226#endif // DEBUG
1227
1228#ifdef ENABLE_LOGGING_AND_PROFILING
1229 if (FLAG_log_gc) {
1230 DoReportStatistics(allocated_histogram_, "allocated");
1231 DoReportStatistics(promoted_histogram_, "promoted");
1232 }
1233#endif // ENABLE_LOGGING_AND_PROFILING
1234}
1235
1236
1237void NewSpace::RecordAllocation(HeapObject* obj) {
1238 InstanceType type = obj->map()->instance_type();
1239 ASSERT(0 <= type && type <= LAST_TYPE);
1240 allocated_histogram_[type].increment_number(1);
1241 allocated_histogram_[type].increment_bytes(obj->Size());
1242}
1243
1244
1245void NewSpace::RecordPromotion(HeapObject* obj) {
1246 InstanceType type = obj->map()->instance_type();
1247 ASSERT(0 <= type && type <= LAST_TYPE);
1248 promoted_histogram_[type].increment_number(1);
1249 promoted_histogram_[type].increment_bytes(obj->Size());
1250}
1251#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1252
1253
1254// -----------------------------------------------------------------------------
1255// Free lists for old object spaces implementation
1256
1257void FreeListNode::set_size(int size_in_bytes) {
1258 ASSERT(size_in_bytes > 0);
1259 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1260
1261 // We write a map and possibly size information to the block. If the block
1262 // is big enough to be a ByteArray with at least one extra word (the next
1263 // pointer), we set its map to be the byte array map and its size to an
1264 // appropriate array length for the desired size from HeapObject::Size().
1265 // If the block is too small (eg, one or two words), to hold both a size
1266 // field and a next pointer, we give it a filler map that gives it the
1267 // correct size.
1268 if (size_in_bytes > Array::kHeaderSize) {
1269 set_map(Heap::byte_array_map());
1270 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1271 } else if (size_in_bytes == kPointerSize) {
1272 set_map(Heap::one_word_filler_map());
1273 } else if (size_in_bytes == 2 * kPointerSize) {
1274 set_map(Heap::two_word_filler_map());
1275 } else {
1276 UNREACHABLE();
1277 }
kasper.lund7276f142008-07-30 08:49:36 +00001278 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001279}
1280
1281
1282Address FreeListNode::next() {
1283 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001284 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001285 return Memory::Address_at(address() + kNextOffset);
1286}
1287
1288
1289void FreeListNode::set_next(Address next) {
1290 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001291 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001292 Memory::Address_at(address() + kNextOffset) = next;
1293}
1294
1295
1296OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1297 Reset();
1298}
1299
1300
1301void OldSpaceFreeList::Reset() {
1302 available_ = 0;
1303 for (int i = 0; i < kFreeListsLength; i++) {
1304 free_[i].head_node_ = NULL;
1305 }
1306 needs_rebuild_ = false;
1307 finger_ = kHead;
1308 free_[kHead].next_size_ = kEnd;
1309}
1310
1311
1312void OldSpaceFreeList::RebuildSizeList() {
1313 ASSERT(needs_rebuild_);
1314 int cur = kHead;
1315 for (int i = cur + 1; i < kFreeListsLength; i++) {
1316 if (free_[i].head_node_ != NULL) {
1317 free_[cur].next_size_ = i;
1318 cur = i;
1319 }
1320 }
1321 free_[cur].next_size_ = kEnd;
1322 needs_rebuild_ = false;
1323}
1324
1325
1326int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1327#ifdef DEBUG
1328 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1329 Memory::Address_at(start + i) = kZapValue;
1330 }
1331#endif
1332 FreeListNode* node = FreeListNode::FromAddress(start);
1333 node->set_size(size_in_bytes);
1334
1335 // Early return to drop too-small blocks on the floor (one or two word
1336 // blocks cannot hold a map pointer, a size field, and a pointer to the
1337 // next block in the free list).
1338 if (size_in_bytes < kMinBlockSize) {
1339 return size_in_bytes;
1340 }
1341
1342 // Insert other blocks at the head of an exact free list.
1343 int index = size_in_bytes >> kPointerSizeLog2;
1344 node->set_next(free_[index].head_node_);
1345 free_[index].head_node_ = node->address();
1346 available_ += size_in_bytes;
1347 needs_rebuild_ = true;
1348 return 0;
1349}
1350
1351
1352Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1353 ASSERT(0 < size_in_bytes);
1354 ASSERT(size_in_bytes <= kMaxBlockSize);
1355 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1356
1357 if (needs_rebuild_) RebuildSizeList();
1358 int index = size_in_bytes >> kPointerSizeLog2;
1359 // Check for a perfect fit.
1360 if (free_[index].head_node_ != NULL) {
1361 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1362 // If this was the last block of its size, remove the size.
1363 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1364 available_ -= size_in_bytes;
1365 *wasted_bytes = 0;
1366 return node;
1367 }
1368 // Search the size list for the best fit.
1369 int prev = finger_ < index ? finger_ : kHead;
1370 int cur = FindSize(index, &prev);
1371 ASSERT(index < cur);
1372 if (cur == kEnd) {
1373 // No large enough size in list.
1374 *wasted_bytes = 0;
1375 return Failure::RetryAfterGC(size_in_bytes, owner_);
1376 }
1377 int rem = cur - index;
1378 int rem_bytes = rem << kPointerSizeLog2;
1379 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001380 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001381 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1382 size_in_bytes);
1383 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1384 // to avoid many redundant tests and calls to Insert/RemoveSize.
1385 if (prev < rem) {
1386 // Simple case: insert rem between prev and cur.
1387 finger_ = prev;
1388 free_[prev].next_size_ = rem;
1389 // If this was the last block of size cur, remove the size.
1390 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1391 free_[rem].next_size_ = free_[cur].next_size_;
1392 } else {
1393 free_[rem].next_size_ = cur;
1394 }
1395 // Add the remainder block.
1396 rem_node->set_size(rem_bytes);
1397 rem_node->set_next(free_[rem].head_node_);
1398 free_[rem].head_node_ = rem_node->address();
1399 } else {
1400 // If this was the last block of size cur, remove the size.
1401 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1402 finger_ = prev;
1403 free_[prev].next_size_ = free_[cur].next_size_;
1404 }
1405 if (rem_bytes < kMinBlockSize) {
1406 // Too-small remainder is wasted.
1407 rem_node->set_size(rem_bytes);
1408 available_ -= size_in_bytes + rem_bytes;
1409 *wasted_bytes = rem_bytes;
1410 return cur_node;
1411 }
1412 // Add the remainder block and, if needed, insert its size.
1413 rem_node->set_size(rem_bytes);
1414 rem_node->set_next(free_[rem].head_node_);
1415 free_[rem].head_node_ = rem_node->address();
1416 if (rem_node->next() == NULL) InsertSize(rem);
1417 }
1418 available_ -= size_in_bytes;
1419 *wasted_bytes = 0;
1420 return cur_node;
1421}
1422
1423
kasper.lund7276f142008-07-30 08:49:36 +00001424#ifdef DEBUG
1425bool OldSpaceFreeList::Contains(FreeListNode* node) {
1426 for (int i = 0; i < kFreeListsLength; i++) {
1427 Address cur_addr = free_[i].head_node_;
1428 while (cur_addr != NULL) {
1429 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1430 if (cur_node == node) return true;
1431 cur_addr = cur_node->next();
1432 }
1433 }
1434 return false;
1435}
1436#endif
1437
1438
1439MapSpaceFreeList::MapSpaceFreeList(AllocationSpace owner) {
1440 owner_ = owner;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 Reset();
1442}
1443
1444
1445void MapSpaceFreeList::Reset() {
1446 available_ = 0;
1447 head_ = NULL;
1448}
1449
1450
1451void MapSpaceFreeList::Free(Address start) {
1452#ifdef DEBUG
1453 for (int i = 0; i < Map::kSize; i += kPointerSize) {
1454 Memory::Address_at(start + i) = kZapValue;
1455 }
1456#endif
1457 FreeListNode* node = FreeListNode::FromAddress(start);
1458 node->set_size(Map::kSize);
1459 node->set_next(head_);
1460 head_ = node->address();
1461 available_ += Map::kSize;
1462}
1463
1464
1465Object* MapSpaceFreeList::Allocate() {
1466 if (head_ == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00001467 return Failure::RetryAfterGC(Map::kSize, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001468 }
1469
1470 FreeListNode* node = FreeListNode::FromAddress(head_);
1471 head_ = node->next();
1472 available_ -= Map::kSize;
1473 return node;
1474}
1475
1476
1477// -----------------------------------------------------------------------------
1478// OldSpace implementation
1479
1480void OldSpace::PrepareForMarkCompact(bool will_compact) {
1481 if (will_compact) {
1482 // Reset relocation info. During a compacting collection, everything in
1483 // the space is considered 'available' and we will rediscover live data
1484 // and waste during the collection.
1485 MCResetRelocationInfo();
1486 mc_end_of_relocation_ = bottom();
1487 ASSERT(Available() == Capacity());
1488 } else {
1489 // During a non-compacting collection, everything below the linear
1490 // allocation pointer is considered allocated (everything above is
1491 // available) and we will rediscover available and wasted bytes during
1492 // the collection.
1493 accounting_stats_.AllocateBytes(free_list_.available());
1494 accounting_stats_.FillWastedBytes(Waste());
1495 }
1496
kasper.lund7276f142008-07-30 08:49:36 +00001497 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001498 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001499}
1500
1501
1502void OldSpace::MCAdjustRelocationEnd(Address address, int size_in_bytes) {
1503 ASSERT(Contains(address));
1504 Address current_top = mc_end_of_relocation_;
1505 Page* current_page = Page::FromAllocationTop(current_top);
1506
1507 // No more objects relocated to this page? Move to the next.
1508 ASSERT(current_top <= current_page->mc_relocation_top);
1509 if (current_top == current_page->mc_relocation_top) {
1510 // The space should already be properly expanded.
1511 Page* next_page = current_page->next_page();
1512 CHECK(next_page->is_valid());
1513 mc_end_of_relocation_ = next_page->ObjectAreaStart();
1514 }
1515 ASSERT(mc_end_of_relocation_ == address);
1516 mc_end_of_relocation_ += size_in_bytes;
1517}
1518
1519
1520void OldSpace::MCCommitRelocationInfo() {
1521 // Update fast allocation info.
1522 allocation_info_.top = mc_forwarding_info_.top;
1523 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001524 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001525
1526 // The space is compacted and we haven't yet built free lists or
1527 // wasted any space.
1528 ASSERT(Waste() == 0);
1529 ASSERT(AvailableFree() == 0);
1530
1531 // Build the free list for the space.
1532 int computed_size = 0;
1533 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1534 while (it.has_next()) {
1535 Page* p = it.next();
1536 // Space below the relocation pointer is allocated.
1537 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1538 if (it.has_next()) {
1539 // Free the space at the top of the page. We cannot use
1540 // p->mc_relocation_top after the call to Free (because Free will clear
1541 // remembered set bits).
1542 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1543 if (extra_size > 0) {
1544 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1545 // The bytes we have just "freed" to add to the free list were
1546 // already accounted as available.
1547 accounting_stats_.WasteBytes(wasted_bytes);
1548 }
1549 }
1550 }
1551
1552 // Make sure the computed size - based on the used portion of the pages in
1553 // use - matches the size obtained while computing forwarding addresses.
1554 ASSERT(computed_size == Size());
1555}
1556
1557
kasper.lund7276f142008-07-30 08:49:36 +00001558// Slow case for normal allocation. Try in order: (1) allocate in the next
1559// page in the space, (2) allocate off the space's free list, (3) expand the
1560// space, (4) fail.
1561HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1562 // Linear allocation in this space has failed. If there is another page
1563 // in the space, move to that page and allocate there. This allocation
1564 // should succeed (size_in_bytes should not be greater than a page's
1565 // object area size).
1566 Page* current_page = TopPageOf(allocation_info_);
1567 if (current_page->next_page()->is_valid()) {
1568 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001569 }
kasper.lund7276f142008-07-30 08:49:36 +00001570
1571 // There is no next page in this space. Try free list allocation.
1572 int wasted_bytes;
1573 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1574 accounting_stats_.WasteBytes(wasted_bytes);
1575 if (!result->IsFailure()) {
1576 accounting_stats_.AllocateBytes(size_in_bytes);
1577 return HeapObject::cast(result);
1578 }
1579
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001580 // Free list allocation failed and there is no next page. Fail if we have
1581 // hit the old generation size limit that should cause a garbage
1582 // collection.
1583 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
1584 return NULL;
1585 }
1586
1587 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00001588 ASSERT(!current_page->next_page()->is_valid());
1589 if (Expand(current_page)) {
1590 return AllocateInNextPage(current_page, size_in_bytes);
1591 }
1592
1593 // Finally, fail.
1594 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001595}
1596
1597
kasper.lund7276f142008-07-30 08:49:36 +00001598// Add the block at the top of the page to the space's free list, set the
1599// allocation info to the next page (assumed to be one), and allocate
1600// linearly there.
1601HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1602 int size_in_bytes) {
1603 ASSERT(current_page->next_page()->is_valid());
1604 // Add the block at the top of this page to the free list.
1605 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1606 if (free_size > 0) {
1607 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1608 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609 }
kasper.lund7276f142008-07-30 08:49:36 +00001610 SetAllocationInfo(&allocation_info_, current_page->next_page());
1611 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612}
1613
1614
1615#ifdef DEBUG
1616// We do not assume that the PageIterator works, because it depends on the
1617// invariants we are checking during verification.
1618void OldSpace::Verify() {
1619 // The allocation pointer should be valid, and it should be in a page in the
1620 // space.
kasper.lund7276f142008-07-30 08:49:36 +00001621 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001622 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
1623 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
1624
1625 // Loop over all the pages.
1626 bool above_allocation_top = false;
1627 Page* current_page = first_page_;
1628 while (current_page->is_valid()) {
1629 if (above_allocation_top) {
1630 // We don't care what's above the allocation top.
1631 } else {
1632 // Unless this is the last page in the space containing allocated
1633 // objects, the allocation top should be at the object area end.
1634 Address top = current_page->AllocationTop();
1635 if (current_page == top_page) {
1636 ASSERT(top == allocation_info_.top);
1637 // The next page will be above the allocation top.
1638 above_allocation_top = true;
1639 } else {
1640 ASSERT(top == current_page->ObjectAreaEnd());
1641 }
1642
1643 // It should be packed with objects from the bottom to the top.
1644 Address current = current_page->ObjectAreaStart();
1645 while (current < top) {
1646 HeapObject* object = HeapObject::FromAddress(current);
1647
1648 // The first word should be a map, and we expect all map pointers to
1649 // be in map space.
1650 Map* map = object->map();
1651 ASSERT(map->IsMap());
1652 ASSERT(Heap::map_space()->Contains(map));
1653
1654 // The object should not be a map.
1655 ASSERT(!object->IsMap());
1656
1657 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001658 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001659
1660 // All the interior pointers should be contained in the heap and have
1661 // their remembered set bits set if they point to new space. Code
1662 // objects do not have remembered set bits that we care about.
1663 VerifyPointersAndRSetVisitor rset_visitor;
1664 VerifyPointersVisitor no_rset_visitor;
1665 int size = object->Size();
1666 if (object->IsCode()) {
1667 Code::cast(object)->ConvertICTargetsFromAddressToObject();
1668 object->IterateBody(map->instance_type(), size, &no_rset_visitor);
1669 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
1670 } else {
1671 object->IterateBody(map->instance_type(), size, &rset_visitor);
1672 }
1673
1674 current += size;
1675 }
1676
1677 // The allocation pointer should not be in the middle of an object.
1678 ASSERT(current == top);
1679 }
1680
1681 current_page = current_page->next_page();
1682 }
1683}
1684
1685
1686struct CommentStatistic {
1687 const char* comment;
1688 int size;
1689 int count;
1690 void Clear() {
1691 comment = NULL;
1692 size = 0;
1693 count = 0;
1694 }
1695};
1696
1697
1698// must be small, since an iteration is used for lookup
1699const int kMaxComments = 64;
1700static CommentStatistic comments_statistics[kMaxComments+1];
1701
1702
1703void PagedSpace::ReportCodeStatistics() {
1704 ReportCodeKindStatistics();
1705 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1706 "count (average)\"):\n");
1707 for (int i = 0; i <= kMaxComments; i++) {
1708 const CommentStatistic& cs = comments_statistics[i];
1709 if (cs.size > 0) {
1710 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1711 cs.size/cs.count);
1712 }
1713 }
1714 PrintF("\n");
1715}
1716
1717
1718void PagedSpace::ResetCodeStatistics() {
1719 ClearCodeKindStatistics();
1720 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1721 comments_statistics[kMaxComments].comment = "Unknown";
1722 comments_statistics[kMaxComments].size = 0;
1723 comments_statistics[kMaxComments].count = 0;
1724}
1725
1726
1727// Adds comment to 'comment_statistics' table. Performance OK sa long as
1728// 'kMaxComments' is small
1729static void EnterComment(const char* comment, int delta) {
1730 // Do not count empty comments
1731 if (delta <= 0) return;
1732 CommentStatistic* cs = &comments_statistics[kMaxComments];
1733 // Search for a free or matching entry in 'comments_statistics': 'cs'
1734 // points to result.
1735 for (int i = 0; i < kMaxComments; i++) {
1736 if (comments_statistics[i].comment == NULL) {
1737 cs = &comments_statistics[i];
1738 cs->comment = comment;
1739 break;
1740 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1741 cs = &comments_statistics[i];
1742 break;
1743 }
1744 }
1745 // Update entry for 'comment'
1746 cs->size += delta;
1747 cs->count += 1;
1748}
1749
1750
1751// Call for each nested comment start (start marked with '[ xxx', end marked
1752// with ']'. RelocIterator 'it' must point to a comment reloc info.
1753static void CollectCommentStatistics(RelocIterator* it) {
1754 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001755 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001756 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1757 if (tmp[0] != '[') {
1758 // Not a nested comment; skip
1759 return;
1760 }
1761
1762 // Search for end of nested comment or a new nested comment
1763 const char* const comment_txt =
1764 reinterpret_cast<const char*>(it->rinfo()->data());
1765 const byte* prev_pc = it->rinfo()->pc();
1766 int flat_delta = 0;
1767 it->next();
1768 while (true) {
1769 // All nested comments must be terminated properly, and therefore exit
1770 // from loop.
1771 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001772 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001773 const char* const txt =
1774 reinterpret_cast<const char*>(it->rinfo()->data());
1775 flat_delta += it->rinfo()->pc() - prev_pc;
1776 if (txt[0] == ']') break; // End of nested comment
1777 // A new comment
1778 CollectCommentStatistics(it);
1779 // Skip code that was covered with previous comment
1780 prev_pc = it->rinfo()->pc();
1781 }
1782 it->next();
1783 }
1784 EnterComment(comment_txt, flat_delta);
1785}
1786
1787
1788// Collects code size statistics:
1789// - by code kind
1790// - by code comment
1791void PagedSpace::CollectCodeStatistics() {
1792 HeapObjectIterator obj_it(this);
1793 while (obj_it.has_next()) {
1794 HeapObject* obj = obj_it.next();
1795 if (obj->IsCode()) {
1796 Code* code = Code::cast(obj);
1797 code_kind_statistics[code->kind()] += code->Size();
1798 RelocIterator it(code);
1799 int delta = 0;
1800 const byte* prev_pc = code->instruction_start();
1801 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001802 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001803 delta += it.rinfo()->pc() - prev_pc;
1804 CollectCommentStatistics(&it);
1805 prev_pc = it.rinfo()->pc();
1806 }
1807 it.next();
1808 }
1809
1810 ASSERT(code->instruction_start() <= prev_pc &&
1811 prev_pc <= code->relocation_start());
1812 delta += code->relocation_start() - prev_pc;
1813 EnterComment("NoComment", delta);
1814 }
1815 }
1816}
1817
1818
1819void OldSpace::ReportStatistics() {
1820 int pct = Available() * 100 / Capacity();
1821 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1822 Capacity(), Waste(), Available(), pct);
1823
1824 // Report remembered set statistics.
1825 int rset_marked_pointers = 0;
1826 int rset_marked_arrays = 0;
1827 int rset_marked_array_elements = 0;
1828 int cross_gen_pointers = 0;
1829 int cross_gen_array_elements = 0;
1830
1831 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1832 while (page_it.has_next()) {
1833 Page* p = page_it.next();
1834
1835 for (Address rset_addr = p->RSetStart();
1836 rset_addr < p->RSetEnd();
1837 rset_addr += kIntSize) {
1838 int rset = Memory::int_at(rset_addr);
1839 if (rset != 0) {
1840 // Bits were set
1841 int intoff = rset_addr - p->address();
1842 int bitoff = 0;
1843 for (; bitoff < kBitsPerInt; ++bitoff) {
1844 if ((rset & (1 << bitoff)) != 0) {
1845 int bitpos = intoff*kBitsPerByte + bitoff;
1846 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1847 Object** obj = reinterpret_cast<Object**>(slot);
1848 if (*obj == Heap::fixed_array_map()) {
1849 rset_marked_arrays++;
1850 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1851
1852 rset_marked_array_elements += fa->length();
1853 // Manually inline FixedArray::IterateBody
1854 Address elm_start = slot + FixedArray::kHeaderSize;
1855 Address elm_stop = elm_start + fa->length() * kPointerSize;
1856 for (Address elm_addr = elm_start;
1857 elm_addr < elm_stop; elm_addr += kPointerSize) {
1858 // Filter non-heap-object pointers
1859 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1860 if (Heap::InNewSpace(*elm_p))
1861 cross_gen_array_elements++;
1862 }
1863 } else {
1864 rset_marked_pointers++;
1865 if (Heap::InNewSpace(*obj))
1866 cross_gen_pointers++;
1867 }
1868 }
1869 }
1870 }
1871 }
1872 }
1873
1874 pct = rset_marked_pointers == 0 ?
1875 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1876 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1877 rset_marked_pointers, cross_gen_pointers, pct);
1878 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1879 PrintF(" elements %d, ", rset_marked_array_elements);
1880 pct = rset_marked_array_elements == 0 ? 0
1881 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1882 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1883 PrintF(" total rset-marked bits %d\n",
1884 (rset_marked_pointers + rset_marked_arrays));
1885 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1886 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1887 (rset_marked_pointers + rset_marked_array_elements);
1888 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1889 (rset_marked_pointers + rset_marked_array_elements),
1890 (cross_gen_pointers + cross_gen_array_elements),
1891 pct);
1892
1893 ClearHistograms();
1894 HeapObjectIterator obj_it(this);
1895 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1896 ReportHistogram(true);
1897}
1898
1899
1900// Dump the range of remembered set words between [start, end) corresponding
1901// to the pointers starting at object_p. The allocation_top is an object
1902// pointer which should not be read past. This is important for large object
1903// pages, where some bits in the remembered set range do not correspond to
1904// allocated addresses.
1905static void PrintRSetRange(Address start, Address end, Object** object_p,
1906 Address allocation_top) {
1907 Address rset_address = start;
1908
1909 // If the range starts on on odd numbered word (eg, for large object extra
1910 // remembered set ranges), print some spaces.
ager@chromium.org9085a012009-05-11 19:22:57 +00001911 if ((reinterpret_cast<uintptr_t>(start) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001912 PrintF(" ");
1913 }
1914
1915 // Loop over all the words in the range.
1916 while (rset_address < end) {
1917 uint32_t rset_word = Memory::uint32_at(rset_address);
1918 int bit_position = 0;
1919
1920 // Loop over all the bits in the word.
1921 while (bit_position < kBitsPerInt) {
1922 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1923 // Print a bar at the allocation pointer.
1924 PrintF("|");
1925 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1926 // Do not dereference object_p past the allocation pointer.
1927 PrintF("#");
1928 } else if ((rset_word & (1 << bit_position)) == 0) {
1929 // Print a dot for zero bits.
1930 PrintF(".");
1931 } else if (Heap::InNewSpace(*object_p)) {
1932 // Print an X for one bits for pointers to new space.
1933 PrintF("X");
1934 } else {
1935 // Print a circle for one bits for pointers to old space.
1936 PrintF("o");
1937 }
1938
1939 // Print a space after every 8th bit except the last.
1940 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1941 PrintF(" ");
1942 }
1943
1944 // Advance to next bit.
1945 bit_position++;
1946 object_p++;
1947 }
1948
1949 // Print a newline after every odd numbered word, otherwise a space.
ager@chromium.org9085a012009-05-11 19:22:57 +00001950 if ((reinterpret_cast<uintptr_t>(rset_address) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001951 PrintF("\n");
1952 } else {
1953 PrintF(" ");
1954 }
1955
1956 // Advance to next remembered set word.
1957 rset_address += kIntSize;
1958 }
1959}
1960
1961
1962void PagedSpace::DoPrintRSet(const char* space_name) {
1963 PageIterator it(this, PageIterator::PAGES_IN_USE);
1964 while (it.has_next()) {
1965 Page* p = it.next();
1966 PrintF("%s page 0x%x:\n", space_name, p);
1967 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
1968 reinterpret_cast<Object**>(p->ObjectAreaStart()),
1969 p->AllocationTop());
1970 PrintF("\n");
1971 }
1972}
1973
1974
1975void OldSpace::PrintRSet() { DoPrintRSet("old"); }
1976#endif
1977
1978// -----------------------------------------------------------------------------
1979// MapSpace implementation
1980
1981void MapSpace::PrepareForMarkCompact(bool will_compact) {
1982 if (will_compact) {
1983 // Reset relocation info.
1984 MCResetRelocationInfo();
1985
1986 // Initialize map index entry.
1987 int page_count = 0;
1988 PageIterator it(this, PageIterator::ALL_PAGES);
1989 while (it.has_next()) {
1990 ASSERT_MAP_PAGE_INDEX(page_count);
1991
1992 Page* p = it.next();
1993 ASSERT(p->mc_page_index == page_count);
1994
1995 page_addresses_[page_count++] = p->address();
1996 }
1997
1998 // During a compacting collection, everything in the space is considered
1999 // 'available' (set by the call to MCResetRelocationInfo) and we will
2000 // rediscover live and wasted bytes during the collection.
2001 ASSERT(Available() == Capacity());
2002 } else {
2003 // During a non-compacting collection, everything below the linear
2004 // allocation pointer except wasted top-of-page blocks is considered
2005 // allocated and we will rediscover available bytes during the
2006 // collection.
2007 accounting_stats_.AllocateBytes(free_list_.available());
2008 }
2009
kasper.lund7276f142008-07-30 08:49:36 +00002010 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002011 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002012}
2013
2014
2015void MapSpace::MCCommitRelocationInfo() {
2016 // Update fast allocation info.
2017 allocation_info_.top = mc_forwarding_info_.top;
2018 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00002019 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002020
2021 // The space is compacted and we haven't yet wasted any space.
2022 ASSERT(Waste() == 0);
2023
2024 // Update allocation_top of each page in use and compute waste.
2025 int computed_size = 0;
2026 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
2027 while (it.has_next()) {
2028 Page* page = it.next();
2029 Address page_top = page->AllocationTop();
2030 computed_size += page_top - page->ObjectAreaStart();
2031 if (it.has_next()) {
2032 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
2033 }
2034 }
2035
2036 // Make sure the computed size - based on the used portion of the
2037 // pages in use - matches the size we adjust during allocation.
2038 ASSERT(computed_size == Size());
2039}
2040
2041
kasper.lund7276f142008-07-30 08:49:36 +00002042// Slow case for normal allocation. Try in order: (1) allocate in the next
2043// page in the space, (2) allocate off the space's free list, (3) expand the
2044// space, (4) fail.
2045HeapObject* MapSpace::SlowAllocateRaw(int size_in_bytes) {
2046 // Linear allocation in this space has failed. If there is another page
2047 // in the space, move to that page and allocate there. This allocation
2048 // should succeed.
2049 Page* current_page = TopPageOf(allocation_info_);
2050 if (current_page->next_page()->is_valid()) {
2051 return AllocateInNextPage(current_page, size_in_bytes);
2052 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002053
kasper.lund7276f142008-07-30 08:49:36 +00002054 // There is no next page in this space. Try free list allocation. The
2055 // map space free list implicitly assumes that all free blocks are map
2056 // sized.
2057 if (size_in_bytes == Map::kSize) {
2058 Object* result = free_list_.Allocate();
2059 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002060 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002061 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002062 }
2063 }
kasper.lund7276f142008-07-30 08:49:36 +00002064
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002065 // Free list allocation failed and there is no next page. Fail if we have
2066 // hit the old generation size limit that should cause a garbage
2067 // collection.
2068 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2069 return NULL;
2070 }
2071
2072 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00002073 ASSERT(!current_page->next_page()->is_valid());
2074 if (Expand(current_page)) {
2075 return AllocateInNextPage(current_page, size_in_bytes);
2076 }
2077
2078 // Finally, fail.
2079 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080}
2081
2082
kasper.lund7276f142008-07-30 08:49:36 +00002083// Move to the next page (there is assumed to be one) and allocate there.
2084// The top of page block is always wasted, because it is too small to hold a
2085// map.
2086HeapObject* MapSpace::AllocateInNextPage(Page* current_page,
2087 int size_in_bytes) {
2088 ASSERT(current_page->next_page()->is_valid());
2089 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == kPageExtra);
2090 accounting_stats_.WasteBytes(kPageExtra);
2091 SetAllocationInfo(&allocation_info_, current_page->next_page());
2092 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002093}
2094
2095
2096#ifdef DEBUG
2097// We do not assume that the PageIterator works, because it depends on the
2098// invariants we are checking during verification.
2099void MapSpace::Verify() {
2100 // The allocation pointer should be valid, and it should be in a page in the
2101 // space.
kasper.lund7276f142008-07-30 08:49:36 +00002102 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002103 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
2104 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
2105
2106 // Loop over all the pages.
2107 bool above_allocation_top = false;
2108 Page* current_page = first_page_;
2109 while (current_page->is_valid()) {
2110 if (above_allocation_top) {
2111 // We don't care what's above the allocation top.
2112 } else {
2113 // Unless this is the last page in the space containing allocated
2114 // objects, the allocation top should be at a constant offset from the
2115 // object area end.
2116 Address top = current_page->AllocationTop();
2117 if (current_page == top_page) {
2118 ASSERT(top == allocation_info_.top);
2119 // The next page will be above the allocation top.
2120 above_allocation_top = true;
2121 } else {
2122 ASSERT(top == current_page->ObjectAreaEnd() - kPageExtra);
2123 }
2124
2125 // It should be packed with objects from the bottom to the top.
2126 Address current = current_page->ObjectAreaStart();
2127 while (current < top) {
2128 HeapObject* object = HeapObject::FromAddress(current);
2129
2130 // The first word should be a map, and we expect all map pointers to
2131 // be in map space.
2132 Map* map = object->map();
2133 ASSERT(map->IsMap());
2134 ASSERT(Heap::map_space()->Contains(map));
2135
2136 // The object should be a map or a byte array.
2137 ASSERT(object->IsMap() || object->IsByteArray());
2138
2139 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002140 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002141
2142 // All the interior pointers should be contained in the heap and
2143 // have their remembered set bits set if they point to new space.
2144 VerifyPointersAndRSetVisitor visitor;
2145 int size = object->Size();
2146 object->IterateBody(map->instance_type(), size, &visitor);
2147
2148 current += size;
2149 }
2150
2151 // The allocation pointer should not be in the middle of an object.
2152 ASSERT(current == top);
2153 }
2154
2155 current_page = current_page->next_page();
2156 }
2157}
2158
2159
2160void MapSpace::ReportStatistics() {
2161 int pct = Available() * 100 / Capacity();
2162 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2163 Capacity(), Waste(), Available(), pct);
2164
2165 // Report remembered set statistics.
2166 int rset_marked_pointers = 0;
2167 int cross_gen_pointers = 0;
2168
2169 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2170 while (page_it.has_next()) {
2171 Page* p = page_it.next();
2172
2173 for (Address rset_addr = p->RSetStart();
2174 rset_addr < p->RSetEnd();
2175 rset_addr += kIntSize) {
2176 int rset = Memory::int_at(rset_addr);
2177 if (rset != 0) {
2178 // Bits were set
2179 int intoff = rset_addr - p->address();
2180 int bitoff = 0;
2181 for (; bitoff < kBitsPerInt; ++bitoff) {
2182 if ((rset & (1 << bitoff)) != 0) {
2183 int bitpos = intoff*kBitsPerByte + bitoff;
2184 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2185 Object** obj = reinterpret_cast<Object**>(slot);
2186 rset_marked_pointers++;
2187 if (Heap::InNewSpace(*obj))
2188 cross_gen_pointers++;
2189 }
2190 }
2191 }
2192 }
2193 }
2194
2195 pct = rset_marked_pointers == 0 ?
2196 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2197 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2198 rset_marked_pointers, cross_gen_pointers, pct);
2199
2200 ClearHistograms();
2201 HeapObjectIterator obj_it(this);
2202 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2203 ReportHistogram(false);
2204}
2205
2206
2207void MapSpace::PrintRSet() { DoPrintRSet("map"); }
2208#endif
2209
2210
2211// -----------------------------------------------------------------------------
2212// LargeObjectIterator
2213
2214LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2215 current_ = space->first_chunk_;
2216 size_func_ = NULL;
2217}
2218
2219
2220LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2221 HeapObjectCallback size_func) {
2222 current_ = space->first_chunk_;
2223 size_func_ = size_func;
2224}
2225
2226
2227HeapObject* LargeObjectIterator::next() {
2228 ASSERT(has_next());
2229 HeapObject* object = current_->GetObject();
2230 current_ = current_->next();
2231 return object;
2232}
2233
2234
2235// -----------------------------------------------------------------------------
2236// LargeObjectChunk
2237
2238LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002239 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002240 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002241 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002242 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2243 chunk_size,
2244 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002245 if (mem == NULL) return NULL;
2246 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2247 if (*chunk_size < requested) {
2248 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2249 LOG(DeleteEvent("LargeObjectChunk", mem));
2250 return NULL;
2251 }
2252 return reinterpret_cast<LargeObjectChunk*>(mem);
2253}
2254
2255
2256int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2257 int os_alignment = OS::AllocateAlignment();
2258 if (os_alignment < Page::kPageSize)
2259 size_in_bytes += (Page::kPageSize - os_alignment);
2260 return size_in_bytes + Page::kObjectStartOffset;
2261}
2262
2263// -----------------------------------------------------------------------------
2264// LargeObjectSpace
2265
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002266LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2267 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002268 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002269 size_(0),
2270 page_count_(0) {}
2271
2272
2273bool LargeObjectSpace::Setup() {
2274 first_chunk_ = NULL;
2275 size_ = 0;
2276 page_count_ = 0;
2277 return true;
2278}
2279
2280
2281void LargeObjectSpace::TearDown() {
2282 while (first_chunk_ != NULL) {
2283 LargeObjectChunk* chunk = first_chunk_;
2284 first_chunk_ = first_chunk_->next();
2285 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2286 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2287 }
2288
2289 size_ = 0;
2290 page_count_ = 0;
2291}
2292
2293
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002294#ifdef ENABLE_HEAP_PROTECTION
2295
2296void LargeObjectSpace::Protect() {
2297 LargeObjectChunk* chunk = first_chunk_;
2298 while (chunk != NULL) {
2299 MemoryAllocator::Protect(chunk->address(), chunk->size());
2300 chunk = chunk->next();
2301 }
2302}
2303
2304
2305void LargeObjectSpace::Unprotect() {
2306 LargeObjectChunk* chunk = first_chunk_;
2307 while (chunk != NULL) {
2308 bool is_code = chunk->GetObject()->IsCode();
2309 MemoryAllocator::Unprotect(chunk->address(), chunk->size(),
2310 is_code ? EXECUTABLE : NOT_EXECUTABLE);
2311 chunk = chunk->next();
2312 }
2313}
2314
2315#endif
2316
2317
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002318Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002319 int object_size,
2320 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002321 ASSERT(0 < object_size && object_size <= requested_size);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002322
2323 // Check if we want to force a GC before growing the old space further.
2324 // If so, fail the allocation.
2325 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2326 return Failure::RetryAfterGC(requested_size, identity());
2327 }
2328
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002329 size_t chunk_size;
2330 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002331 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002332 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002333 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002334 }
2335
2336 size_ += chunk_size;
2337 page_count_++;
2338 chunk->set_next(first_chunk_);
2339 chunk->set_size(chunk_size);
2340 first_chunk_ = chunk;
2341
2342 // Set the object address and size in the page header and clear its
2343 // remembered set.
2344 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2345 Address object_address = page->ObjectAreaStart();
2346 // Clear the low order bit of the second word in the page to flag it as a
2347 // large object page. If the chunk_size happened to be written there, its
2348 // low order bit should already be clear.
2349 ASSERT((chunk_size & 0x1) == 0);
2350 page->is_normal_page &= ~0x1;
2351 page->ClearRSet();
2352 int extra_bytes = requested_size - object_size;
2353 if (extra_bytes > 0) {
2354 // The extra memory for the remembered set should be cleared.
2355 memset(object_address + object_size, 0, extra_bytes);
2356 }
2357
2358 return HeapObject::FromAddress(object_address);
2359}
2360
2361
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002362Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002363 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002364 return AllocateRawInternal(size_in_bytes,
2365 size_in_bytes,
2366 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002367}
2368
2369
2370Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002371 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002372 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002373 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2374 size_in_bytes,
2375 NOT_EXECUTABLE);
2376}
2377
2378
2379Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2380 ASSERT(0 < size_in_bytes);
2381 return AllocateRawInternal(size_in_bytes,
2382 size_in_bytes,
2383 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002384}
2385
2386
2387// GC support
2388Object* LargeObjectSpace::FindObject(Address a) {
2389 for (LargeObjectChunk* chunk = first_chunk_;
2390 chunk != NULL;
2391 chunk = chunk->next()) {
2392 Address chunk_address = chunk->address();
2393 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2394 return chunk->GetObject();
2395 }
2396 }
2397 return Failure::Exception();
2398}
2399
2400
2401void LargeObjectSpace::ClearRSet() {
2402 ASSERT(Page::is_rset_in_use());
2403
2404 LargeObjectIterator it(this);
2405 while (it.has_next()) {
2406 HeapObject* object = it.next();
2407 // We only have code, sequential strings, or fixed arrays in large
2408 // object space, and only fixed arrays need remembered set support.
2409 if (object->IsFixedArray()) {
2410 // Clear the normal remembered set region of the page;
2411 Page* page = Page::FromAddress(object->address());
2412 page->ClearRSet();
2413
2414 // Clear the extra remembered set.
2415 int size = object->Size();
2416 int extra_rset_bytes = ExtraRSetBytesFor(size);
2417 memset(object->address() + size, 0, extra_rset_bytes);
2418 }
2419 }
2420}
2421
2422
2423void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2424 ASSERT(Page::is_rset_in_use());
2425
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002426 static void* lo_rset_histogram = StatsTable::CreateHistogram(
2427 "V8.RSetLO",
2428 0,
2429 // Keeping this histogram's buckets the same as the paged space histogram.
2430 Page::kObjectAreaSize / kPointerSize,
2431 30);
2432
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002433 LargeObjectIterator it(this);
2434 while (it.has_next()) {
2435 // We only have code, sequential strings, or fixed arrays in large
2436 // object space, and only fixed arrays can possibly contain pointers to
2437 // the young generation.
2438 HeapObject* object = it.next();
2439 if (object->IsFixedArray()) {
2440 // Iterate the normal page remembered set range.
2441 Page* page = Page::FromAddress(object->address());
2442 Address object_end = object->address() + object->Size();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002443 int count = Heap::IterateRSetRange(page->ObjectAreaStart(),
2444 Min(page->ObjectAreaEnd(), object_end),
2445 page->RSetStart(),
2446 copy_object_func);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002447
2448 // Iterate the extra array elements.
2449 if (object_end > page->ObjectAreaEnd()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002450 count += Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2451 object_end, copy_object_func);
2452 }
2453 if (lo_rset_histogram != NULL) {
2454 StatsTable::AddHistogramSample(lo_rset_histogram, count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002455 }
2456 }
2457 }
2458}
2459
2460
2461void LargeObjectSpace::FreeUnmarkedObjects() {
2462 LargeObjectChunk* previous = NULL;
2463 LargeObjectChunk* current = first_chunk_;
2464 while (current != NULL) {
2465 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002466 if (object->IsMarked()) {
2467 object->ClearMark();
2468 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002469 previous = current;
2470 current = current->next();
2471 } else {
2472 Address chunk_address = current->address();
2473 size_t chunk_size = current->size();
2474
2475 // Cut the chunk out from the chunk list.
2476 current = current->next();
2477 if (previous == NULL) {
2478 first_chunk_ = current;
2479 } else {
2480 previous->set_next(current);
2481 }
2482
2483 // Free the chunk.
2484 if (object->IsCode()) {
2485 LOG(CodeDeleteEvent(object->address()));
2486 }
2487 size_ -= chunk_size;
2488 page_count_--;
2489 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2490 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2491 }
2492 }
2493}
2494
2495
2496bool LargeObjectSpace::Contains(HeapObject* object) {
2497 Address address = object->address();
2498 Page* page = Page::FromAddress(address);
2499
2500 SLOW_ASSERT(!page->IsLargeObjectPage()
2501 || !FindObject(address)->IsFailure());
2502
2503 return page->IsLargeObjectPage();
2504}
2505
2506
2507#ifdef DEBUG
2508// We do not assume that the large object iterator works, because it depends
2509// on the invariants we are checking during verification.
2510void LargeObjectSpace::Verify() {
2511 for (LargeObjectChunk* chunk = first_chunk_;
2512 chunk != NULL;
2513 chunk = chunk->next()) {
2514 // Each chunk contains an object that starts at the large object page's
2515 // object area start.
2516 HeapObject* object = chunk->GetObject();
2517 Page* page = Page::FromAddress(object->address());
2518 ASSERT(object->address() == page->ObjectAreaStart());
2519
2520 // The first word should be a map, and we expect all map pointers to be
2521 // in map space.
2522 Map* map = object->map();
2523 ASSERT(map->IsMap());
2524 ASSERT(Heap::map_space()->Contains(map));
2525
2526 // We have only code, sequential strings, fixed arrays, and byte arrays
2527 // in large object space.
2528 ASSERT(object->IsCode() || object->IsSeqString()
2529 || object->IsFixedArray() || object->IsByteArray());
2530
2531 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002532 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002533
2534 // Byte arrays and strings don't have interior pointers.
2535 if (object->IsCode()) {
2536 VerifyPointersVisitor code_visitor;
2537 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2538 object->IterateBody(map->instance_type(),
2539 object->Size(),
2540 &code_visitor);
2541 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2542 } else if (object->IsFixedArray()) {
2543 // We loop over fixed arrays ourselves, rather then using the visitor,
2544 // because the visitor doesn't support the start/offset iteration
2545 // needed for IsRSetSet.
2546 FixedArray* array = FixedArray::cast(object);
2547 for (int j = 0; j < array->length(); j++) {
2548 Object* element = array->get(j);
2549 if (element->IsHeapObject()) {
2550 HeapObject* element_object = HeapObject::cast(element);
2551 ASSERT(Heap::Contains(element_object));
2552 ASSERT(element_object->map()->IsMap());
2553 if (Heap::InNewSpace(element_object)) {
2554 ASSERT(Page::IsRSetSet(object->address(),
2555 FixedArray::kHeaderSize + j * kPointerSize));
2556 }
2557 }
2558 }
2559 }
2560 }
2561}
2562
2563
2564void LargeObjectSpace::Print() {
2565 LargeObjectIterator it(this);
2566 while (it.has_next()) {
2567 it.next()->Print();
2568 }
2569}
2570
2571
2572void LargeObjectSpace::ReportStatistics() {
2573 PrintF(" size: %d\n", size_);
2574 int num_objects = 0;
2575 ClearHistograms();
2576 LargeObjectIterator it(this);
2577 while (it.has_next()) {
2578 num_objects++;
2579 CollectHistogramInfo(it.next());
2580 }
2581
2582 PrintF(" number of objects %d\n", num_objects);
2583 if (num_objects > 0) ReportHistogram(false);
2584}
2585
2586
2587void LargeObjectSpace::CollectCodeStatistics() {
2588 LargeObjectIterator obj_it(this);
2589 while (obj_it.has_next()) {
2590 HeapObject* obj = obj_it.next();
2591 if (obj->IsCode()) {
2592 Code* code = Code::cast(obj);
2593 code_kind_statistics[code->kind()] += code->Size();
2594 }
2595 }
2596}
2597
2598
2599void LargeObjectSpace::PrintRSet() {
2600 LargeObjectIterator it(this);
2601 while (it.has_next()) {
2602 HeapObject* object = it.next();
2603 if (object->IsFixedArray()) {
2604 Page* page = Page::FromAddress(object->address());
2605
2606 Address allocation_top = object->address() + object->Size();
2607 PrintF("large page 0x%x:\n", page);
2608 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2609 reinterpret_cast<Object**>(object->address()),
2610 allocation_top);
2611 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2612 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2613 kBitsPerInt);
2614 PrintF("------------------------------------------------------------"
2615 "-----------\n");
2616 PrintRSetRange(allocation_top,
2617 allocation_top + extra_rset_bits / kBitsPerByte,
2618 reinterpret_cast<Object**>(object->address()
2619 + Page::kObjectAreaSize),
2620 allocation_top);
2621 PrintF("\n");
2622 }
2623 }
2624}
2625#endif // DEBUG
2626
2627} } // namespace v8::internal