blob: 9f266cb0ea1c3c4f2ec38fc751566a13b83edf00 [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.orgdefbd102009-07-13 14:04:26 +000040 ASSERT((space).low() <= (info).top \
41 && (info).top <= (space).high() \
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000042 && (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;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000136 }
137}
138
139
140// -----------------------------------------------------------------------------
141// Page
142
143#ifdef DEBUG
144Page::RSetState Page::rset_state_ = Page::IN_USE;
145#endif
146
147// -----------------------------------------------------------------------------
148// MemoryAllocator
149//
150int MemoryAllocator::capacity_ = 0;
151int MemoryAllocator::size_ = 0;
152
153VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
154
155// 270 is an estimate based on the static default heap size of a pair of 256K
156// semispaces and a 64M old generation.
157const int kEstimatedNumberOfChunks = 270;
158List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
159 kEstimatedNumberOfChunks);
160List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
161int MemoryAllocator::max_nof_chunks_ = 0;
162int MemoryAllocator::top_ = 0;
163
164
165void MemoryAllocator::Push(int free_chunk_id) {
166 ASSERT(max_nof_chunks_ > 0);
167 ASSERT(top_ < max_nof_chunks_);
168 free_chunk_ids_[top_++] = free_chunk_id;
169}
170
171
172int MemoryAllocator::Pop() {
173 ASSERT(top_ > 0);
174 return free_chunk_ids_[--top_];
175}
176
177
178bool MemoryAllocator::Setup(int capacity) {
179 capacity_ = RoundUp(capacity, Page::kPageSize);
180
181 // Over-estimate the size of chunks_ array. It assumes the expansion of old
182 // space is always in the unit of a chunk (kChunkSize) except the last
183 // expansion.
184 //
185 // Due to alignment, allocated space might be one page less than required
186 // number (kPagesPerChunk) of pages for old spaces.
187 //
kasper.lund7276f142008-07-30 08:49:36 +0000188 // Reserve two chunk ids for semispaces, one for map space, one for old
189 // space, and one for code space.
190 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191 if (max_nof_chunks_ > kMaxNofChunks) return false;
192
193 size_ = 0;
194 ChunkInfo info; // uninitialized element.
195 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
196 chunks_.Add(info);
197 free_chunk_ids_.Add(i);
198 }
199 top_ = max_nof_chunks_;
200 return true;
201}
202
203
204void MemoryAllocator::TearDown() {
205 for (int i = 0; i < max_nof_chunks_; i++) {
206 if (chunks_[i].address() != NULL) DeleteChunk(i);
207 }
208 chunks_.Clear();
209 free_chunk_ids_.Clear();
210
211 if (initial_chunk_ != NULL) {
212 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
213 delete initial_chunk_;
214 initial_chunk_ = NULL;
215 }
216
217 ASSERT(top_ == max_nof_chunks_); // all chunks are free
218 top_ = 0;
219 capacity_ = 0;
220 size_ = 0;
221 max_nof_chunks_ = 0;
222}
223
224
225void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000226 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000227 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
229
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000230 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231 int alloced = *allocated;
232 size_ += alloced;
233 Counters::memory_allocated.Increment(alloced);
234 return mem;
235}
236
237
238void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
239 OS::Free(mem, length);
240 Counters::memory_allocated.Decrement(length);
241 size_ -= length;
242 ASSERT(size_ >= 0);
243}
244
245
246void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
247 ASSERT(initial_chunk_ == NULL);
248
249 initial_chunk_ = new VirtualMemory(requested);
250 CHECK(initial_chunk_ != NULL);
251 if (!initial_chunk_->IsReserved()) {
252 delete initial_chunk_;
253 initial_chunk_ = NULL;
254 return NULL;
255 }
256
257 // We are sure that we have mapped a block of requested addresses.
258 ASSERT(initial_chunk_->size() == requested);
259 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
260 size_ += requested;
261 return initial_chunk_->address();
262}
263
264
265static int PagesInChunk(Address start, size_t size) {
266 // The first page starts on the first page-aligned address from start onward
267 // and the last page ends on the last page-aligned address before
268 // start+size. Page::kPageSize is a power of two so we can divide by
269 // shifting.
270 return (RoundDown(start + size, Page::kPageSize)
271 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
272}
273
274
275Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
276 PagedSpace* owner) {
277 if (requested_pages <= 0) return Page::FromAddress(NULL);
278 size_t chunk_size = requested_pages * Page::kPageSize;
279
280 // There is not enough space to guarantee the desired number pages can be
281 // allocated.
282 if (size_ + static_cast<int>(chunk_size) > capacity_) {
283 // Request as many pages as we can.
284 chunk_size = capacity_ - size_;
285 requested_pages = chunk_size >> Page::kPageSizeBits;
286
287 if (requested_pages <= 0) return Page::FromAddress(NULL);
288 }
kasper.lund7276f142008-07-30 08:49:36 +0000289 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 if (chunk == NULL) return Page::FromAddress(NULL);
291 LOG(NewEvent("PagedChunk", chunk, chunk_size));
292
293 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
294 if (*allocated_pages == 0) {
295 FreeRawMemory(chunk, chunk_size);
296 LOG(DeleteEvent("PagedChunk", chunk));
297 return Page::FromAddress(NULL);
298 }
299
300 int chunk_id = Pop();
301 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
302
303 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
304}
305
306
307Page* MemoryAllocator::CommitPages(Address start, size_t size,
308 PagedSpace* owner, int* num_pages) {
309 ASSERT(start != NULL);
310 *num_pages = PagesInChunk(start, size);
311 ASSERT(*num_pages > 0);
312 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000313 ASSERT(InInitialChunk(start));
314 ASSERT(InInitialChunk(start + size - 1));
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000315 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316 return Page::FromAddress(NULL);
317 }
318 Counters::memory_allocated.Increment(size);
319
320 // So long as we correctly overestimated the number of chunks we should not
321 // run out of chunk ids.
322 CHECK(!OutOfChunkIds());
323 int chunk_id = Pop();
324 chunks_[chunk_id].init(start, size, owner);
325 return InitializePagesInChunk(chunk_id, *num_pages, owner);
326}
327
328
kasper.lund7276f142008-07-30 08:49:36 +0000329bool MemoryAllocator::CommitBlock(Address start,
330 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000331 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000332 ASSERT(start != NULL);
333 ASSERT(size > 0);
334 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000335 ASSERT(InInitialChunk(start));
336 ASSERT(InInitialChunk(start + size - 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000337
kasper.lund7276f142008-07-30 08:49:36 +0000338 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 Counters::memory_allocated.Increment(size);
340 return true;
341}
342
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000343bool MemoryAllocator::UncommitBlock(Address start, size_t size) {
344 ASSERT(start != NULL);
345 ASSERT(size > 0);
346 ASSERT(initial_chunk_ != NULL);
347 ASSERT(InInitialChunk(start));
348 ASSERT(InInitialChunk(start + size - 1));
349
350 if (!initial_chunk_->Uncommit(start, size)) return false;
351 Counters::memory_allocated.Decrement(size);
352 return true;
353}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000354
355Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
356 PagedSpace* owner) {
357 ASSERT(IsValidChunk(chunk_id));
358 ASSERT(pages_in_chunk > 0);
359
360 Address chunk_start = chunks_[chunk_id].address();
361
362 Address low = RoundUp(chunk_start, Page::kPageSize);
363
364#ifdef DEBUG
365 size_t chunk_size = chunks_[chunk_id].size();
366 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
367 ASSERT(pages_in_chunk <=
368 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
369#endif
370
371 Address page_addr = low;
372 for (int i = 0; i < pages_in_chunk; i++) {
373 Page* p = Page::FromAddress(page_addr);
374 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
375 p->is_normal_page = 1;
376 page_addr += Page::kPageSize;
377 }
378
379 // Set the next page of the last page to 0.
380 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
381 last_page->opaque_header = OffsetFrom(0) | chunk_id;
382
383 return Page::FromAddress(low);
384}
385
386
387Page* MemoryAllocator::FreePages(Page* p) {
388 if (!p->is_valid()) return p;
389
390 // Find the first page in the same chunk as 'p'
391 Page* first_page = FindFirstPageInSameChunk(p);
392 Page* page_to_return = Page::FromAddress(NULL);
393
394 if (p != first_page) {
395 // Find the last page in the same chunk as 'prev'.
396 Page* last_page = FindLastPageInSameChunk(p);
397 first_page = GetNextPage(last_page); // first page in next chunk
398
399 // set the next_page of last_page to NULL
400 SetNextPage(last_page, Page::FromAddress(NULL));
401 page_to_return = p; // return 'p' when exiting
402 }
403
404 while (first_page->is_valid()) {
405 int chunk_id = GetChunkId(first_page);
406 ASSERT(IsValidChunk(chunk_id));
407
408 // Find the first page of the next chunk before deleting this chunk.
409 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
410
411 // Free the current chunk.
412 DeleteChunk(chunk_id);
413 }
414
415 return page_to_return;
416}
417
418
419void MemoryAllocator::DeleteChunk(int chunk_id) {
420 ASSERT(IsValidChunk(chunk_id));
421
422 ChunkInfo& c = chunks_[chunk_id];
423
424 // We cannot free a chunk contained in the initial chunk because it was not
425 // allocated with AllocateRawMemory. Instead we uncommit the virtual
426 // memory.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000427 if (InInitialChunk(c.address())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000428 // TODO(1240712): VirtualMemory::Uncommit has a return value which
429 // is ignored here.
430 initial_chunk_->Uncommit(c.address(), c.size());
431 Counters::memory_allocated.Decrement(c.size());
432 } else {
433 LOG(DeleteEvent("PagedChunk", c.address()));
434 FreeRawMemory(c.address(), c.size());
435 }
436 c.init(NULL, 0, NULL);
437 Push(chunk_id);
438}
439
440
441Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
442 int chunk_id = GetChunkId(p);
443 ASSERT(IsValidChunk(chunk_id));
444
445 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
446 return Page::FromAddress(low);
447}
448
449
450Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
451 int chunk_id = GetChunkId(p);
452 ASSERT(IsValidChunk(chunk_id));
453
454 Address chunk_start = chunks_[chunk_id].address();
455 size_t chunk_size = chunks_[chunk_id].size();
456
457 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
458 ASSERT(chunk_start <= p->address() && p->address() < high);
459
460 return Page::FromAddress(high - Page::kPageSize);
461}
462
463
464#ifdef DEBUG
465void MemoryAllocator::ReportStatistics() {
466 float pct = static_cast<float>(capacity_ - size_) / capacity_;
467 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
468 capacity_, size_, static_cast<int>(pct*100));
469}
470#endif
471
472
473// -----------------------------------------------------------------------------
474// PagedSpace implementation
475
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000476PagedSpace::PagedSpace(int max_capacity,
477 AllocationSpace id,
478 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000479 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
481 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482 accounting_stats_.Clear();
483
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000484 allocation_info_.top = NULL;
485 allocation_info_.limit = NULL;
486
487 mc_forwarding_info_.top = NULL;
488 mc_forwarding_info_.limit = NULL;
489}
490
491
492bool PagedSpace::Setup(Address start, size_t size) {
493 if (HasBeenSetup()) return false;
494
495 int num_pages = 0;
496 // Try to use the virtual memory range passed to us. If it is too small to
497 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000498 int pages_in_chunk = PagesInChunk(start, size);
499 if (pages_in_chunk > 0) {
500 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
501 Page::kPageSize * pages_in_chunk,
502 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000503 } else {
504 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
505 max_capacity_ / Page::kObjectAreaSize);
506 first_page_ =
507 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
508 if (!first_page_->is_valid()) return false;
509 }
510
511 // We are sure that the first page is valid and that we have at least one
512 // page.
513 ASSERT(first_page_->is_valid());
514 ASSERT(num_pages > 0);
515 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
516 ASSERT(Capacity() <= max_capacity_);
517
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000518 // Sequentially initialize remembered sets in the newly allocated
519 // pages and cache the current last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
521 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000522 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000523 }
524
525 // Use first_page_ for allocation.
526 SetAllocationInfo(&allocation_info_, first_page_);
527
528 return true;
529}
530
531
532bool PagedSpace::HasBeenSetup() {
533 return (Capacity() > 0);
534}
535
536
537void PagedSpace::TearDown() {
538 first_page_ = MemoryAllocator::FreePages(first_page_);
539 ASSERT(!first_page_->is_valid());
540
541 accounting_stats_.Clear();
542}
543
544
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000545#ifdef ENABLE_HEAP_PROTECTION
546
547void PagedSpace::Protect() {
548 Page* page = first_page_;
549 while (page->is_valid()) {
550 MemoryAllocator::ProtectChunkFromPage(page);
551 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
552 }
553}
554
555
556void PagedSpace::Unprotect() {
557 Page* page = first_page_;
558 while (page->is_valid()) {
559 MemoryAllocator::UnprotectChunkFromPage(page);
560 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
561 }
562}
563
564#endif
565
566
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000567void PagedSpace::ClearRSet() {
568 PageIterator it(this, PageIterator::ALL_PAGES);
569 while (it.has_next()) {
570 it.next()->ClearRSet();
571 }
572}
573
574
575Object* PagedSpace::FindObject(Address addr) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 // Note: this function can only be called before or after mark-compact GC
577 // because it accesses map pointers.
578 ASSERT(!MarkCompactCollector::in_use());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579
580 if (!Contains(addr)) return Failure::Exception();
581
582 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000583 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000584 Address cur = p->ObjectAreaStart();
585 Address end = p->AllocationTop();
586 while (cur < end) {
587 HeapObject* obj = HeapObject::FromAddress(cur);
588 Address next = cur + obj->Size();
589 if ((cur <= addr) && (addr < next)) return obj;
590 cur = next;
591 }
592
kasper.lund7276f142008-07-30 08:49:36 +0000593 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594 return Failure::Exception();
595}
596
597
kasper.lund7276f142008-07-30 08:49:36 +0000598bool PagedSpace::IsUsed(Page* page) {
599 PageIterator it(this, PageIterator::PAGES_IN_USE);
600 while (it.has_next()) {
601 if (page == it.next()) return true;
602 }
603 return false;
604}
605
606
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
608 alloc_info->top = p->ObjectAreaStart();
609 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000610 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611}
612
613
614void PagedSpace::MCResetRelocationInfo() {
615 // Set page indexes.
616 int i = 0;
617 PageIterator it(this, PageIterator::ALL_PAGES);
618 while (it.has_next()) {
619 Page* p = it.next();
620 p->mc_page_index = i++;
621 }
622
623 // Set mc_forwarding_info_ to the first page in the space.
624 SetAllocationInfo(&mc_forwarding_info_, first_page_);
625 // All the bytes in the space are 'available'. We will rediscover
626 // allocated and wasted bytes during GC.
627 accounting_stats_.Reset();
628}
629
630
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
632#ifdef DEBUG
633 // The Contains function considers the address at the beginning of a
634 // page in the page, MCSpaceOffsetForAddress considers it is in the
635 // previous page.
636 if (Page::IsAlignedToPageSize(addr)) {
637 ASSERT(Contains(addr - kPointerSize));
638 } else {
639 ASSERT(Contains(addr));
640 }
641#endif
642
643 // If addr is at the end of a page, it belongs to previous page
644 Page* p = Page::IsAlignedToPageSize(addr)
645 ? Page::FromAllocationTop(addr)
646 : Page::FromAddress(addr);
647 int index = p->mc_page_index;
648 return (index * Page::kPageSize) + p->Offset(addr);
649}
650
651
kasper.lund7276f142008-07-30 08:49:36 +0000652// Slow case for reallocating and promoting objects during a compacting
653// collection. This function is not space-specific.
654HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
655 Page* current_page = TopPageOf(mc_forwarding_info_);
656 if (!current_page->next_page()->is_valid()) {
657 if (!Expand(current_page)) {
658 return NULL;
659 }
660 }
661
662 // There are surely more pages in the space now.
663 ASSERT(current_page->next_page()->is_valid());
664 // We do not add the top of page block for current page to the space's
665 // free list---the block may contain live objects so we cannot write
666 // bookkeeping information to it. Instead, we will recover top of page
667 // blocks when we move objects to their new locations.
668 //
669 // We do however write the allocation pointer to the page. The encoding
670 // of forwarding addresses is as an offset in terms of live bytes, so we
671 // need quick access to the allocation top of each page to decode
672 // forwarding addresses.
673 current_page->mc_relocation_top = mc_forwarding_info_.top;
674 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
675 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
676}
677
678
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000679bool PagedSpace::Expand(Page* last_page) {
680 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
681 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
682
683 if (Capacity() == max_capacity_) return false;
684
685 ASSERT(Capacity() < max_capacity_);
686 // Last page must be valid and its next page is invalid.
687 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
688
689 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
690 if (available_pages <= 0) return false;
691
692 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
693 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
694 if (!p->is_valid()) return false;
695
696 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
697 ASSERT(Capacity() <= max_capacity_);
698
699 MemoryAllocator::SetNextPage(last_page, p);
700
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000701 // Sequentially clear remembered set of new pages and and cache the
702 // new last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703 while (p->is_valid()) {
704 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000705 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706 p = p->next_page();
707 }
708
709 return true;
710}
711
712
713#ifdef DEBUG
714int PagedSpace::CountTotalPages() {
715 int count = 0;
716 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
717 count++;
718 }
719 return count;
720}
721#endif
722
723
724void PagedSpace::Shrink() {
725 // Release half of free pages.
726 Page* top_page = AllocationTopPage();
727 ASSERT(top_page->is_valid());
728
729 // Loop over the pages from the top page to the end of the space to count
730 // the number of pages to keep and find the last page to keep.
731 int free_pages = 0;
732 int pages_to_keep = 0; // Of the free pages.
733 Page* last_page_to_keep = top_page;
734 Page* current_page = top_page->next_page();
735 // Loop over the pages to the end of the space.
736 while (current_page->is_valid()) {
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000737#if defined(ANDROID)
738 // Free all chunks if possible
739#else
kasper.lund7276f142008-07-30 08:49:36 +0000740 // Advance last_page_to_keep every other step to end up at the midpoint.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000741 if ((free_pages & 0x1) == 1) {
742 pages_to_keep++;
743 last_page_to_keep = last_page_to_keep->next_page();
744 }
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000745#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000746 free_pages++;
747 current_page = current_page->next_page();
748 }
749
750 // Free pages after last_page_to_keep, and adjust the next_page link.
751 Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
752 MemoryAllocator::SetNextPage(last_page_to_keep, p);
753
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000754 // Since pages are only freed in whole chunks, we may have kept more
755 // than pages_to_keep. Count the extra pages and cache the new last
756 // page in the space.
757 last_page_ = last_page_to_keep;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758 while (p->is_valid()) {
759 pages_to_keep++;
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000760 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000761 p = p->next_page();
762 }
763
764 // The difference between free_pages and pages_to_keep is the number of
765 // pages actually freed.
766 ASSERT(pages_to_keep <= free_pages);
767 int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
768 accounting_stats_.ShrinkSpace(bytes_freed);
769
770 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
771}
772
773
774bool PagedSpace::EnsureCapacity(int capacity) {
775 if (Capacity() >= capacity) return true;
776
777 // Start from the allocation top and loop to the last page in the space.
778 Page* last_page = AllocationTopPage();
779 Page* next_page = last_page->next_page();
780 while (next_page->is_valid()) {
781 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
782 next_page = last_page->next_page();
783 }
784
785 // Expand the space until it has the required capacity or expansion fails.
786 do {
787 if (!Expand(last_page)) return false;
788 ASSERT(last_page->next_page()->is_valid());
789 last_page =
790 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
791 } while (Capacity() < capacity);
792
793 return true;
794}
795
796
797#ifdef DEBUG
798void PagedSpace::Print() { }
799#endif
800
801
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000802#ifdef DEBUG
803// We do not assume that the PageIterator works, because it depends on the
804// invariants we are checking during verification.
805void PagedSpace::Verify(ObjectVisitor* visitor) {
806 // The allocation pointer should be valid, and it should be in a page in the
807 // space.
808 ASSERT(allocation_info_.VerifyPagedAllocation());
809 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
810 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
811
812 // Loop over all the pages.
813 bool above_allocation_top = false;
814 Page* current_page = first_page_;
815 while (current_page->is_valid()) {
816 if (above_allocation_top) {
817 // We don't care what's above the allocation top.
818 } else {
819 // Unless this is the last page in the space containing allocated
820 // objects, the allocation top should be at a constant offset from the
821 // object area end.
822 Address top = current_page->AllocationTop();
823 if (current_page == top_page) {
824 ASSERT(top == allocation_info_.top);
825 // The next page will be above the allocation top.
826 above_allocation_top = true;
827 } else {
828 ASSERT(top == current_page->ObjectAreaEnd() - page_extra_);
829 }
830
831 // It should be packed with objects from the bottom to the top.
832 Address current = current_page->ObjectAreaStart();
833 while (current < top) {
834 HeapObject* object = HeapObject::FromAddress(current);
835
836 // The first word should be a map, and we expect all map pointers to
837 // be in map space.
838 Map* map = object->map();
839 ASSERT(map->IsMap());
840 ASSERT(Heap::map_space()->Contains(map));
841
842 // Perform space-specific object verification.
843 VerifyObject(object);
844
845 // The object itself should look OK.
846 object->Verify();
847
848 // All the interior pointers should be contained in the heap and
849 // have their remembered set bits set if required as determined
850 // by the visitor.
851 int size = object->Size();
852 if (object->IsCode()) {
853 Code::cast(object)->ConvertICTargetsFromAddressToObject();
854 object->IterateBody(map->instance_type(), size, visitor);
855 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
856 } else {
857 object->IterateBody(map->instance_type(), size, visitor);
858 }
859
860 current += size;
861 }
862
863 // The allocation pointer should not be in the middle of an object.
864 ASSERT(current == top);
865 }
866
867 current_page = current_page->next_page();
868 }
869}
870#endif
871
872
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873// -----------------------------------------------------------------------------
874// NewSpace implementation
875
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000876
877bool NewSpace::Setup(Address start, int size) {
878 // Setup new space based on the preallocated memory block defined by
879 // start and size. The provided space is divided into two semi-spaces.
880 // To support fast containment testing in the new space, the size of
881 // this chunk must be a power of two and it must be aligned to its size.
882 int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
883 int maximum_semispace_capacity = Heap::SemiSpaceSize();
884
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000885 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
886 ASSERT(IsPowerOf2(maximum_semispace_capacity));
887 maximum_capacity_ = maximum_semispace_capacity;
888 capacity_ = initial_semispace_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000889
890 // Allocate and setup the histogram arrays if necessary.
891#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
892 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
893 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
894
895#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
896 promoted_histogram_[name].set_name(#name);
897 INSTANCE_TYPE_LIST(SET_NAME)
898#undef SET_NAME
899#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000901 ASSERT(size == 2 * maximum_capacity_);
902 ASSERT(IsAddressAligned(start, size, 0));
903
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000904 if (!to_space_.Setup(start, capacity_, maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000905 return false;
906 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000907 if (!from_space_.Setup(start + maximum_capacity_,
908 capacity_,
909 maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910 return false;
911 }
912
913 start_ = start;
914 address_mask_ = ~(size - 1);
915 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000916 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000918 allocation_info_.top = to_space_.low();
919 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000920 mc_forwarding_info_.top = NULL;
921 mc_forwarding_info_.limit = NULL;
922
923 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
924 return true;
925}
926
927
928void NewSpace::TearDown() {
929#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
930 if (allocated_histogram_) {
931 DeleteArray(allocated_histogram_);
932 allocated_histogram_ = NULL;
933 }
934 if (promoted_histogram_) {
935 DeleteArray(promoted_histogram_);
936 promoted_histogram_ = NULL;
937 }
938#endif
939
940 start_ = NULL;
941 capacity_ = 0;
942 allocation_info_.top = NULL;
943 allocation_info_.limit = NULL;
944 mc_forwarding_info_.top = NULL;
945 mc_forwarding_info_.limit = NULL;
946
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000947 to_space_.TearDown();
948 from_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000949}
950
951
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000952#ifdef ENABLE_HEAP_PROTECTION
953
954void NewSpace::Protect() {
955 MemoryAllocator::Protect(ToSpaceLow(), Capacity());
956 MemoryAllocator::Protect(FromSpaceLow(), Capacity());
957}
958
959
960void NewSpace::Unprotect() {
961 MemoryAllocator::Unprotect(ToSpaceLow(), Capacity(),
962 to_space_.executable());
963 MemoryAllocator::Unprotect(FromSpaceLow(), Capacity(),
964 from_space_.executable());
965}
966
967#endif
968
969
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000970void NewSpace::Flip() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000971 SemiSpace tmp = from_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000972 from_space_ = to_space_;
973 to_space_ = tmp;
974}
975
976
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000977bool NewSpace::Grow() {
978 ASSERT(capacity_ < maximum_capacity_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000979 // TODO(1240712): Failure to double the from space can result in
980 // semispaces of different sizes. In the event of that failure, the
981 // to space doubling should be rolled back before returning false.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000982 if (!to_space_.Grow() || !from_space_.Grow()) return false;
983 capacity_ = to_space_.Capacity() + from_space_.Capacity();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000984 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000985 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
986 return true;
987}
988
989
990void NewSpace::ResetAllocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000991 allocation_info_.top = to_space_.low();
992 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000993 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
994}
995
996
997void NewSpace::MCResetRelocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000998 mc_forwarding_info_.top = from_space_.low();
999 mc_forwarding_info_.limit = from_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001000 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
1001}
1002
1003
1004void NewSpace::MCCommitRelocationInfo() {
1005 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
1006 // valid allocation info for the to space.
1007 allocation_info_.top = mc_forwarding_info_.top;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001008 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001009 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
1010}
1011
1012
1013#ifdef DEBUG
1014// We do not use the SemispaceIterator because verification doesn't assume
1015// that it works (it depends on the invariants we are checking).
1016void NewSpace::Verify() {
1017 // The allocation pointer should be in the space or at the very end.
1018 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
1019
1020 // There should be objects packed in from the low address up to the
1021 // allocation pointer.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001022 Address current = to_space_.low();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001023 while (current < top()) {
1024 HeapObject* object = HeapObject::FromAddress(current);
1025
1026 // The first word should be a map, and we expect all map pointers to
1027 // be in map space.
1028 Map* map = object->map();
1029 ASSERT(map->IsMap());
1030 ASSERT(Heap::map_space()->Contains(map));
1031
1032 // The object should not be code or a map.
1033 ASSERT(!object->IsMap());
1034 ASSERT(!object->IsCode());
1035
1036 // The object itself should look OK.
1037 object->Verify();
1038
1039 // All the interior pointers should be contained in the heap.
1040 VerifyPointersVisitor visitor;
1041 int size = object->Size();
1042 object->IterateBody(map->instance_type(), size, &visitor);
1043
1044 current += size;
1045 }
1046
1047 // The allocation pointer should not be in the middle of an object.
1048 ASSERT(current == top());
1049}
1050#endif
1051
1052
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001053bool SemiSpace::Commit() {
1054 ASSERT(!is_committed());
1055 if (!MemoryAllocator::CommitBlock(start_, capacity_, executable())) {
1056 return false;
1057 }
1058 committed_ = true;
1059 return true;
1060}
1061
1062
1063bool SemiSpace::Uncommit() {
1064 ASSERT(is_committed());
1065 if (!MemoryAllocator::UncommitBlock(start_, capacity_)) {
1066 return false;
1067 }
1068 committed_ = false;
1069 return true;
1070}
1071
1072
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001073// -----------------------------------------------------------------------------
1074// SemiSpace implementation
1075
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001076bool SemiSpace::Setup(Address start,
1077 int initial_capacity,
1078 int maximum_capacity) {
1079 // Creates a space in the young generation. The constructor does not
1080 // allocate memory from the OS. A SemiSpace is given a contiguous chunk of
1081 // memory of size 'capacity' when set up, and does not grow or shrink
1082 // otherwise. In the mark-compact collector, the memory region of the from
1083 // space is used as the marking stack. It requires contiguous memory
1084 // addresses.
1085 capacity_ = initial_capacity;
1086 maximum_capacity_ = maximum_capacity;
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001087 committed_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001088
1089 start_ = start;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001090 address_mask_ = ~(maximum_capacity - 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001091 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +00001092 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001093 age_mark_ = start_;
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001094
1095 return Commit();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001096}
1097
1098
1099void SemiSpace::TearDown() {
1100 start_ = NULL;
1101 capacity_ = 0;
1102}
1103
1104
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001105bool SemiSpace::Grow() {
1106 // Commit 50% extra space but only up to maximum capacity.
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001107 int extra = RoundUp(capacity_ / 2, OS::AllocateAlignment());
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001108 if (capacity_ + extra > maximum_capacity_) {
1109 extra = maximum_capacity_ - capacity_;
1110 }
1111 if (!MemoryAllocator::CommitBlock(high(), extra, executable())) {
kasper.lund7276f142008-07-30 08:49:36 +00001112 return false;
1113 }
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001114 capacity_ += extra;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001115 return true;
1116}
1117
1118
1119#ifdef DEBUG
1120void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001121
1122
1123void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001124#endif
1125
1126
1127// -----------------------------------------------------------------------------
1128// SemiSpaceIterator implementation.
1129SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
1130 Initialize(space, space->bottom(), space->top(), NULL);
1131}
1132
1133
1134SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
1135 HeapObjectCallback size_func) {
1136 Initialize(space, space->bottom(), space->top(), size_func);
1137}
1138
1139
1140SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
1141 Initialize(space, start, space->top(), NULL);
1142}
1143
1144
1145void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
1146 Address end,
1147 HeapObjectCallback size_func) {
1148 ASSERT(space->ToSpaceContains(start));
1149 ASSERT(space->ToSpaceLow() <= end
1150 && end <= space->ToSpaceHigh());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001151 space_ = &space->to_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152 current_ = start;
1153 limit_ = end;
1154 size_func_ = size_func;
1155}
1156
1157
1158#ifdef DEBUG
1159// A static array of histogram info for each type.
1160static HistogramInfo heap_histograms[LAST_TYPE+1];
1161static JSObject::SpillInformation js_spill_information;
1162
1163// heap_histograms is shared, always clear it before using it.
1164static void ClearHistograms() {
1165 // We reset the name each time, though it hasn't changed.
1166#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1167 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1168#undef DEF_TYPE_NAME
1169
1170#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1171 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1172#undef CLEAR_HISTOGRAM
1173
1174 js_spill_information.Clear();
1175}
1176
1177
1178static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1179
1180
1181static void ClearCodeKindStatistics() {
1182 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1183 code_kind_statistics[i] = 0;
1184 }
1185}
1186
1187
1188static void ReportCodeKindStatistics() {
1189 const char* table[Code::NUMBER_OF_KINDS];
1190
1191#define CASE(name) \
1192 case Code::name: table[Code::name] = #name; \
1193 break
1194
1195 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1196 switch (static_cast<Code::Kind>(i)) {
1197 CASE(FUNCTION);
1198 CASE(STUB);
1199 CASE(BUILTIN);
1200 CASE(LOAD_IC);
1201 CASE(KEYED_LOAD_IC);
1202 CASE(STORE_IC);
1203 CASE(KEYED_STORE_IC);
1204 CASE(CALL_IC);
1205 }
1206 }
1207
1208#undef CASE
1209
1210 PrintF("\n Code kind histograms: \n");
1211 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1212 if (code_kind_statistics[i] > 0) {
1213 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1214 }
1215 }
1216 PrintF("\n");
1217}
1218
1219
1220static int CollectHistogramInfo(HeapObject* obj) {
1221 InstanceType type = obj->map()->instance_type();
1222 ASSERT(0 <= type && type <= LAST_TYPE);
1223 ASSERT(heap_histograms[type].name() != NULL);
1224 heap_histograms[type].increment_number(1);
1225 heap_histograms[type].increment_bytes(obj->Size());
1226
1227 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1228 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1229 }
1230
1231 return obj->Size();
1232}
1233
1234
1235static void ReportHistogram(bool print_spill) {
1236 PrintF("\n Object Histogram:\n");
1237 for (int i = 0; i <= LAST_TYPE; i++) {
1238 if (heap_histograms[i].number() > 0) {
1239 PrintF(" %-33s%10d (%10d bytes)\n",
1240 heap_histograms[i].name(),
1241 heap_histograms[i].number(),
1242 heap_histograms[i].bytes());
1243 }
1244 }
1245 PrintF("\n");
1246
1247 // Summarize string types.
1248 int string_number = 0;
1249 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001250#define INCREMENT(type, size, name, camel_name) \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001251 string_number += heap_histograms[type].number(); \
1252 string_bytes += heap_histograms[type].bytes();
1253 STRING_TYPE_LIST(INCREMENT)
1254#undef INCREMENT
1255 if (string_number > 0) {
1256 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1257 string_bytes);
1258 }
1259
1260 if (FLAG_collect_heap_spill_statistics && print_spill) {
1261 js_spill_information.Print();
1262 }
1263}
1264#endif // DEBUG
1265
1266
1267// Support for statistics gathering for --heap-stats and --log-gc.
1268#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1269void NewSpace::ClearHistograms() {
1270 for (int i = 0; i <= LAST_TYPE; i++) {
1271 allocated_histogram_[i].clear();
1272 promoted_histogram_[i].clear();
1273 }
1274}
1275
1276// Because the copying collector does not touch garbage objects, we iterate
1277// the new space before a collection to get a histogram of allocated objects.
1278// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1279// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1280// flag is set.
1281void NewSpace::CollectStatistics() {
1282 ClearHistograms();
1283 SemiSpaceIterator it(this);
1284 while (it.has_next()) RecordAllocation(it.next());
1285}
1286
1287
1288#ifdef ENABLE_LOGGING_AND_PROFILING
1289static void DoReportStatistics(HistogramInfo* info, const char* description) {
1290 LOG(HeapSampleBeginEvent("NewSpace", description));
1291 // Lump all the string types together.
1292 int string_number = 0;
1293 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001294#define INCREMENT(type, size, name, camel_name) \
1295 string_number += info[type].number(); \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001296 string_bytes += info[type].bytes();
1297 STRING_TYPE_LIST(INCREMENT)
1298#undef INCREMENT
1299 if (string_number > 0) {
1300 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1301 }
1302
1303 // Then do the other types.
1304 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1305 if (info[i].number() > 0) {
1306 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1307 info[i].bytes()));
1308 }
1309 }
1310 LOG(HeapSampleEndEvent("NewSpace", description));
1311}
1312#endif // ENABLE_LOGGING_AND_PROFILING
1313
1314
1315void NewSpace::ReportStatistics() {
1316#ifdef DEBUG
1317 if (FLAG_heap_stats) {
1318 float pct = static_cast<float>(Available()) / Capacity();
1319 PrintF(" capacity: %d, available: %d, %%%d\n",
1320 Capacity(), Available(), static_cast<int>(pct*100));
1321 PrintF("\n Object Histogram:\n");
1322 for (int i = 0; i <= LAST_TYPE; i++) {
1323 if (allocated_histogram_[i].number() > 0) {
1324 PrintF(" %-33s%10d (%10d bytes)\n",
1325 allocated_histogram_[i].name(),
1326 allocated_histogram_[i].number(),
1327 allocated_histogram_[i].bytes());
1328 }
1329 }
1330 PrintF("\n");
1331 }
1332#endif // DEBUG
1333
1334#ifdef ENABLE_LOGGING_AND_PROFILING
1335 if (FLAG_log_gc) {
1336 DoReportStatistics(allocated_histogram_, "allocated");
1337 DoReportStatistics(promoted_histogram_, "promoted");
1338 }
1339#endif // ENABLE_LOGGING_AND_PROFILING
1340}
1341
1342
1343void NewSpace::RecordAllocation(HeapObject* obj) {
1344 InstanceType type = obj->map()->instance_type();
1345 ASSERT(0 <= type && type <= LAST_TYPE);
1346 allocated_histogram_[type].increment_number(1);
1347 allocated_histogram_[type].increment_bytes(obj->Size());
1348}
1349
1350
1351void NewSpace::RecordPromotion(HeapObject* obj) {
1352 InstanceType type = obj->map()->instance_type();
1353 ASSERT(0 <= type && type <= LAST_TYPE);
1354 promoted_histogram_[type].increment_number(1);
1355 promoted_histogram_[type].increment_bytes(obj->Size());
1356}
1357#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1358
1359
1360// -----------------------------------------------------------------------------
1361// Free lists for old object spaces implementation
1362
1363void FreeListNode::set_size(int size_in_bytes) {
1364 ASSERT(size_in_bytes > 0);
1365 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1366
1367 // We write a map and possibly size information to the block. If the block
1368 // is big enough to be a ByteArray with at least one extra word (the next
1369 // pointer), we set its map to be the byte array map and its size to an
1370 // appropriate array length for the desired size from HeapObject::Size().
1371 // If the block is too small (eg, one or two words), to hold both a size
1372 // field and a next pointer, we give it a filler map that gives it the
1373 // correct size.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001374 if (size_in_bytes > ByteArray::kAlignedSize) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001375 set_map(Heap::raw_unchecked_byte_array_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001376 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1377 } else if (size_in_bytes == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001378 set_map(Heap::raw_unchecked_one_pointer_filler_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001379 } else if (size_in_bytes == 2 * kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001380 set_map(Heap::raw_unchecked_two_pointer_filler_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001381 } else {
1382 UNREACHABLE();
1383 }
kasper.lund7276f142008-07-30 08:49:36 +00001384 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001385}
1386
1387
1388Address FreeListNode::next() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001389 ASSERT(map() == Heap::raw_unchecked_byte_array_map() ||
1390 map() == Heap::raw_unchecked_two_pointer_filler_map());
1391 if (map() == Heap::raw_unchecked_byte_array_map()) {
1392 ASSERT(Size() >= kNextOffset + kPointerSize);
1393 return Memory::Address_at(address() + kNextOffset);
1394 } else {
1395 return Memory::Address_at(address() + kPointerSize);
1396 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001397}
1398
1399
1400void FreeListNode::set_next(Address next) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001401 ASSERT(map() == Heap::raw_unchecked_byte_array_map() ||
1402 map() == Heap::raw_unchecked_two_pointer_filler_map());
1403 if (map() == Heap::raw_unchecked_byte_array_map()) {
1404 ASSERT(Size() >= kNextOffset + kPointerSize);
1405 Memory::Address_at(address() + kNextOffset) = next;
1406 } else {
1407 Memory::Address_at(address() + kPointerSize) = next;
1408 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409}
1410
1411
1412OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1413 Reset();
1414}
1415
1416
1417void OldSpaceFreeList::Reset() {
1418 available_ = 0;
1419 for (int i = 0; i < kFreeListsLength; i++) {
1420 free_[i].head_node_ = NULL;
1421 }
1422 needs_rebuild_ = false;
1423 finger_ = kHead;
1424 free_[kHead].next_size_ = kEnd;
1425}
1426
1427
1428void OldSpaceFreeList::RebuildSizeList() {
1429 ASSERT(needs_rebuild_);
1430 int cur = kHead;
1431 for (int i = cur + 1; i < kFreeListsLength; i++) {
1432 if (free_[i].head_node_ != NULL) {
1433 free_[cur].next_size_ = i;
1434 cur = i;
1435 }
1436 }
1437 free_[cur].next_size_ = kEnd;
1438 needs_rebuild_ = false;
1439}
1440
1441
1442int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1443#ifdef DEBUG
1444 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1445 Memory::Address_at(start + i) = kZapValue;
1446 }
1447#endif
1448 FreeListNode* node = FreeListNode::FromAddress(start);
1449 node->set_size(size_in_bytes);
1450
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001451 // We don't use the freelists in compacting mode. This makes it more like a
1452 // GC that only has mark-sweep-compact and doesn't have a mark-sweep
1453 // collector.
1454 if (FLAG_always_compact) {
1455 return size_in_bytes;
1456 }
1457
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001458 // Early return to drop too-small blocks on the floor (one or two word
1459 // blocks cannot hold a map pointer, a size field, and a pointer to the
1460 // next block in the free list).
1461 if (size_in_bytes < kMinBlockSize) {
1462 return size_in_bytes;
1463 }
1464
1465 // Insert other blocks at the head of an exact free list.
1466 int index = size_in_bytes >> kPointerSizeLog2;
1467 node->set_next(free_[index].head_node_);
1468 free_[index].head_node_ = node->address();
1469 available_ += size_in_bytes;
1470 needs_rebuild_ = true;
1471 return 0;
1472}
1473
1474
1475Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1476 ASSERT(0 < size_in_bytes);
1477 ASSERT(size_in_bytes <= kMaxBlockSize);
1478 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1479
1480 if (needs_rebuild_) RebuildSizeList();
1481 int index = size_in_bytes >> kPointerSizeLog2;
1482 // Check for a perfect fit.
1483 if (free_[index].head_node_ != NULL) {
1484 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1485 // If this was the last block of its size, remove the size.
1486 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1487 available_ -= size_in_bytes;
1488 *wasted_bytes = 0;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001489 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001490 return node;
1491 }
1492 // Search the size list for the best fit.
1493 int prev = finger_ < index ? finger_ : kHead;
1494 int cur = FindSize(index, &prev);
1495 ASSERT(index < cur);
1496 if (cur == kEnd) {
1497 // No large enough size in list.
1498 *wasted_bytes = 0;
1499 return Failure::RetryAfterGC(size_in_bytes, owner_);
1500 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001501 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001502 int rem = cur - index;
1503 int rem_bytes = rem << kPointerSizeLog2;
1504 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001505 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001506 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1507 size_in_bytes);
1508 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1509 // to avoid many redundant tests and calls to Insert/RemoveSize.
1510 if (prev < rem) {
1511 // Simple case: insert rem between prev and cur.
1512 finger_ = prev;
1513 free_[prev].next_size_ = rem;
1514 // If this was the last block of size cur, remove the size.
1515 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1516 free_[rem].next_size_ = free_[cur].next_size_;
1517 } else {
1518 free_[rem].next_size_ = cur;
1519 }
1520 // Add the remainder block.
1521 rem_node->set_size(rem_bytes);
1522 rem_node->set_next(free_[rem].head_node_);
1523 free_[rem].head_node_ = rem_node->address();
1524 } else {
1525 // If this was the last block of size cur, remove the size.
1526 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1527 finger_ = prev;
1528 free_[prev].next_size_ = free_[cur].next_size_;
1529 }
1530 if (rem_bytes < kMinBlockSize) {
1531 // Too-small remainder is wasted.
1532 rem_node->set_size(rem_bytes);
1533 available_ -= size_in_bytes + rem_bytes;
1534 *wasted_bytes = rem_bytes;
1535 return cur_node;
1536 }
1537 // Add the remainder block and, if needed, insert its size.
1538 rem_node->set_size(rem_bytes);
1539 rem_node->set_next(free_[rem].head_node_);
1540 free_[rem].head_node_ = rem_node->address();
1541 if (rem_node->next() == NULL) InsertSize(rem);
1542 }
1543 available_ -= size_in_bytes;
1544 *wasted_bytes = 0;
1545 return cur_node;
1546}
1547
1548
kasper.lund7276f142008-07-30 08:49:36 +00001549#ifdef DEBUG
1550bool OldSpaceFreeList::Contains(FreeListNode* node) {
1551 for (int i = 0; i < kFreeListsLength; i++) {
1552 Address cur_addr = free_[i].head_node_;
1553 while (cur_addr != NULL) {
1554 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1555 if (cur_node == node) return true;
1556 cur_addr = cur_node->next();
1557 }
1558 }
1559 return false;
1560}
1561#endif
1562
1563
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001564FixedSizeFreeList::FixedSizeFreeList(AllocationSpace owner, int object_size)
1565 : owner_(owner), object_size_(object_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566 Reset();
1567}
1568
1569
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001570void FixedSizeFreeList::Reset() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001571 available_ = 0;
1572 head_ = NULL;
1573}
1574
1575
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001576void FixedSizeFreeList::Free(Address start) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001577#ifdef DEBUG
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001578 for (int i = 0; i < object_size_; i += kPointerSize) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579 Memory::Address_at(start + i) = kZapValue;
1580 }
1581#endif
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001582 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583 FreeListNode* node = FreeListNode::FromAddress(start);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001584 node->set_size(object_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001585 node->set_next(head_);
1586 head_ = node->address();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001587 available_ += object_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001588}
1589
1590
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001591Object* FixedSizeFreeList::Allocate() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001592 if (head_ == NULL) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001593 return Failure::RetryAfterGC(object_size_, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001594 }
1595
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001596 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001597 FreeListNode* node = FreeListNode::FromAddress(head_);
1598 head_ = node->next();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001599 available_ -= object_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001600 return node;
1601}
1602
1603
1604// -----------------------------------------------------------------------------
1605// OldSpace implementation
1606
1607void OldSpace::PrepareForMarkCompact(bool will_compact) {
1608 if (will_compact) {
1609 // Reset relocation info. During a compacting collection, everything in
1610 // the space is considered 'available' and we will rediscover live data
1611 // and waste during the collection.
1612 MCResetRelocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001613 ASSERT(Available() == Capacity());
1614 } else {
1615 // During a non-compacting collection, everything below the linear
1616 // allocation pointer is considered allocated (everything above is
1617 // available) and we will rediscover available and wasted bytes during
1618 // the collection.
1619 accounting_stats_.AllocateBytes(free_list_.available());
1620 accounting_stats_.FillWastedBytes(Waste());
1621 }
1622
kasper.lund7276f142008-07-30 08:49:36 +00001623 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001624 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001625}
1626
1627
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628void OldSpace::MCCommitRelocationInfo() {
1629 // Update fast allocation info.
1630 allocation_info_.top = mc_forwarding_info_.top;
1631 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001632 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633
1634 // The space is compacted and we haven't yet built free lists or
1635 // wasted any space.
1636 ASSERT(Waste() == 0);
1637 ASSERT(AvailableFree() == 0);
1638
1639 // Build the free list for the space.
1640 int computed_size = 0;
1641 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1642 while (it.has_next()) {
1643 Page* p = it.next();
1644 // Space below the relocation pointer is allocated.
1645 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1646 if (it.has_next()) {
1647 // Free the space at the top of the page. We cannot use
1648 // p->mc_relocation_top after the call to Free (because Free will clear
1649 // remembered set bits).
1650 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1651 if (extra_size > 0) {
1652 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1653 // The bytes we have just "freed" to add to the free list were
1654 // already accounted as available.
1655 accounting_stats_.WasteBytes(wasted_bytes);
1656 }
1657 }
1658 }
1659
1660 // Make sure the computed size - based on the used portion of the pages in
1661 // use - matches the size obtained while computing forwarding addresses.
1662 ASSERT(computed_size == Size());
1663}
1664
1665
kasper.lund7276f142008-07-30 08:49:36 +00001666// Slow case for normal allocation. Try in order: (1) allocate in the next
1667// page in the space, (2) allocate off the space's free list, (3) expand the
1668// space, (4) fail.
1669HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1670 // Linear allocation in this space has failed. If there is another page
1671 // in the space, move to that page and allocate there. This allocation
1672 // should succeed (size_in_bytes should not be greater than a page's
1673 // object area size).
1674 Page* current_page = TopPageOf(allocation_info_);
1675 if (current_page->next_page()->is_valid()) {
1676 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001677 }
kasper.lund7276f142008-07-30 08:49:36 +00001678
1679 // There is no next page in this space. Try free list allocation.
1680 int wasted_bytes;
1681 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1682 accounting_stats_.WasteBytes(wasted_bytes);
1683 if (!result->IsFailure()) {
1684 accounting_stats_.AllocateBytes(size_in_bytes);
1685 return HeapObject::cast(result);
1686 }
1687
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001688 // Free list allocation failed and there is no next page. Fail if we have
1689 // hit the old generation size limit that should cause a garbage
1690 // collection.
1691 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
1692 return NULL;
1693 }
1694
1695 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00001696 ASSERT(!current_page->next_page()->is_valid());
1697 if (Expand(current_page)) {
1698 return AllocateInNextPage(current_page, size_in_bytes);
1699 }
1700
1701 // Finally, fail.
1702 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001703}
1704
1705
kasper.lund7276f142008-07-30 08:49:36 +00001706// Add the block at the top of the page to the space's free list, set the
1707// allocation info to the next page (assumed to be one), and allocate
1708// linearly there.
1709HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1710 int size_in_bytes) {
1711 ASSERT(current_page->next_page()->is_valid());
1712 // Add the block at the top of this page to the free list.
1713 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1714 if (free_size > 0) {
1715 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1716 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001717 }
kasper.lund7276f142008-07-30 08:49:36 +00001718 SetAllocationInfo(&allocation_info_, current_page->next_page());
1719 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720}
1721
1722
1723#ifdef DEBUG
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001724struct CommentStatistic {
1725 const char* comment;
1726 int size;
1727 int count;
1728 void Clear() {
1729 comment = NULL;
1730 size = 0;
1731 count = 0;
1732 }
1733};
1734
1735
1736// must be small, since an iteration is used for lookup
1737const int kMaxComments = 64;
1738static CommentStatistic comments_statistics[kMaxComments+1];
1739
1740
1741void PagedSpace::ReportCodeStatistics() {
1742 ReportCodeKindStatistics();
1743 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1744 "count (average)\"):\n");
1745 for (int i = 0; i <= kMaxComments; i++) {
1746 const CommentStatistic& cs = comments_statistics[i];
1747 if (cs.size > 0) {
1748 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1749 cs.size/cs.count);
1750 }
1751 }
1752 PrintF("\n");
1753}
1754
1755
1756void PagedSpace::ResetCodeStatistics() {
1757 ClearCodeKindStatistics();
1758 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1759 comments_statistics[kMaxComments].comment = "Unknown";
1760 comments_statistics[kMaxComments].size = 0;
1761 comments_statistics[kMaxComments].count = 0;
1762}
1763
1764
1765// Adds comment to 'comment_statistics' table. Performance OK sa long as
1766// 'kMaxComments' is small
1767static void EnterComment(const char* comment, int delta) {
1768 // Do not count empty comments
1769 if (delta <= 0) return;
1770 CommentStatistic* cs = &comments_statistics[kMaxComments];
1771 // Search for a free or matching entry in 'comments_statistics': 'cs'
1772 // points to result.
1773 for (int i = 0; i < kMaxComments; i++) {
1774 if (comments_statistics[i].comment == NULL) {
1775 cs = &comments_statistics[i];
1776 cs->comment = comment;
1777 break;
1778 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1779 cs = &comments_statistics[i];
1780 break;
1781 }
1782 }
1783 // Update entry for 'comment'
1784 cs->size += delta;
1785 cs->count += 1;
1786}
1787
1788
1789// Call for each nested comment start (start marked with '[ xxx', end marked
1790// with ']'. RelocIterator 'it' must point to a comment reloc info.
1791static void CollectCommentStatistics(RelocIterator* it) {
1792 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001793 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001794 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1795 if (tmp[0] != '[') {
1796 // Not a nested comment; skip
1797 return;
1798 }
1799
1800 // Search for end of nested comment or a new nested comment
1801 const char* const comment_txt =
1802 reinterpret_cast<const char*>(it->rinfo()->data());
1803 const byte* prev_pc = it->rinfo()->pc();
1804 int flat_delta = 0;
1805 it->next();
1806 while (true) {
1807 // All nested comments must be terminated properly, and therefore exit
1808 // from loop.
1809 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001810 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001811 const char* const txt =
1812 reinterpret_cast<const char*>(it->rinfo()->data());
1813 flat_delta += it->rinfo()->pc() - prev_pc;
1814 if (txt[0] == ']') break; // End of nested comment
1815 // A new comment
1816 CollectCommentStatistics(it);
1817 // Skip code that was covered with previous comment
1818 prev_pc = it->rinfo()->pc();
1819 }
1820 it->next();
1821 }
1822 EnterComment(comment_txt, flat_delta);
1823}
1824
1825
1826// Collects code size statistics:
1827// - by code kind
1828// - by code comment
1829void PagedSpace::CollectCodeStatistics() {
1830 HeapObjectIterator obj_it(this);
1831 while (obj_it.has_next()) {
1832 HeapObject* obj = obj_it.next();
1833 if (obj->IsCode()) {
1834 Code* code = Code::cast(obj);
1835 code_kind_statistics[code->kind()] += code->Size();
1836 RelocIterator it(code);
1837 int delta = 0;
1838 const byte* prev_pc = code->instruction_start();
1839 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001840 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001841 delta += it.rinfo()->pc() - prev_pc;
1842 CollectCommentStatistics(&it);
1843 prev_pc = it.rinfo()->pc();
1844 }
1845 it.next();
1846 }
1847
1848 ASSERT(code->instruction_start() <= prev_pc &&
1849 prev_pc <= code->relocation_start());
1850 delta += code->relocation_start() - prev_pc;
1851 EnterComment("NoComment", delta);
1852 }
1853 }
1854}
1855
1856
1857void OldSpace::ReportStatistics() {
1858 int pct = Available() * 100 / Capacity();
1859 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1860 Capacity(), Waste(), Available(), pct);
1861
1862 // Report remembered set statistics.
1863 int rset_marked_pointers = 0;
1864 int rset_marked_arrays = 0;
1865 int rset_marked_array_elements = 0;
1866 int cross_gen_pointers = 0;
1867 int cross_gen_array_elements = 0;
1868
1869 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1870 while (page_it.has_next()) {
1871 Page* p = page_it.next();
1872
1873 for (Address rset_addr = p->RSetStart();
1874 rset_addr < p->RSetEnd();
1875 rset_addr += kIntSize) {
1876 int rset = Memory::int_at(rset_addr);
1877 if (rset != 0) {
1878 // Bits were set
1879 int intoff = rset_addr - p->address();
1880 int bitoff = 0;
1881 for (; bitoff < kBitsPerInt; ++bitoff) {
1882 if ((rset & (1 << bitoff)) != 0) {
1883 int bitpos = intoff*kBitsPerByte + bitoff;
1884 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1885 Object** obj = reinterpret_cast<Object**>(slot);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001886 if (*obj == Heap::raw_unchecked_fixed_array_map()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001887 rset_marked_arrays++;
1888 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1889
1890 rset_marked_array_elements += fa->length();
1891 // Manually inline FixedArray::IterateBody
1892 Address elm_start = slot + FixedArray::kHeaderSize;
1893 Address elm_stop = elm_start + fa->length() * kPointerSize;
1894 for (Address elm_addr = elm_start;
1895 elm_addr < elm_stop; elm_addr += kPointerSize) {
1896 // Filter non-heap-object pointers
1897 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1898 if (Heap::InNewSpace(*elm_p))
1899 cross_gen_array_elements++;
1900 }
1901 } else {
1902 rset_marked_pointers++;
1903 if (Heap::InNewSpace(*obj))
1904 cross_gen_pointers++;
1905 }
1906 }
1907 }
1908 }
1909 }
1910 }
1911
1912 pct = rset_marked_pointers == 0 ?
1913 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1914 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1915 rset_marked_pointers, cross_gen_pointers, pct);
1916 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1917 PrintF(" elements %d, ", rset_marked_array_elements);
1918 pct = rset_marked_array_elements == 0 ? 0
1919 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1920 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1921 PrintF(" total rset-marked bits %d\n",
1922 (rset_marked_pointers + rset_marked_arrays));
1923 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1924 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1925 (rset_marked_pointers + rset_marked_array_elements);
1926 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1927 (rset_marked_pointers + rset_marked_array_elements),
1928 (cross_gen_pointers + cross_gen_array_elements),
1929 pct);
1930
1931 ClearHistograms();
1932 HeapObjectIterator obj_it(this);
1933 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1934 ReportHistogram(true);
1935}
1936
1937
1938// Dump the range of remembered set words between [start, end) corresponding
1939// to the pointers starting at object_p. The allocation_top is an object
1940// pointer which should not be read past. This is important for large object
1941// pages, where some bits in the remembered set range do not correspond to
1942// allocated addresses.
1943static void PrintRSetRange(Address start, Address end, Object** object_p,
1944 Address allocation_top) {
1945 Address rset_address = start;
1946
1947 // If the range starts on on odd numbered word (eg, for large object extra
1948 // remembered set ranges), print some spaces.
ager@chromium.org9085a012009-05-11 19:22:57 +00001949 if ((reinterpret_cast<uintptr_t>(start) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001950 PrintF(" ");
1951 }
1952
1953 // Loop over all the words in the range.
1954 while (rset_address < end) {
1955 uint32_t rset_word = Memory::uint32_at(rset_address);
1956 int bit_position = 0;
1957
1958 // Loop over all the bits in the word.
1959 while (bit_position < kBitsPerInt) {
1960 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1961 // Print a bar at the allocation pointer.
1962 PrintF("|");
1963 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1964 // Do not dereference object_p past the allocation pointer.
1965 PrintF("#");
1966 } else if ((rset_word & (1 << bit_position)) == 0) {
1967 // Print a dot for zero bits.
1968 PrintF(".");
1969 } else if (Heap::InNewSpace(*object_p)) {
1970 // Print an X for one bits for pointers to new space.
1971 PrintF("X");
1972 } else {
1973 // Print a circle for one bits for pointers to old space.
1974 PrintF("o");
1975 }
1976
1977 // Print a space after every 8th bit except the last.
1978 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1979 PrintF(" ");
1980 }
1981
1982 // Advance to next bit.
1983 bit_position++;
1984 object_p++;
1985 }
1986
1987 // Print a newline after every odd numbered word, otherwise a space.
ager@chromium.org9085a012009-05-11 19:22:57 +00001988 if ((reinterpret_cast<uintptr_t>(rset_address) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001989 PrintF("\n");
1990 } else {
1991 PrintF(" ");
1992 }
1993
1994 // Advance to next remembered set word.
1995 rset_address += kIntSize;
1996 }
1997}
1998
1999
2000void PagedSpace::DoPrintRSet(const char* space_name) {
2001 PageIterator it(this, PageIterator::PAGES_IN_USE);
2002 while (it.has_next()) {
2003 Page* p = it.next();
2004 PrintF("%s page 0x%x:\n", space_name, p);
2005 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
2006 reinterpret_cast<Object**>(p->ObjectAreaStart()),
2007 p->AllocationTop());
2008 PrintF("\n");
2009 }
2010}
2011
2012
2013void OldSpace::PrintRSet() { DoPrintRSet("old"); }
2014#endif
2015
2016// -----------------------------------------------------------------------------
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002017// FixedSpace implementation
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002018
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002019void FixedSpace::PrepareForMarkCompact(bool will_compact) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002020 if (will_compact) {
2021 // Reset relocation info.
2022 MCResetRelocationInfo();
2023
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002024 // During a compacting collection, everything in the space is considered
2025 // 'available' (set by the call to MCResetRelocationInfo) and we will
2026 // rediscover live and wasted bytes during the collection.
2027 ASSERT(Available() == Capacity());
2028 } else {
2029 // During a non-compacting collection, everything below the linear
2030 // allocation pointer except wasted top-of-page blocks is considered
2031 // allocated and we will rediscover available bytes during the
2032 // collection.
2033 accounting_stats_.AllocateBytes(free_list_.available());
2034 }
2035
kasper.lund7276f142008-07-30 08:49:36 +00002036 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002037 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002038}
2039
2040
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002041void FixedSpace::MCCommitRelocationInfo() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002042 // Update fast allocation info.
2043 allocation_info_.top = mc_forwarding_info_.top;
2044 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00002045 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002046
2047 // The space is compacted and we haven't yet wasted any space.
2048 ASSERT(Waste() == 0);
2049
2050 // Update allocation_top of each page in use and compute waste.
2051 int computed_size = 0;
2052 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
2053 while (it.has_next()) {
2054 Page* page = it.next();
2055 Address page_top = page->AllocationTop();
2056 computed_size += page_top - page->ObjectAreaStart();
2057 if (it.has_next()) {
2058 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
2059 }
2060 }
2061
2062 // Make sure the computed size - based on the used portion of the
2063 // pages in use - matches the size we adjust during allocation.
2064 ASSERT(computed_size == Size());
2065}
2066
2067
kasper.lund7276f142008-07-30 08:49:36 +00002068// Slow case for normal allocation. Try in order: (1) allocate in the next
2069// page in the space, (2) allocate off the space's free list, (3) expand the
2070// space, (4) fail.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002071HeapObject* FixedSpace::SlowAllocateRaw(int size_in_bytes) {
2072 ASSERT_EQ(object_size_in_bytes_, size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002073 // Linear allocation in this space has failed. If there is another page
2074 // in the space, move to that page and allocate there. This allocation
2075 // should succeed.
2076 Page* current_page = TopPageOf(allocation_info_);
2077 if (current_page->next_page()->is_valid()) {
2078 return AllocateInNextPage(current_page, size_in_bytes);
2079 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002081 // There is no next page in this space. Try free list allocation.
2082 // The fixed space free list implicitly assumes that all free blocks
2083 // are of the fixed size.
2084 if (size_in_bytes == object_size_in_bytes_) {
kasper.lund7276f142008-07-30 08:49:36 +00002085 Object* result = free_list_.Allocate();
2086 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002087 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002088 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002089 }
2090 }
kasper.lund7276f142008-07-30 08:49:36 +00002091
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002092 // Free list allocation failed and there is no next page. Fail if we have
2093 // hit the old generation size limit that should cause a garbage
2094 // collection.
2095 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2096 return NULL;
2097 }
2098
2099 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00002100 ASSERT(!current_page->next_page()->is_valid());
2101 if (Expand(current_page)) {
2102 return AllocateInNextPage(current_page, size_in_bytes);
2103 }
2104
2105 // Finally, fail.
2106 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002107}
2108
2109
kasper.lund7276f142008-07-30 08:49:36 +00002110// Move to the next page (there is assumed to be one) and allocate there.
2111// The top of page block is always wasted, because it is too small to hold a
2112// map.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002113HeapObject* FixedSpace::AllocateInNextPage(Page* current_page,
2114 int size_in_bytes) {
kasper.lund7276f142008-07-30 08:49:36 +00002115 ASSERT(current_page->next_page()->is_valid());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002116 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == page_extra_);
2117 ASSERT_EQ(object_size_in_bytes_, size_in_bytes);
2118 accounting_stats_.WasteBytes(page_extra_);
kasper.lund7276f142008-07-30 08:49:36 +00002119 SetAllocationInfo(&allocation_info_, current_page->next_page());
2120 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002121}
2122
2123
2124#ifdef DEBUG
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002125void FixedSpace::ReportStatistics() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002126 int pct = Available() * 100 / Capacity();
2127 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2128 Capacity(), Waste(), Available(), pct);
2129
2130 // Report remembered set statistics.
2131 int rset_marked_pointers = 0;
2132 int cross_gen_pointers = 0;
2133
2134 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2135 while (page_it.has_next()) {
2136 Page* p = page_it.next();
2137
2138 for (Address rset_addr = p->RSetStart();
2139 rset_addr < p->RSetEnd();
2140 rset_addr += kIntSize) {
2141 int rset = Memory::int_at(rset_addr);
2142 if (rset != 0) {
2143 // Bits were set
2144 int intoff = rset_addr - p->address();
2145 int bitoff = 0;
2146 for (; bitoff < kBitsPerInt; ++bitoff) {
2147 if ((rset & (1 << bitoff)) != 0) {
2148 int bitpos = intoff*kBitsPerByte + bitoff;
2149 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2150 Object** obj = reinterpret_cast<Object**>(slot);
2151 rset_marked_pointers++;
2152 if (Heap::InNewSpace(*obj))
2153 cross_gen_pointers++;
2154 }
2155 }
2156 }
2157 }
2158 }
2159
2160 pct = rset_marked_pointers == 0 ?
2161 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2162 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2163 rset_marked_pointers, cross_gen_pointers, pct);
2164
2165 ClearHistograms();
2166 HeapObjectIterator obj_it(this);
2167 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2168 ReportHistogram(false);
2169}
2170
2171
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002172void FixedSpace::PrintRSet() { DoPrintRSet(name_); }
2173#endif
2174
2175
2176// -----------------------------------------------------------------------------
2177// MapSpace implementation
2178
2179void MapSpace::PrepareForMarkCompact(bool will_compact) {
2180 // Call prepare of the super class.
2181 FixedSpace::PrepareForMarkCompact(will_compact);
2182
2183 if (will_compact) {
2184 // Initialize map index entry.
2185 int page_count = 0;
2186 PageIterator it(this, PageIterator::ALL_PAGES);
2187 while (it.has_next()) {
2188 ASSERT_MAP_PAGE_INDEX(page_count);
2189
2190 Page* p = it.next();
2191 ASSERT(p->mc_page_index == page_count);
2192
2193 page_addresses_[page_count++] = p->address();
2194 }
2195 }
2196}
2197
2198
2199#ifdef DEBUG
2200void MapSpace::VerifyObject(HeapObject* object) {
2201 // The object should be a map or a free-list node.
2202 ASSERT(object->IsMap() || object->IsByteArray());
2203}
2204#endif
2205
2206
2207// -----------------------------------------------------------------------------
2208// GlobalPropertyCellSpace implementation
2209
2210#ifdef DEBUG
2211void CellSpace::VerifyObject(HeapObject* object) {
2212 // The object should be a global object property cell or a free-list node.
2213 ASSERT(object->IsJSGlobalPropertyCell() ||
2214 object->map() == Heap::two_pointer_filler_map());
2215}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002216#endif
2217
2218
2219// -----------------------------------------------------------------------------
2220// LargeObjectIterator
2221
2222LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2223 current_ = space->first_chunk_;
2224 size_func_ = NULL;
2225}
2226
2227
2228LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2229 HeapObjectCallback size_func) {
2230 current_ = space->first_chunk_;
2231 size_func_ = size_func;
2232}
2233
2234
2235HeapObject* LargeObjectIterator::next() {
2236 ASSERT(has_next());
2237 HeapObject* object = current_->GetObject();
2238 current_ = current_->next();
2239 return object;
2240}
2241
2242
2243// -----------------------------------------------------------------------------
2244// LargeObjectChunk
2245
2246LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002247 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002248 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002249 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002250 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2251 chunk_size,
2252 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002253 if (mem == NULL) return NULL;
2254 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2255 if (*chunk_size < requested) {
2256 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2257 LOG(DeleteEvent("LargeObjectChunk", mem));
2258 return NULL;
2259 }
2260 return reinterpret_cast<LargeObjectChunk*>(mem);
2261}
2262
2263
2264int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2265 int os_alignment = OS::AllocateAlignment();
2266 if (os_alignment < Page::kPageSize)
2267 size_in_bytes += (Page::kPageSize - os_alignment);
2268 return size_in_bytes + Page::kObjectStartOffset;
2269}
2270
2271// -----------------------------------------------------------------------------
2272// LargeObjectSpace
2273
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002274LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2275 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002276 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002277 size_(0),
2278 page_count_(0) {}
2279
2280
2281bool LargeObjectSpace::Setup() {
2282 first_chunk_ = NULL;
2283 size_ = 0;
2284 page_count_ = 0;
2285 return true;
2286}
2287
2288
2289void LargeObjectSpace::TearDown() {
2290 while (first_chunk_ != NULL) {
2291 LargeObjectChunk* chunk = first_chunk_;
2292 first_chunk_ = first_chunk_->next();
2293 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2294 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2295 }
2296
2297 size_ = 0;
2298 page_count_ = 0;
2299}
2300
2301
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002302#ifdef ENABLE_HEAP_PROTECTION
2303
2304void LargeObjectSpace::Protect() {
2305 LargeObjectChunk* chunk = first_chunk_;
2306 while (chunk != NULL) {
2307 MemoryAllocator::Protect(chunk->address(), chunk->size());
2308 chunk = chunk->next();
2309 }
2310}
2311
2312
2313void LargeObjectSpace::Unprotect() {
2314 LargeObjectChunk* chunk = first_chunk_;
2315 while (chunk != NULL) {
2316 bool is_code = chunk->GetObject()->IsCode();
2317 MemoryAllocator::Unprotect(chunk->address(), chunk->size(),
2318 is_code ? EXECUTABLE : NOT_EXECUTABLE);
2319 chunk = chunk->next();
2320 }
2321}
2322
2323#endif
2324
2325
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002326Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002327 int object_size,
2328 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002329 ASSERT(0 < object_size && object_size <= requested_size);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002330
2331 // Check if we want to force a GC before growing the old space further.
2332 // If so, fail the allocation.
2333 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2334 return Failure::RetryAfterGC(requested_size, identity());
2335 }
2336
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002337 size_t chunk_size;
2338 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002339 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002340 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002341 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002342 }
2343
2344 size_ += chunk_size;
2345 page_count_++;
2346 chunk->set_next(first_chunk_);
2347 chunk->set_size(chunk_size);
2348 first_chunk_ = chunk;
2349
2350 // Set the object address and size in the page header and clear its
2351 // remembered set.
2352 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2353 Address object_address = page->ObjectAreaStart();
2354 // Clear the low order bit of the second word in the page to flag it as a
2355 // large object page. If the chunk_size happened to be written there, its
2356 // low order bit should already be clear.
2357 ASSERT((chunk_size & 0x1) == 0);
2358 page->is_normal_page &= ~0x1;
2359 page->ClearRSet();
2360 int extra_bytes = requested_size - object_size;
2361 if (extra_bytes > 0) {
2362 // The extra memory for the remembered set should be cleared.
2363 memset(object_address + object_size, 0, extra_bytes);
2364 }
2365
2366 return HeapObject::FromAddress(object_address);
2367}
2368
2369
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002370Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002371 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002372 return AllocateRawInternal(size_in_bytes,
2373 size_in_bytes,
2374 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002375}
2376
2377
2378Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002379 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002380 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002381 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2382 size_in_bytes,
2383 NOT_EXECUTABLE);
2384}
2385
2386
2387Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2388 ASSERT(0 < size_in_bytes);
2389 return AllocateRawInternal(size_in_bytes,
2390 size_in_bytes,
2391 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002392}
2393
2394
2395// GC support
2396Object* LargeObjectSpace::FindObject(Address a) {
2397 for (LargeObjectChunk* chunk = first_chunk_;
2398 chunk != NULL;
2399 chunk = chunk->next()) {
2400 Address chunk_address = chunk->address();
2401 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2402 return chunk->GetObject();
2403 }
2404 }
2405 return Failure::Exception();
2406}
2407
2408
2409void LargeObjectSpace::ClearRSet() {
2410 ASSERT(Page::is_rset_in_use());
2411
2412 LargeObjectIterator it(this);
2413 while (it.has_next()) {
2414 HeapObject* object = it.next();
2415 // We only have code, sequential strings, or fixed arrays in large
2416 // object space, and only fixed arrays need remembered set support.
2417 if (object->IsFixedArray()) {
2418 // Clear the normal remembered set region of the page;
2419 Page* page = Page::FromAddress(object->address());
2420 page->ClearRSet();
2421
2422 // Clear the extra remembered set.
2423 int size = object->Size();
2424 int extra_rset_bytes = ExtraRSetBytesFor(size);
2425 memset(object->address() + size, 0, extra_rset_bytes);
2426 }
2427 }
2428}
2429
2430
2431void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2432 ASSERT(Page::is_rset_in_use());
2433
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002434 static void* lo_rset_histogram = StatsTable::CreateHistogram(
2435 "V8.RSetLO",
2436 0,
2437 // Keeping this histogram's buckets the same as the paged space histogram.
2438 Page::kObjectAreaSize / kPointerSize,
2439 30);
2440
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002441 LargeObjectIterator it(this);
2442 while (it.has_next()) {
2443 // We only have code, sequential strings, or fixed arrays in large
2444 // object space, and only fixed arrays can possibly contain pointers to
2445 // the young generation.
2446 HeapObject* object = it.next();
2447 if (object->IsFixedArray()) {
2448 // Iterate the normal page remembered set range.
2449 Page* page = Page::FromAddress(object->address());
2450 Address object_end = object->address() + object->Size();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002451 int count = Heap::IterateRSetRange(page->ObjectAreaStart(),
2452 Min(page->ObjectAreaEnd(), object_end),
2453 page->RSetStart(),
2454 copy_object_func);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002455
2456 // Iterate the extra array elements.
2457 if (object_end > page->ObjectAreaEnd()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002458 count += Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2459 object_end, copy_object_func);
2460 }
2461 if (lo_rset_histogram != NULL) {
2462 StatsTable::AddHistogramSample(lo_rset_histogram, count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002463 }
2464 }
2465 }
2466}
2467
2468
2469void LargeObjectSpace::FreeUnmarkedObjects() {
2470 LargeObjectChunk* previous = NULL;
2471 LargeObjectChunk* current = first_chunk_;
2472 while (current != NULL) {
2473 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002474 if (object->IsMarked()) {
2475 object->ClearMark();
2476 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002477 previous = current;
2478 current = current->next();
2479 } else {
2480 Address chunk_address = current->address();
2481 size_t chunk_size = current->size();
2482
2483 // Cut the chunk out from the chunk list.
2484 current = current->next();
2485 if (previous == NULL) {
2486 first_chunk_ = current;
2487 } else {
2488 previous->set_next(current);
2489 }
2490
2491 // Free the chunk.
2492 if (object->IsCode()) {
2493 LOG(CodeDeleteEvent(object->address()));
2494 }
2495 size_ -= chunk_size;
2496 page_count_--;
2497 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2498 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2499 }
2500 }
2501}
2502
2503
2504bool LargeObjectSpace::Contains(HeapObject* object) {
2505 Address address = object->address();
2506 Page* page = Page::FromAddress(address);
2507
2508 SLOW_ASSERT(!page->IsLargeObjectPage()
2509 || !FindObject(address)->IsFailure());
2510
2511 return page->IsLargeObjectPage();
2512}
2513
2514
2515#ifdef DEBUG
2516// We do not assume that the large object iterator works, because it depends
2517// on the invariants we are checking during verification.
2518void LargeObjectSpace::Verify() {
2519 for (LargeObjectChunk* chunk = first_chunk_;
2520 chunk != NULL;
2521 chunk = chunk->next()) {
2522 // Each chunk contains an object that starts at the large object page's
2523 // object area start.
2524 HeapObject* object = chunk->GetObject();
2525 Page* page = Page::FromAddress(object->address());
2526 ASSERT(object->address() == page->ObjectAreaStart());
2527
2528 // The first word should be a map, and we expect all map pointers to be
2529 // in map space.
2530 Map* map = object->map();
2531 ASSERT(map->IsMap());
2532 ASSERT(Heap::map_space()->Contains(map));
2533
2534 // We have only code, sequential strings, fixed arrays, and byte arrays
2535 // in large object space.
2536 ASSERT(object->IsCode() || object->IsSeqString()
2537 || object->IsFixedArray() || object->IsByteArray());
2538
2539 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002540 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002541
2542 // Byte arrays and strings don't have interior pointers.
2543 if (object->IsCode()) {
2544 VerifyPointersVisitor code_visitor;
2545 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2546 object->IterateBody(map->instance_type(),
2547 object->Size(),
2548 &code_visitor);
2549 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2550 } else if (object->IsFixedArray()) {
2551 // We loop over fixed arrays ourselves, rather then using the visitor,
2552 // because the visitor doesn't support the start/offset iteration
2553 // needed for IsRSetSet.
2554 FixedArray* array = FixedArray::cast(object);
2555 for (int j = 0; j < array->length(); j++) {
2556 Object* element = array->get(j);
2557 if (element->IsHeapObject()) {
2558 HeapObject* element_object = HeapObject::cast(element);
2559 ASSERT(Heap::Contains(element_object));
2560 ASSERT(element_object->map()->IsMap());
2561 if (Heap::InNewSpace(element_object)) {
2562 ASSERT(Page::IsRSetSet(object->address(),
2563 FixedArray::kHeaderSize + j * kPointerSize));
2564 }
2565 }
2566 }
2567 }
2568 }
2569}
2570
2571
2572void LargeObjectSpace::Print() {
2573 LargeObjectIterator it(this);
2574 while (it.has_next()) {
2575 it.next()->Print();
2576 }
2577}
2578
2579
2580void LargeObjectSpace::ReportStatistics() {
2581 PrintF(" size: %d\n", size_);
2582 int num_objects = 0;
2583 ClearHistograms();
2584 LargeObjectIterator it(this);
2585 while (it.has_next()) {
2586 num_objects++;
2587 CollectHistogramInfo(it.next());
2588 }
2589
2590 PrintF(" number of objects %d\n", num_objects);
2591 if (num_objects > 0) ReportHistogram(false);
2592}
2593
2594
2595void LargeObjectSpace::CollectCodeStatistics() {
2596 LargeObjectIterator obj_it(this);
2597 while (obj_it.has_next()) {
2598 HeapObject* obj = obj_it.next();
2599 if (obj->IsCode()) {
2600 Code* code = Code::cast(obj);
2601 code_kind_statistics[code->kind()] += code->Size();
2602 }
2603 }
2604}
2605
2606
2607void LargeObjectSpace::PrintRSet() {
2608 LargeObjectIterator it(this);
2609 while (it.has_next()) {
2610 HeapObject* object = it.next();
2611 if (object->IsFixedArray()) {
2612 Page* page = Page::FromAddress(object->address());
2613
2614 Address allocation_top = object->address() + object->Size();
2615 PrintF("large page 0x%x:\n", page);
2616 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2617 reinterpret_cast<Object**>(object->address()),
2618 allocation_top);
2619 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2620 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2621 kBitsPerInt);
2622 PrintF("------------------------------------------------------------"
2623 "-----------\n");
2624 PrintRSetRange(allocation_top,
2625 allocation_top + extra_rset_bits / kBitsPerByte,
2626 reinterpret_cast<Object**>(object->address()
2627 + Page::kObjectAreaSize),
2628 allocation_top);
2629 PrintF("\n");
2630 }
2631 }
2632}
2633#endif // DEBUG
2634
2635} } // namespace v8::internal