blob: 0e6a91e2ae7ee795c97ed74de8b39199c76a9899 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_SPACES_H_
29#define V8_SPACES_H_
30
31#include "list-inl.h"
32#include "log.h"
33
34namespace v8 {
35namespace internal {
36
37// -----------------------------------------------------------------------------
38// Heap structures:
39//
40// A JS heap consists of a young generation, an old generation, and a large
41// object space. The young generation is divided into two semispaces. A
42// scavenger implements Cheney's copying algorithm. The old generation is
43// separated into a map space and an old object space. The map space contains
44// all (and only) map objects, the rest of old objects go into the old space.
45// The old generation is collected by a mark-sweep-compact collector.
46//
47// The semispaces of the young generation are contiguous. The old and map
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010048// spaces consists of a list of pages. A page has a page header and an object
49// area. A page size is deliberately chosen as 8K bytes.
50// The first word of a page is an opaque page header that has the
Steve Blocka7e24c12009-10-30 11:49:00 +000051// address of the next page and its ownership information. The second word may
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010052// have the allocation top address of this page. Heap objects are aligned to the
53// pointer size.
Steve Blocka7e24c12009-10-30 11:49:00 +000054//
55// There is a separate large object space for objects larger than
56// Page::kMaxHeapObjectSize, so that they do not have to move during
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010057// collection. The large object space is paged. Pages in large object space
58// may be larger than 8K.
Steve Blocka7e24c12009-10-30 11:49:00 +000059//
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010060// A card marking write barrier is used to keep track of intergenerational
61// references. Old space pages are divided into regions of Page::kRegionSize
62// size. Each region has a corresponding dirty bit in the page header which is
63// set if the region might contain pointers to new space. For details about
64// dirty bits encoding see comments in the Page::GetRegionNumberForAddress()
65// method body.
66//
67// During scavenges and mark-sweep collections we iterate intergenerational
68// pointers without decoding heap object maps so if the page belongs to old
69// pointer space or large object space it is essential to guarantee that
70// the page does not contain any garbage pointers to new space: every pointer
71// aligned word which satisfies the Heap::InNewSpace() predicate must be a
72// pointer to a live heap object in new space. Thus objects in old pointer
73// and large object spaces should have a special layout (e.g. no bare integer
74// fields). This requirement does not apply to map space which is iterated in
75// a special fashion. However we still require pointer fields of dead maps to
76// be cleaned.
77//
78// To enable lazy cleaning of old space pages we use a notion of allocation
79// watermark. Every pointer under watermark is considered to be well formed.
80// Page allocation watermark is not necessarily equal to page allocation top but
81// all alive objects on page should reside under allocation watermark.
82// During scavenge allocation watermark might be bumped and invalid pointers
83// might appear below it. To avoid following them we store a valid watermark
84// into special field in the page header and set a page WATERMARK_INVALIDATED
85// flag. For details see comments in the Page::SetAllocationWatermark() method
86// body.
87//
Steve Blocka7e24c12009-10-30 11:49:00 +000088
89// Some assertion macros used in the debugging mode.
90
Leon Clarkee46be812010-01-19 14:06:41 +000091#define ASSERT_PAGE_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000092 ASSERT((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
93
Leon Clarkee46be812010-01-19 14:06:41 +000094#define ASSERT_OBJECT_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000095 ASSERT((OffsetFrom(address) & kObjectAlignmentMask) == 0)
96
Leon Clarkee46be812010-01-19 14:06:41 +000097#define ASSERT_MAP_ALIGNED(address) \
98 ASSERT((OffsetFrom(address) & kMapAlignmentMask) == 0)
99
100#define ASSERT_OBJECT_SIZE(size) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000101 ASSERT((0 < size) && (size <= Page::kMaxHeapObjectSize))
102
Leon Clarkee46be812010-01-19 14:06:41 +0000103#define ASSERT_PAGE_OFFSET(offset) \
104 ASSERT((Page::kObjectStartOffset <= offset) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000105 && (offset <= Page::kPageSize))
106
Leon Clarkee46be812010-01-19 14:06:41 +0000107#define ASSERT_MAP_PAGE_INDEX(index) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000108 ASSERT((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
109
110
111class PagedSpace;
112class MemoryAllocator;
113class AllocationInfo;
114
115// -----------------------------------------------------------------------------
116// A page normally has 8K bytes. Large object pages may be larger. A page
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100117// address is always aligned to the 8K page size.
Steve Blocka7e24c12009-10-30 11:49:00 +0000118//
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100119// Each page starts with a header of Page::kPageHeaderSize size which contains
120// bookkeeping data.
Steve Blocka7e24c12009-10-30 11:49:00 +0000121//
122// The mark-compact collector transforms a map pointer into a page index and a
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100123// page offset. The exact encoding is described in the comments for
Leon Clarkee46be812010-01-19 14:06:41 +0000124// class MapWord in objects.h.
Steve Blocka7e24c12009-10-30 11:49:00 +0000125//
126// The only way to get a page pointer is by calling factory methods:
127// Page* p = Page::FromAddress(addr); or
128// Page* p = Page::FromAllocationTop(top);
129class Page {
130 public:
131 // Returns the page containing a given address. The address ranges
132 // from [page_addr .. page_addr + kPageSize[
133 //
134 // Note that this function only works for addresses in normal paged
135 // spaces and addresses in the first 8K of large object pages (i.e.,
136 // the start of large objects but not necessarily derived pointers
137 // within them).
138 INLINE(static Page* FromAddress(Address a)) {
139 return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
140 }
141
142 // Returns the page containing an allocation top. Because an allocation
143 // top address can be the upper bound of the page, we need to subtract
144 // it with kPointerSize first. The address ranges from
145 // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
146 INLINE(static Page* FromAllocationTop(Address top)) {
147 Page* p = FromAddress(top - kPointerSize);
148 ASSERT_PAGE_OFFSET(p->Offset(top));
149 return p;
150 }
151
152 // Returns the start address of this page.
153 Address address() { return reinterpret_cast<Address>(this); }
154
155 // Checks whether this is a valid page address.
156 bool is_valid() { return address() != NULL; }
157
158 // Returns the next page of this page.
159 inline Page* next_page();
160
161 // Return the end of allocation in this page. Undefined for unused pages.
162 inline Address AllocationTop();
163
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100164 // Return the allocation watermark for the page.
165 // For old space pages it is guaranteed that the area under the watermark
166 // does not contain any garbage pointers to new space.
167 inline Address AllocationWatermark();
168
169 // Return the allocation watermark offset from the beginning of the page.
170 inline uint32_t AllocationWatermarkOffset();
171
172 inline void SetAllocationWatermark(Address allocation_watermark);
173
174 inline void SetCachedAllocationWatermark(Address allocation_watermark);
175 inline Address CachedAllocationWatermark();
176
Steve Blocka7e24c12009-10-30 11:49:00 +0000177 // Returns the start address of the object area in this page.
178 Address ObjectAreaStart() { return address() + kObjectStartOffset; }
179
180 // Returns the end address (exclusive) of the object area in this page.
181 Address ObjectAreaEnd() { return address() + Page::kPageSize; }
182
Steve Blocka7e24c12009-10-30 11:49:00 +0000183 // Checks whether an address is page aligned.
184 static bool IsAlignedToPageSize(Address a) {
185 return 0 == (OffsetFrom(a) & kPageAlignmentMask);
186 }
187
Steve Block6ded16b2010-05-10 14:33:55 +0100188 // True if this page was in use before current compaction started.
189 // Result is valid only for pages owned by paged spaces and
190 // only after PagedSpace::PrepareForMarkCompact was called.
191 inline bool WasInUseBeforeMC();
192
193 inline void SetWasInUseBeforeMC(bool was_in_use);
194
Steve Blocka7e24c12009-10-30 11:49:00 +0000195 // True if this page is a large object page.
Steve Block6ded16b2010-05-10 14:33:55 +0100196 inline bool IsLargeObjectPage();
197
198 inline void SetIsLargeObjectPage(bool is_large_object_page);
Steve Blocka7e24c12009-10-30 11:49:00 +0000199
Steve Block791712a2010-08-27 10:21:07 +0100200 inline bool IsPageExecutable();
201
202 inline void SetIsPageExecutable(bool is_page_executable);
203
Steve Blocka7e24c12009-10-30 11:49:00 +0000204 // Returns the offset of a given address to this page.
205 INLINE(int Offset(Address a)) {
Steve Blockd0582a62009-12-15 09:54:21 +0000206 int offset = static_cast<int>(a - address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000207 ASSERT_PAGE_OFFSET(offset);
208 return offset;
209 }
210
211 // Returns the address for a given offset to the this page.
212 Address OffsetToAddress(int offset) {
213 ASSERT_PAGE_OFFSET(offset);
214 return address() + offset;
215 }
216
217 // ---------------------------------------------------------------------
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100218 // Card marking support
Steve Blocka7e24c12009-10-30 11:49:00 +0000219
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100220 static const uint32_t kAllRegionsCleanMarks = 0x0;
221 static const uint32_t kAllRegionsDirtyMarks = 0xFFFFFFFF;
Steve Blocka7e24c12009-10-30 11:49:00 +0000222
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100223 inline uint32_t GetRegionMarks();
224 inline void SetRegionMarks(uint32_t dirty);
Steve Blocka7e24c12009-10-30 11:49:00 +0000225
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100226 inline uint32_t GetRegionMaskForAddress(Address addr);
227 inline uint32_t GetRegionMaskForSpan(Address start, int length_in_bytes);
228 inline int GetRegionNumberForAddress(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000229
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100230 inline void MarkRegionDirty(Address addr);
231 inline bool IsRegionDirty(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000232
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100233 inline void ClearRegionMarks(Address start,
234 Address end,
235 bool reaches_limit);
Steve Blocka7e24c12009-10-30 11:49:00 +0000236
Steve Blocka7e24c12009-10-30 11:49:00 +0000237 // Page size in bytes. This must be a multiple of the OS page size.
238 static const int kPageSize = 1 << kPageSizeBits;
239
240 // Page size mask.
241 static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
242
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100243 static const int kPageHeaderSize = kPointerSize + kPointerSize + kIntSize +
244 kIntSize + kPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000245
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100246 // The start offset of the object area in a page. Aligned to both maps and
247 // code alignment to be suitable for both.
248 static const int kObjectStartOffset =
249 CODE_POINTER_ALIGN(MAP_POINTER_ALIGN(kPageHeaderSize));
Steve Blocka7e24c12009-10-30 11:49:00 +0000250
251 // Object area size in bytes.
252 static const int kObjectAreaSize = kPageSize - kObjectStartOffset;
253
254 // Maximum object size that fits in a page.
255 static const int kMaxHeapObjectSize = kObjectAreaSize;
256
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100257 static const int kDirtyFlagOffset = 2 * kPointerSize;
258 static const int kRegionSizeLog2 = 8;
259 static const int kRegionSize = 1 << kRegionSizeLog2;
260 static const intptr_t kRegionAlignmentMask = (kRegionSize - 1);
261
262 STATIC_CHECK(kRegionSize == kPageSize / kBitsPerInt);
263
Steve Block6ded16b2010-05-10 14:33:55 +0100264 enum PageFlag {
Steve Block791712a2010-08-27 10:21:07 +0100265 IS_NORMAL_PAGE = 0,
266 WAS_IN_USE_BEFORE_MC,
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100267
268 // Page allocation watermark was bumped by preallocation during scavenge.
269 // Correct watermark can be retrieved by CachedAllocationWatermark() method
Steve Block791712a2010-08-27 10:21:07 +0100270 WATERMARK_INVALIDATED,
271 IS_EXECUTABLE,
272 NUM_PAGE_FLAGS // Must be last
Steve Block6ded16b2010-05-10 14:33:55 +0100273 };
Steve Block791712a2010-08-27 10:21:07 +0100274 static const int kPageFlagMask = (1 << NUM_PAGE_FLAGS) - 1;
Steve Block6ded16b2010-05-10 14:33:55 +0100275
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100276 // To avoid an additional WATERMARK_INVALIDATED flag clearing pass during
277 // scavenge we just invalidate the watermark on each old space page after
278 // processing it. And then we flip the meaning of the WATERMARK_INVALIDATED
279 // flag at the beginning of the next scavenge and each page becomes marked as
280 // having a valid watermark.
281 //
282 // The following invariant must hold for pages in old pointer and map spaces:
283 // If page is in use then page is marked as having invalid watermark at
284 // the beginning and at the end of any GC.
285 //
286 // This invariant guarantees that after flipping flag meaning at the
287 // beginning of scavenge all pages in use will be marked as having valid
288 // watermark.
289 static inline void FlipMeaningOfInvalidatedWatermarkFlag();
290
291 // Returns true if the page allocation watermark was not altered during
292 // scavenge.
293 inline bool IsWatermarkValid();
294
295 inline void InvalidateWatermark(bool value);
296
Steve Block6ded16b2010-05-10 14:33:55 +0100297 inline bool GetPageFlag(PageFlag flag);
298 inline void SetPageFlag(PageFlag flag, bool value);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100299 inline void ClearPageFlags();
300
301 inline void ClearGCFields();
302
Steve Block791712a2010-08-27 10:21:07 +0100303 static const int kAllocationWatermarkOffsetShift = WATERMARK_INVALIDATED + 1;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100304 static const int kAllocationWatermarkOffsetBits = kPageSizeBits + 1;
305 static const uint32_t kAllocationWatermarkOffsetMask =
306 ((1 << kAllocationWatermarkOffsetBits) - 1) <<
307 kAllocationWatermarkOffsetShift;
308
309 static const uint32_t kFlagsMask =
310 ((1 << kAllocationWatermarkOffsetShift) - 1);
311
312 STATIC_CHECK(kBitsPerInt - kAllocationWatermarkOffsetShift >=
313 kAllocationWatermarkOffsetBits);
314
315 // This field contains the meaning of the WATERMARK_INVALIDATED flag.
316 // Instead of clearing this flag from all pages we just flip
317 // its meaning at the beginning of a scavenge.
318 static intptr_t watermark_invalidated_mark_;
Steve Block6ded16b2010-05-10 14:33:55 +0100319
Steve Blocka7e24c12009-10-30 11:49:00 +0000320 //---------------------------------------------------------------------------
321 // Page header description.
322 //
323 // If a page is not in the large object space, the first word,
324 // opaque_header, encodes the next page address (aligned to kPageSize 8K)
325 // and the chunk number (0 ~ 8K-1). Only MemoryAllocator should use
326 // opaque_header. The value range of the opaque_header is [0..kPageSize[,
327 // or [next_page_start, next_page_end[. It cannot point to a valid address
328 // in the current page. If a page is in the large object space, the first
329 // word *may* (if the page start and large object chunk start are the
330 // same) contain the address of the next large object chunk.
331 intptr_t opaque_header;
332
333 // If the page is not in the large object space, the low-order bit of the
334 // second word is set. If the page is in the large object space, the
335 // second word *may* (if the page start and large object chunk start are
336 // the same) contain the large object chunk size. In either case, the
337 // low-order bit for large object pages will be cleared.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100338 // For normal pages this word is used to store page flags and
339 // offset of allocation top.
340 intptr_t flags_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000341
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100342 // This field contains dirty marks for regions covering the page. Only dirty
343 // regions might contain intergenerational references.
344 // Only 32 dirty marks are supported so for large object pages several regions
345 // might be mapped to a single dirty mark.
346 uint32_t dirty_regions_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000347
348 // The index of the page in its owner space.
349 int mc_page_index;
350
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100351 // During mark-compact collections this field contains the forwarding address
352 // of the first live object in this page.
353 // During scavenge collection this field is used to store allocation watermark
354 // if it is altered during scavenge.
Steve Blocka7e24c12009-10-30 11:49:00 +0000355 Address mc_first_forwarded;
Steve Blocka7e24c12009-10-30 11:49:00 +0000356};
357
358
359// ----------------------------------------------------------------------------
360// Space is the abstract superclass for all allocation spaces.
361class Space : public Malloced {
362 public:
363 Space(AllocationSpace id, Executability executable)
364 : id_(id), executable_(executable) {}
365
366 virtual ~Space() {}
367
368 // Does the space need executable memory?
369 Executability executable() { return executable_; }
370
371 // Identity used in error reporting.
372 AllocationSpace identity() { return id_; }
373
Ben Murdochf87a2032010-10-22 12:50:53 +0100374 virtual intptr_t Size() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000375
Steve Block6ded16b2010-05-10 14:33:55 +0100376#ifdef ENABLE_HEAP_PROTECTION
377 // Protect/unprotect the space by marking it read-only/writable.
378 virtual void Protect() = 0;
379 virtual void Unprotect() = 0;
380#endif
381
Steve Blocka7e24c12009-10-30 11:49:00 +0000382#ifdef DEBUG
383 virtual void Print() = 0;
384#endif
385
Leon Clarkee46be812010-01-19 14:06:41 +0000386 // After calling this we can allocate a certain number of bytes using only
387 // linear allocation (with a LinearAllocationScope and an AlwaysAllocateScope)
388 // without using freelists or causing a GC. This is used by partial
389 // snapshots. It returns true of space was reserved or false if a GC is
390 // needed. For paged spaces the space requested must include the space wasted
391 // at the end of each when allocating linearly.
392 virtual bool ReserveSpace(int bytes) = 0;
393
Steve Blocka7e24c12009-10-30 11:49:00 +0000394 private:
395 AllocationSpace id_;
396 Executability executable_;
397};
398
399
400// ----------------------------------------------------------------------------
401// All heap objects containing executable code (code objects) must be allocated
402// from a 2 GB range of memory, so that they can call each other using 32-bit
403// displacements. This happens automatically on 32-bit platforms, where 32-bit
404// displacements cover the entire 4GB virtual address space. On 64-bit
405// platforms, we support this using the CodeRange object, which reserves and
406// manages a range of virtual memory.
407class CodeRange : public AllStatic {
408 public:
409 // Reserves a range of virtual memory, but does not commit any of it.
410 // Can only be called once, at heap initialization time.
411 // Returns false on failure.
412 static bool Setup(const size_t requested_size);
413
414 // Frees the range of virtual memory, and frees the data structures used to
415 // manage it.
416 static void TearDown();
417
418 static bool exists() { return code_range_ != NULL; }
419 static bool contains(Address address) {
420 if (code_range_ == NULL) return false;
421 Address start = static_cast<Address>(code_range_->address());
422 return start <= address && address < start + code_range_->size();
423 }
424
425 // Allocates a chunk of memory from the large-object portion of
426 // the code range. On platforms with no separate code range, should
427 // not be called.
428 static void* AllocateRawMemory(const size_t requested, size_t* allocated);
429 static void FreeRawMemory(void* buf, size_t length);
430
431 private:
432 // The reserved range of virtual memory that all code objects are put in.
433 static VirtualMemory* code_range_;
434 // Plain old data class, just a struct plus a constructor.
435 class FreeBlock {
436 public:
437 FreeBlock(Address start_arg, size_t size_arg)
438 : start(start_arg), size(size_arg) {}
439 FreeBlock(void* start_arg, size_t size_arg)
440 : start(static_cast<Address>(start_arg)), size(size_arg) {}
441
442 Address start;
443 size_t size;
444 };
445
446 // Freed blocks of memory are added to the free list. When the allocation
447 // list is exhausted, the free list is sorted and merged to make the new
448 // allocation list.
449 static List<FreeBlock> free_list_;
450 // Memory is allocated from the free blocks on the allocation list.
451 // The block at current_allocation_block_index_ is the current block.
452 static List<FreeBlock> allocation_list_;
453 static int current_allocation_block_index_;
454
455 // Finds a block on the allocation list that contains at least the
456 // requested amount of memory. If none is found, sorts and merges
457 // the existing free memory blocks, and searches again.
458 // If none can be found, terminates V8 with FatalProcessOutOfMemory.
459 static void GetNextAllocationBlock(size_t requested);
460 // Compares the start addresses of two free blocks.
461 static int CompareFreeBlockAddress(const FreeBlock* left,
462 const FreeBlock* right);
463};
464
465
466// ----------------------------------------------------------------------------
467// A space acquires chunks of memory from the operating system. The memory
468// allocator manages chunks for the paged heap spaces (old space and map
469// space). A paged chunk consists of pages. Pages in a chunk have contiguous
470// addresses and are linked as a list.
471//
472// The allocator keeps an initial chunk which is used for the new space. The
473// leftover regions of the initial chunk are used for the initial chunks of
474// old space and map space if they are big enough to hold at least one page.
475// The allocator assumes that there is one old space and one map space, each
476// expands the space by allocating kPagesPerChunk pages except the last
477// expansion (before running out of space). The first chunk may contain fewer
478// than kPagesPerChunk pages as well.
479//
480// The memory allocator also allocates chunks for the large object space, but
481// they are managed by the space itself. The new space does not expand.
Steve Block6ded16b2010-05-10 14:33:55 +0100482//
483// The fact that pages for paged spaces are allocated and deallocated in chunks
484// induces a constraint on the order of pages in a linked lists. We say that
485// pages are linked in the chunk-order if and only if every two consecutive
486// pages from the same chunk are consecutive in the linked list.
487//
488
Steve Blocka7e24c12009-10-30 11:49:00 +0000489
490class MemoryAllocator : public AllStatic {
491 public:
492 // Initializes its internal bookkeeping structures.
493 // Max capacity of the total space.
Ben Murdochf87a2032010-10-22 12:50:53 +0100494 static bool Setup(intptr_t max_capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +0000495
496 // Deletes valid chunks.
497 static void TearDown();
498
499 // Reserves an initial address range of virtual memory to be split between
500 // the two new space semispaces, the old space, and the map space. The
501 // memory is not yet committed or assigned to spaces and split into pages.
502 // The initial chunk is unmapped when the memory allocator is torn down.
503 // This function should only be called when there is not already a reserved
504 // initial chunk (initial_chunk_ should be NULL). It returns the start
505 // address of the initial chunk if successful, with the side effect of
506 // setting the initial chunk, or else NULL if unsuccessful and leaves the
507 // initial chunk NULL.
508 static void* ReserveInitialChunk(const size_t requested);
509
510 // Commits pages from an as-yet-unmanaged block of virtual memory into a
511 // paged space. The block should be part of the initial chunk reserved via
512 // a call to ReserveInitialChunk. The number of pages is always returned in
513 // the output parameter num_pages. This function assumes that the start
514 // address is non-null and that it is big enough to hold at least one
515 // page-aligned page. The call always succeeds, and num_pages is always
516 // greater than zero.
517 static Page* CommitPages(Address start, size_t size, PagedSpace* owner,
518 int* num_pages);
519
520 // Commit a contiguous block of memory from the initial chunk. Assumes that
521 // the address is not NULL, the size is greater than zero, and that the
522 // block is contained in the initial chunk. Returns true if it succeeded
523 // and false otherwise.
524 static bool CommitBlock(Address start, size_t size, Executability executable);
525
Steve Blocka7e24c12009-10-30 11:49:00 +0000526 // Uncommit a contiguous block of memory [start..(start+size)[.
527 // start is not NULL, the size is greater than zero, and the
528 // block is contained in the initial chunk. Returns true if it succeeded
529 // and false otherwise.
530 static bool UncommitBlock(Address start, size_t size);
531
Leon Clarke4515c472010-02-03 11:58:03 +0000532 // Zaps a contiguous block of memory [start..(start+size)[ thus
533 // filling it up with a recognizable non-NULL bit pattern.
534 static void ZapBlock(Address start, size_t size);
535
Steve Blocka7e24c12009-10-30 11:49:00 +0000536 // Attempts to allocate the requested (non-zero) number of pages from the
537 // OS. Fewer pages might be allocated than requested. If it fails to
538 // allocate memory for the OS or cannot allocate a single page, this
539 // function returns an invalid page pointer (NULL). The caller must check
540 // whether the returned page is valid (by calling Page::is_valid()). It is
541 // guaranteed that allocated pages have contiguous addresses. The actual
542 // number of allocated pages is returned in the output parameter
543 // allocated_pages. If the PagedSpace owner is executable and there is
544 // a code range, the pages are allocated from the code range.
545 static Page* AllocatePages(int requested_pages, int* allocated_pages,
546 PagedSpace* owner);
547
Steve Block6ded16b2010-05-10 14:33:55 +0100548 // Frees pages from a given page and after. Requires pages to be
549 // linked in chunk-order (see comment for class).
550 // If 'p' is the first page of a chunk, pages from 'p' are freed
551 // and this function returns an invalid page pointer.
552 // Otherwise, the function searches a page after 'p' that is
553 // the first page of a chunk. Pages after the found page
554 // are freed and the function returns 'p'.
Steve Blocka7e24c12009-10-30 11:49:00 +0000555 static Page* FreePages(Page* p);
556
Steve Block6ded16b2010-05-10 14:33:55 +0100557 // Frees all pages owned by given space.
558 static void FreeAllPages(PagedSpace* space);
559
Steve Blocka7e24c12009-10-30 11:49:00 +0000560 // Allocates and frees raw memory of certain size.
561 // These are just thin wrappers around OS::Allocate and OS::Free,
562 // but keep track of allocated bytes as part of heap.
563 // If the flag is EXECUTABLE and a code range exists, the requested
564 // memory is allocated from the code range. If a code range exists
565 // and the freed memory is in it, the code range manages the freed memory.
566 static void* AllocateRawMemory(const size_t requested,
567 size_t* allocated,
568 Executability executable);
Steve Block791712a2010-08-27 10:21:07 +0100569 static void FreeRawMemory(void* buf,
570 size_t length,
571 Executability executable);
Iain Merrick9ac36c92010-09-13 15:29:50 +0100572 static void PerformAllocationCallback(ObjectSpace space,
573 AllocationAction action,
574 size_t size);
575
576 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
577 ObjectSpace space,
578 AllocationAction action);
579 static void RemoveMemoryAllocationCallback(
580 MemoryAllocationCallback callback);
581 static bool MemoryAllocationCallbackRegistered(
582 MemoryAllocationCallback callback);
Steve Blocka7e24c12009-10-30 11:49:00 +0000583
584 // Returns the maximum available bytes of heaps.
Ben Murdochf87a2032010-10-22 12:50:53 +0100585 static intptr_t Available() {
586 return capacity_ < size_ ? 0 : capacity_ - size_;
587 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000588
589 // Returns allocated spaces in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100590 static intptr_t Size() { return size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000591
Steve Block791712a2010-08-27 10:21:07 +0100592 // Returns allocated executable spaces in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100593 static intptr_t SizeExecutable() { return size_executable_; }
Steve Block791712a2010-08-27 10:21:07 +0100594
Steve Blocka7e24c12009-10-30 11:49:00 +0000595 // Returns maximum available bytes that the old space can have.
Ben Murdochf87a2032010-10-22 12:50:53 +0100596 static intptr_t MaxAvailable() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000597 return (Available() / Page::kPageSize) * Page::kObjectAreaSize;
598 }
599
600 // Links two pages.
601 static inline void SetNextPage(Page* prev, Page* next);
602
603 // Returns the next page of a given page.
604 static inline Page* GetNextPage(Page* p);
605
606 // Checks whether a page belongs to a space.
607 static inline bool IsPageInSpace(Page* p, PagedSpace* space);
608
609 // Returns the space that owns the given page.
610 static inline PagedSpace* PageOwner(Page* page);
611
612 // Finds the first/last page in the same chunk as a given page.
613 static Page* FindFirstPageInSameChunk(Page* p);
614 static Page* FindLastPageInSameChunk(Page* p);
615
Steve Block6ded16b2010-05-10 14:33:55 +0100616 // Relinks list of pages owned by space to make it chunk-ordered.
617 // Returns new first and last pages of space.
618 // Also returns last page in relinked list which has WasInUsedBeforeMC
619 // flag set.
620 static void RelinkPageListInChunkOrder(PagedSpace* space,
621 Page** first_page,
622 Page** last_page,
623 Page** last_page_in_use);
624
Steve Blocka7e24c12009-10-30 11:49:00 +0000625#ifdef ENABLE_HEAP_PROTECTION
626 // Protect/unprotect a block of memory by marking it read-only/writable.
627 static inline void Protect(Address start, size_t size);
628 static inline void Unprotect(Address start, size_t size,
629 Executability executable);
630
631 // Protect/unprotect a chunk given a page in the chunk.
632 static inline void ProtectChunkFromPage(Page* page);
633 static inline void UnprotectChunkFromPage(Page* page);
634#endif
635
636#ifdef DEBUG
637 // Reports statistic info of the space.
638 static void ReportStatistics();
639#endif
640
641 // Due to encoding limitation, we can only have 8K chunks.
Leon Clarkee46be812010-01-19 14:06:41 +0000642 static const int kMaxNofChunks = 1 << kPageSizeBits;
Steve Blocka7e24c12009-10-30 11:49:00 +0000643 // If a chunk has at least 16 pages, the maximum heap size is about
644 // 8K * 8K * 16 = 1G bytes.
645#ifdef V8_TARGET_ARCH_X64
646 static const int kPagesPerChunk = 32;
647#else
648 static const int kPagesPerChunk = 16;
649#endif
650 static const int kChunkSize = kPagesPerChunk * Page::kPageSize;
651
652 private:
653 // Maximum space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100654 static intptr_t capacity_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000655
656 // Allocated space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100657 static intptr_t size_;
Steve Block791712a2010-08-27 10:21:07 +0100658 // Allocated executable space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100659 static intptr_t size_executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000660
Iain Merrick9ac36c92010-09-13 15:29:50 +0100661 struct MemoryAllocationCallbackRegistration {
662 MemoryAllocationCallbackRegistration(MemoryAllocationCallback callback,
663 ObjectSpace space,
664 AllocationAction action)
665 : callback(callback), space(space), action(action) {
666 }
667 MemoryAllocationCallback callback;
668 ObjectSpace space;
669 AllocationAction action;
670 };
671 // A List of callback that are triggered when memory is allocated or free'd
672 static List<MemoryAllocationCallbackRegistration>
673 memory_allocation_callbacks_;
674
Steve Blocka7e24c12009-10-30 11:49:00 +0000675 // The initial chunk of virtual memory.
676 static VirtualMemory* initial_chunk_;
677
678 // Allocated chunk info: chunk start address, chunk size, and owning space.
679 class ChunkInfo BASE_EMBEDDED {
680 public:
Iain Merrick9ac36c92010-09-13 15:29:50 +0100681 ChunkInfo() : address_(NULL),
682 size_(0),
683 owner_(NULL),
684 executable_(NOT_EXECUTABLE) {}
685 inline void init(Address a, size_t s, PagedSpace* o);
Steve Blocka7e24c12009-10-30 11:49:00 +0000686 Address address() { return address_; }
687 size_t size() { return size_; }
688 PagedSpace* owner() { return owner_; }
Iain Merrick9ac36c92010-09-13 15:29:50 +0100689 // We save executability of the owner to allow using it
690 // when collecting stats after the owner has been destroyed.
691 Executability executable() const { return executable_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000692
693 private:
694 Address address_;
695 size_t size_;
696 PagedSpace* owner_;
Iain Merrick9ac36c92010-09-13 15:29:50 +0100697 Executability executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000698 };
699
700 // Chunks_, free_chunk_ids_ and top_ act as a stack of free chunk ids.
701 static List<ChunkInfo> chunks_;
702 static List<int> free_chunk_ids_;
703 static int max_nof_chunks_;
704 static int top_;
705
706 // Push/pop a free chunk id onto/from the stack.
707 static void Push(int free_chunk_id);
708 static int Pop();
709 static bool OutOfChunkIds() { return top_ == 0; }
710
711 // Frees a chunk.
712 static void DeleteChunk(int chunk_id);
713
714 // Basic check whether a chunk id is in the valid range.
715 static inline bool IsValidChunkId(int chunk_id);
716
717 // Checks whether a chunk id identifies an allocated chunk.
718 static inline bool IsValidChunk(int chunk_id);
719
720 // Returns the chunk id that a page belongs to.
721 static inline int GetChunkId(Page* p);
722
723 // True if the address lies in the initial chunk.
724 static inline bool InInitialChunk(Address address);
725
726 // Initializes pages in a chunk. Returns the first page address.
727 // This function and GetChunkId() are provided for the mark-compact
728 // collector to rebuild page headers in the from space, which is
729 // used as a marking stack and its page headers are destroyed.
730 static Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
731 PagedSpace* owner);
Steve Block6ded16b2010-05-10 14:33:55 +0100732
733 static Page* RelinkPagesInChunk(int chunk_id,
734 Address chunk_start,
735 size_t chunk_size,
736 Page* prev,
737 Page** last_page_in_use);
Steve Blocka7e24c12009-10-30 11:49:00 +0000738};
739
740
741// -----------------------------------------------------------------------------
742// Interface for heap object iterator to be implemented by all object space
743// object iterators.
744//
Leon Clarked91b9f72010-01-27 17:25:45 +0000745// NOTE: The space specific object iterators also implements the own next()
746// method which is used to avoid using virtual functions
Steve Blocka7e24c12009-10-30 11:49:00 +0000747// iterating a specific space.
748
749class ObjectIterator : public Malloced {
750 public:
751 virtual ~ObjectIterator() { }
752
Steve Blocka7e24c12009-10-30 11:49:00 +0000753 virtual HeapObject* next_object() = 0;
754};
755
756
757// -----------------------------------------------------------------------------
758// Heap object iterator in new/old/map spaces.
759//
760// A HeapObjectIterator iterates objects from a given address to the
761// top of a space. The given address must be below the current
762// allocation pointer (space top). There are some caveats.
763//
764// (1) If the space top changes upward during iteration (because of
765// allocating new objects), the iterator does not iterate objects
766// above the original space top. The caller must create a new
767// iterator starting from the old top in order to visit these new
768// objects.
769//
770// (2) If new objects are allocated below the original allocation top
771// (e.g., free-list allocation in paged spaces), the new objects
772// may or may not be iterated depending on their position with
773// respect to the current point of iteration.
774//
775// (3) The space top should not change downward during iteration,
776// otherwise the iterator will return not-necessarily-valid
777// objects.
778
779class HeapObjectIterator: public ObjectIterator {
780 public:
781 // Creates a new object iterator in a given space. If a start
782 // address is not given, the iterator starts from the space bottom.
783 // If the size function is not given, the iterator calls the default
784 // Object::Size().
785 explicit HeapObjectIterator(PagedSpace* space);
786 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
787 HeapObjectIterator(PagedSpace* space, Address start);
788 HeapObjectIterator(PagedSpace* space,
789 Address start,
790 HeapObjectCallback size_func);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100791 HeapObjectIterator(Page* page, HeapObjectCallback size_func);
Steve Blocka7e24c12009-10-30 11:49:00 +0000792
Leon Clarked91b9f72010-01-27 17:25:45 +0000793 inline HeapObject* next() {
794 return (cur_addr_ < cur_limit_) ? FromCurrentPage() : FromNextPage();
795 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000796
797 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +0000798 virtual HeapObject* next_object() { return next(); }
799
800 private:
801 Address cur_addr_; // current iteration point
802 Address end_addr_; // end iteration point
803 Address cur_limit_; // current page limit
804 HeapObjectCallback size_func_; // size function
805 Page* end_page_; // caches the page of the end address
806
Leon Clarked91b9f72010-01-27 17:25:45 +0000807 HeapObject* FromCurrentPage() {
808 ASSERT(cur_addr_ < cur_limit_);
809
810 HeapObject* obj = HeapObject::FromAddress(cur_addr_);
811 int obj_size = (size_func_ == NULL) ? obj->Size() : size_func_(obj);
812 ASSERT_OBJECT_SIZE(obj_size);
813
814 cur_addr_ += obj_size;
815 ASSERT(cur_addr_ <= cur_limit_);
816
817 return obj;
818 }
819
820 // Slow path of next, goes into the next page.
821 HeapObject* FromNextPage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000822
823 // Initializes fields.
824 void Initialize(Address start, Address end, HeapObjectCallback size_func);
825
826#ifdef DEBUG
827 // Verifies whether fields have valid values.
828 void Verify();
829#endif
830};
831
832
833// -----------------------------------------------------------------------------
834// A PageIterator iterates the pages in a paged space.
835//
836// The PageIterator class provides three modes for iterating pages in a space:
837// PAGES_IN_USE iterates pages containing allocated objects.
838// PAGES_USED_BY_MC iterates pages that hold relocated objects during a
839// mark-compact collection.
840// ALL_PAGES iterates all pages in the space.
841//
842// There are some caveats.
843//
844// (1) If the space expands during iteration, new pages will not be
845// returned by the iterator in any mode.
846//
847// (2) If new objects are allocated during iteration, they will appear
848// in pages returned by the iterator. Allocation may cause the
849// allocation pointer or MC allocation pointer in the last page to
850// change between constructing the iterator and iterating the last
851// page.
852//
853// (3) The space should not shrink during iteration, otherwise the
854// iterator will return deallocated pages.
855
856class PageIterator BASE_EMBEDDED {
857 public:
858 enum Mode {
859 PAGES_IN_USE,
860 PAGES_USED_BY_MC,
861 ALL_PAGES
862 };
863
864 PageIterator(PagedSpace* space, Mode mode);
865
866 inline bool has_next();
867 inline Page* next();
868
869 private:
870 PagedSpace* space_;
871 Page* prev_page_; // Previous page returned.
872 Page* stop_page_; // Page to stop at (last page returned by the iterator).
873};
874
875
876// -----------------------------------------------------------------------------
877// A space has a list of pages. The next page can be accessed via
878// Page::next_page() call. The next page of the last page is an
879// invalid page pointer. A space can expand and shrink dynamically.
880
881// An abstraction of allocation and relocation pointers in a page-structured
882// space.
883class AllocationInfo {
884 public:
885 Address top; // current allocation top
886 Address limit; // current allocation limit
887
888#ifdef DEBUG
889 bool VerifyPagedAllocation() {
890 return (Page::FromAllocationTop(top) == Page::FromAllocationTop(limit))
891 && (top <= limit);
892 }
893#endif
894};
895
896
897// An abstraction of the accounting statistics of a page-structured space.
898// The 'capacity' of a space is the number of object-area bytes (ie, not
899// including page bookkeeping structures) currently in the space. The 'size'
900// of a space is the number of allocated bytes, the 'waste' in the space is
901// the number of bytes that are not allocated and not available to
902// allocation without reorganizing the space via a GC (eg, small blocks due
903// to internal fragmentation, top of page areas in map space), and the bytes
904// 'available' is the number of unallocated bytes that are not waste. The
905// capacity is the sum of size, waste, and available.
906//
907// The stats are only set by functions that ensure they stay balanced. These
908// functions increase or decrease one of the non-capacity stats in
909// conjunction with capacity, or else they always balance increases and
910// decreases to the non-capacity stats.
911class AllocationStats BASE_EMBEDDED {
912 public:
913 AllocationStats() { Clear(); }
914
915 // Zero out all the allocation statistics (ie, no capacity).
916 void Clear() {
917 capacity_ = 0;
918 available_ = 0;
919 size_ = 0;
920 waste_ = 0;
921 }
922
923 // Reset the allocation statistics (ie, available = capacity with no
924 // wasted or allocated bytes).
925 void Reset() {
926 available_ = capacity_;
927 size_ = 0;
928 waste_ = 0;
929 }
930
931 // Accessors for the allocation statistics.
Ben Murdochf87a2032010-10-22 12:50:53 +0100932 intptr_t Capacity() { return capacity_; }
933 intptr_t Available() { return available_; }
934 intptr_t Size() { return size_; }
935 intptr_t Waste() { return waste_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000936
937 // Grow the space by adding available bytes.
938 void ExpandSpace(int size_in_bytes) {
939 capacity_ += size_in_bytes;
940 available_ += size_in_bytes;
941 }
942
943 // Shrink the space by removing available bytes.
944 void ShrinkSpace(int size_in_bytes) {
945 capacity_ -= size_in_bytes;
946 available_ -= size_in_bytes;
947 }
948
949 // Allocate from available bytes (available -> size).
Ben Murdochf87a2032010-10-22 12:50:53 +0100950 void AllocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000951 available_ -= size_in_bytes;
952 size_ += size_in_bytes;
953 }
954
955 // Free allocated bytes, making them available (size -> available).
Ben Murdochf87a2032010-10-22 12:50:53 +0100956 void DeallocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000957 size_ -= size_in_bytes;
958 available_ += size_in_bytes;
959 }
960
961 // Waste free bytes (available -> waste).
962 void WasteBytes(int size_in_bytes) {
963 available_ -= size_in_bytes;
964 waste_ += size_in_bytes;
965 }
966
967 // Consider the wasted bytes to be allocated, as they contain filler
968 // objects (waste -> size).
Ben Murdochf87a2032010-10-22 12:50:53 +0100969 void FillWastedBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000970 waste_ -= size_in_bytes;
971 size_ += size_in_bytes;
972 }
973
974 private:
Ben Murdochf87a2032010-10-22 12:50:53 +0100975 intptr_t capacity_;
976 intptr_t available_;
977 intptr_t size_;
978 intptr_t waste_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000979};
980
981
982class PagedSpace : public Space {
983 public:
984 // Creates a space with a maximum capacity, and an id.
Ben Murdochf87a2032010-10-22 12:50:53 +0100985 PagedSpace(intptr_t max_capacity,
986 AllocationSpace id,
987 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000988
989 virtual ~PagedSpace() {}
990
991 // Set up the space using the given address range of virtual memory (from
992 // the memory allocator's initial chunk) if possible. If the block of
993 // addresses is not big enough to contain a single page-aligned page, a
994 // fresh chunk will be allocated.
995 bool Setup(Address start, size_t size);
996
997 // Returns true if the space has been successfully set up and not
998 // subsequently torn down.
999 bool HasBeenSetup();
1000
1001 // Cleans up the space, frees all pages in this space except those belonging
1002 // to the initial chunk, uncommits addresses in the initial chunk.
1003 void TearDown();
1004
1005 // Checks whether an object/address is in this space.
1006 inline bool Contains(Address a);
1007 bool Contains(HeapObject* o) { return Contains(o->address()); }
1008
1009 // Given an address occupied by a live object, return that object if it is
1010 // in this space, or Failure::Exception() if it is not. The implementation
1011 // iterates over objects in the page containing the address, the cost is
1012 // linear in the number of objects in the page. It may be slow.
1013 Object* FindObject(Address addr);
1014
1015 // Checks whether page is currently in use by this space.
1016 bool IsUsed(Page* page);
1017
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001018 void MarkAllPagesClean();
Steve Blocka7e24c12009-10-30 11:49:00 +00001019
1020 // Prepares for a mark-compact GC.
Steve Block6ded16b2010-05-10 14:33:55 +01001021 virtual void PrepareForMarkCompact(bool will_compact);
Steve Blocka7e24c12009-10-30 11:49:00 +00001022
Steve Block6ded16b2010-05-10 14:33:55 +01001023 // The top of allocation in a page in this space. Undefined if page is unused.
1024 Address PageAllocationTop(Page* page) {
1025 return page == TopPageOf(allocation_info_) ? top()
1026 : PageAllocationLimit(page);
1027 }
1028
1029 // The limit of allocation for a page in this space.
1030 virtual Address PageAllocationLimit(Page* page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001031
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001032 void FlushTopPageWatermark() {
1033 AllocationTopPage()->SetCachedAllocationWatermark(top());
1034 AllocationTopPage()->InvalidateWatermark(true);
1035 }
1036
Steve Blocka7e24c12009-10-30 11:49:00 +00001037 // Current capacity without growing (Size() + Available() + Waste()).
Ben Murdochf87a2032010-10-22 12:50:53 +01001038 intptr_t Capacity() { return accounting_stats_.Capacity(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001039
Steve Block3ce2e202009-11-05 08:53:23 +00001040 // Total amount of memory committed for this space. For paged
1041 // spaces this equals the capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01001042 intptr_t CommittedMemory() { return Capacity(); }
Steve Block3ce2e202009-11-05 08:53:23 +00001043
Steve Blocka7e24c12009-10-30 11:49:00 +00001044 // Available bytes without growing.
Ben Murdochf87a2032010-10-22 12:50:53 +01001045 intptr_t Available() { return accounting_stats_.Available(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001046
1047 // Allocated bytes in this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001048 virtual intptr_t Size() { return accounting_stats_.Size(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001049
1050 // Wasted bytes due to fragmentation and not recoverable until the
1051 // next GC of this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001052 intptr_t Waste() { return accounting_stats_.Waste(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001053
1054 // Returns the address of the first object in this space.
1055 Address bottom() { return first_page_->ObjectAreaStart(); }
1056
1057 // Returns the allocation pointer in this space.
1058 Address top() { return allocation_info_.top; }
1059
1060 // Allocate the requested number of bytes in the space if possible, return a
1061 // failure object if not.
1062 inline Object* AllocateRaw(int size_in_bytes);
1063
1064 // Allocate the requested number of bytes for relocation during mark-compact
1065 // collection.
1066 inline Object* MCAllocateRaw(int size_in_bytes);
1067
Leon Clarkee46be812010-01-19 14:06:41 +00001068 virtual bool ReserveSpace(int bytes);
1069
1070 // Used by ReserveSpace.
1071 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001072
Steve Block6ded16b2010-05-10 14:33:55 +01001073 // Free all pages in range from prev (exclusive) to last (inclusive).
1074 // Freed pages are moved to the end of page list.
1075 void FreePages(Page* prev, Page* last);
1076
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001077 // Deallocates a block.
1078 virtual void DeallocateBlock(Address start,
1079 int size_in_bytes,
1080 bool add_to_freelist) = 0;
1081
Steve Block6ded16b2010-05-10 14:33:55 +01001082 // Set space allocation info.
1083 void SetTop(Address top) {
1084 allocation_info_.top = top;
1085 allocation_info_.limit = PageAllocationLimit(Page::FromAllocationTop(top));
1086 }
1087
Steve Blocka7e24c12009-10-30 11:49:00 +00001088 // ---------------------------------------------------------------------------
1089 // Mark-compact collection support functions
1090
1091 // Set the relocation point to the beginning of the space.
1092 void MCResetRelocationInfo();
1093
1094 // Writes relocation info to the top page.
1095 void MCWriteRelocationInfoToPage() {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001096 TopPageOf(mc_forwarding_info_)->
1097 SetAllocationWatermark(mc_forwarding_info_.top);
Steve Blocka7e24c12009-10-30 11:49:00 +00001098 }
1099
1100 // Computes the offset of a given address in this space to the beginning
1101 // of the space.
1102 int MCSpaceOffsetForAddress(Address addr);
1103
1104 // Updates the allocation pointer to the relocation top after a mark-compact
1105 // collection.
1106 virtual void MCCommitRelocationInfo() = 0;
1107
1108 // Releases half of unused pages.
1109 void Shrink();
1110
1111 // Ensures that the capacity is at least 'capacity'. Returns false on failure.
1112 bool EnsureCapacity(int capacity);
1113
1114#ifdef ENABLE_HEAP_PROTECTION
1115 // Protect/unprotect the space by marking it read-only/writable.
1116 void Protect();
1117 void Unprotect();
1118#endif
1119
1120#ifdef DEBUG
1121 // Print meta info and objects in this space.
1122 virtual void Print();
1123
1124 // Verify integrity of this space.
1125 virtual void Verify(ObjectVisitor* visitor);
1126
1127 // Overridden by subclasses to verify space-specific object
1128 // properties (e.g., only maps or free-list nodes are in map space).
1129 virtual void VerifyObject(HeapObject* obj) {}
1130
1131 // Report code object related statistics
1132 void CollectCodeStatistics();
1133 static void ReportCodeStatistics();
1134 static void ResetCodeStatistics();
1135#endif
1136
Steve Block6ded16b2010-05-10 14:33:55 +01001137 // Returns the page of the allocation pointer.
1138 Page* AllocationTopPage() { return TopPageOf(allocation_info_); }
1139
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001140 void RelinkPageListInChunkOrder(bool deallocate_blocks);
1141
Steve Blocka7e24c12009-10-30 11:49:00 +00001142 protected:
1143 // Maximum capacity of this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001144 intptr_t max_capacity_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001145
1146 // Accounting information for this space.
1147 AllocationStats accounting_stats_;
1148
1149 // The first page in this space.
1150 Page* first_page_;
1151
1152 // The last page in this space. Initially set in Setup, updated in
1153 // Expand and Shrink.
1154 Page* last_page_;
1155
Steve Block6ded16b2010-05-10 14:33:55 +01001156 // True if pages owned by this space are linked in chunk-order.
1157 // See comment for class MemoryAllocator for definition of chunk-order.
1158 bool page_list_is_chunk_ordered_;
1159
Steve Blocka7e24c12009-10-30 11:49:00 +00001160 // Normal allocation information.
1161 AllocationInfo allocation_info_;
1162
1163 // Relocation information during mark-compact collections.
1164 AllocationInfo mc_forwarding_info_;
1165
1166 // Bytes of each page that cannot be allocated. Possibly non-zero
1167 // for pages in spaces with only fixed-size objects. Always zero
1168 // for pages in spaces with variable sized objects (those pages are
1169 // padded with free-list nodes).
1170 int page_extra_;
1171
1172 // Sets allocation pointer to a page bottom.
1173 static void SetAllocationInfo(AllocationInfo* alloc_info, Page* p);
1174
1175 // Returns the top page specified by an allocation info structure.
1176 static Page* TopPageOf(AllocationInfo alloc_info) {
1177 return Page::FromAllocationTop(alloc_info.limit);
1178 }
1179
Leon Clarked91b9f72010-01-27 17:25:45 +00001180 int CountPagesToTop() {
1181 Page* p = Page::FromAllocationTop(allocation_info_.top);
1182 PageIterator it(this, PageIterator::ALL_PAGES);
1183 int counter = 1;
1184 while (it.has_next()) {
1185 if (it.next() == p) return counter;
1186 counter++;
1187 }
1188 UNREACHABLE();
1189 return -1;
1190 }
1191
Steve Blocka7e24c12009-10-30 11:49:00 +00001192 // Expands the space by allocating a fixed number of pages. Returns false if
1193 // it cannot allocate requested number of pages from OS. Newly allocated
1194 // pages are append to the last_page;
1195 bool Expand(Page* last_page);
1196
1197 // Generic fast case allocation function that tries linear allocation in
1198 // the top page of 'alloc_info'. Returns NULL on failure.
1199 inline HeapObject* AllocateLinearly(AllocationInfo* alloc_info,
1200 int size_in_bytes);
1201
1202 // During normal allocation or deserialization, roll to the next page in
1203 // the space (there is assumed to be one) and allocate there. This
1204 // function is space-dependent.
1205 virtual HeapObject* AllocateInNextPage(Page* current_page,
1206 int size_in_bytes) = 0;
1207
1208 // Slow path of AllocateRaw. This function is space-dependent.
1209 virtual HeapObject* SlowAllocateRaw(int size_in_bytes) = 0;
1210
1211 // Slow path of MCAllocateRaw.
1212 HeapObject* SlowMCAllocateRaw(int size_in_bytes);
1213
1214#ifdef DEBUG
Leon Clarkee46be812010-01-19 14:06:41 +00001215 // Returns the number of total pages in this space.
1216 int CountTotalPages();
Steve Blocka7e24c12009-10-30 11:49:00 +00001217#endif
1218 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001219
1220 // Returns a pointer to the page of the relocation pointer.
1221 Page* MCRelocationTopPage() { return TopPageOf(mc_forwarding_info_); }
1222
Steve Blocka7e24c12009-10-30 11:49:00 +00001223 friend class PageIterator;
1224};
1225
1226
1227#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1228class NumberAndSizeInfo BASE_EMBEDDED {
1229 public:
1230 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1231
1232 int number() const { return number_; }
1233 void increment_number(int num) { number_ += num; }
1234
1235 int bytes() const { return bytes_; }
1236 void increment_bytes(int size) { bytes_ += size; }
1237
1238 void clear() {
1239 number_ = 0;
1240 bytes_ = 0;
1241 }
1242
1243 private:
1244 int number_;
1245 int bytes_;
1246};
1247
1248
1249// HistogramInfo class for recording a single "bar" of a histogram. This
1250// class is used for collecting statistics to print to stdout (when compiled
1251// with DEBUG) or to the log file (when compiled with
1252// ENABLE_LOGGING_AND_PROFILING).
1253class HistogramInfo: public NumberAndSizeInfo {
1254 public:
1255 HistogramInfo() : NumberAndSizeInfo() {}
1256
1257 const char* name() { return name_; }
1258 void set_name(const char* name) { name_ = name; }
1259
1260 private:
1261 const char* name_;
1262};
1263#endif
1264
1265
1266// -----------------------------------------------------------------------------
1267// SemiSpace in young generation
1268//
1269// A semispace is a contiguous chunk of memory. The mark-compact collector
1270// uses the memory in the from space as a marking stack when tracing live
1271// objects.
1272
1273class SemiSpace : public Space {
1274 public:
1275 // Constructor.
1276 SemiSpace() :Space(NEW_SPACE, NOT_EXECUTABLE) {
1277 start_ = NULL;
1278 age_mark_ = NULL;
1279 }
1280
1281 // Sets up the semispace using the given chunk.
1282 bool Setup(Address start, int initial_capacity, int maximum_capacity);
1283
1284 // Tear down the space. Heap memory was not allocated by the space, so it
1285 // is not deallocated here.
1286 void TearDown();
1287
1288 // True if the space has been set up but not torn down.
1289 bool HasBeenSetup() { return start_ != NULL; }
1290
1291 // Grow the size of the semispace by committing extra virtual memory.
1292 // Assumes that the caller has checked that the semispace has not reached
1293 // its maximum capacity (and thus there is space available in the reserved
1294 // address range to grow).
1295 bool Grow();
1296
1297 // Grow the semispace to the new capacity. The new capacity
1298 // requested must be larger than the current capacity.
1299 bool GrowTo(int new_capacity);
1300
1301 // Shrinks the semispace to the new capacity. The new capacity
1302 // requested must be more than the amount of used memory in the
1303 // semispace and less than the current capacity.
1304 bool ShrinkTo(int new_capacity);
1305
1306 // Returns the start address of the space.
1307 Address low() { return start_; }
1308 // Returns one past the end address of the space.
1309 Address high() { return low() + capacity_; }
1310
1311 // Age mark accessors.
1312 Address age_mark() { return age_mark_; }
1313 void set_age_mark(Address mark) { age_mark_ = mark; }
1314
1315 // True if the address is in the address range of this semispace (not
1316 // necessarily below the allocation pointer).
1317 bool Contains(Address a) {
1318 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1319 == reinterpret_cast<uintptr_t>(start_);
1320 }
1321
1322 // True if the object is a heap object in the address range of this
1323 // semispace (not necessarily below the allocation pointer).
1324 bool Contains(Object* o) {
1325 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1326 }
1327
1328 // The offset of an address from the beginning of the space.
Steve Blockd0582a62009-12-15 09:54:21 +00001329 int SpaceOffsetForAddress(Address addr) {
1330 return static_cast<int>(addr - low());
1331 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001332
Leon Clarkee46be812010-01-19 14:06:41 +00001333 // If we don't have these here then SemiSpace will be abstract. However
1334 // they should never be called.
Ben Murdochf87a2032010-10-22 12:50:53 +01001335 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001336 UNREACHABLE();
1337 return 0;
1338 }
1339
Leon Clarkee46be812010-01-19 14:06:41 +00001340 virtual bool ReserveSpace(int bytes) {
1341 UNREACHABLE();
1342 return false;
1343 }
1344
Steve Blocka7e24c12009-10-30 11:49:00 +00001345 bool is_committed() { return committed_; }
1346 bool Commit();
1347 bool Uncommit();
1348
Steve Block6ded16b2010-05-10 14:33:55 +01001349#ifdef ENABLE_HEAP_PROTECTION
1350 // Protect/unprotect the space by marking it read-only/writable.
1351 virtual void Protect() {}
1352 virtual void Unprotect() {}
1353#endif
1354
Steve Blocka7e24c12009-10-30 11:49:00 +00001355#ifdef DEBUG
1356 virtual void Print();
1357 virtual void Verify();
1358#endif
1359
1360 // Returns the current capacity of the semi space.
1361 int Capacity() { return capacity_; }
1362
1363 // Returns the maximum capacity of the semi space.
1364 int MaximumCapacity() { return maximum_capacity_; }
1365
1366 // Returns the initial capacity of the semi space.
1367 int InitialCapacity() { return initial_capacity_; }
1368
1369 private:
1370 // The current and maximum capacity of the space.
1371 int capacity_;
1372 int maximum_capacity_;
1373 int initial_capacity_;
1374
1375 // The start address of the space.
1376 Address start_;
1377 // Used to govern object promotion during mark-compact collection.
1378 Address age_mark_;
1379
1380 // Masks and comparison values to test for containment in this semispace.
1381 uintptr_t address_mask_;
1382 uintptr_t object_mask_;
1383 uintptr_t object_expected_;
1384
1385 bool committed_;
1386
1387 public:
1388 TRACK_MEMORY("SemiSpace")
1389};
1390
1391
1392// A SemiSpaceIterator is an ObjectIterator that iterates over the active
1393// semispace of the heap's new space. It iterates over the objects in the
1394// semispace from a given start address (defaulting to the bottom of the
1395// semispace) to the top of the semispace. New objects allocated after the
1396// iterator is created are not iterated.
1397class SemiSpaceIterator : public ObjectIterator {
1398 public:
1399 // Create an iterator over the objects in the given space. If no start
1400 // address is given, the iterator starts from the bottom of the space. If
1401 // no size function is given, the iterator calls Object::Size().
1402 explicit SemiSpaceIterator(NewSpace* space);
1403 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
1404 SemiSpaceIterator(NewSpace* space, Address start);
1405
Steve Blocka7e24c12009-10-30 11:49:00 +00001406 HeapObject* next() {
Leon Clarked91b9f72010-01-27 17:25:45 +00001407 if (current_ == limit_) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001408
1409 HeapObject* object = HeapObject::FromAddress(current_);
1410 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
1411
1412 current_ += size;
1413 return object;
1414 }
1415
1416 // Implementation of the ObjectIterator functions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001417 virtual HeapObject* next_object() { return next(); }
1418
1419 private:
1420 void Initialize(NewSpace* space, Address start, Address end,
1421 HeapObjectCallback size_func);
1422
1423 // The semispace.
1424 SemiSpace* space_;
1425 // The current iteration point.
1426 Address current_;
1427 // The end of iteration.
1428 Address limit_;
1429 // The callback function.
1430 HeapObjectCallback size_func_;
1431};
1432
1433
1434// -----------------------------------------------------------------------------
1435// The young generation space.
1436//
1437// The new space consists of a contiguous pair of semispaces. It simply
1438// forwards most functions to the appropriate semispace.
1439
1440class NewSpace : public Space {
1441 public:
1442 // Constructor.
1443 NewSpace() : Space(NEW_SPACE, NOT_EXECUTABLE) {}
1444
1445 // Sets up the new space using the given chunk.
1446 bool Setup(Address start, int size);
1447
1448 // Tears down the space. Heap memory was not allocated by the space, so it
1449 // is not deallocated here.
1450 void TearDown();
1451
1452 // True if the space has been set up but not torn down.
1453 bool HasBeenSetup() {
1454 return to_space_.HasBeenSetup() && from_space_.HasBeenSetup();
1455 }
1456
1457 // Flip the pair of spaces.
1458 void Flip();
1459
1460 // Grow the capacity of the semispaces. Assumes that they are not at
1461 // their maximum capacity.
1462 void Grow();
1463
1464 // Shrink the capacity of the semispaces.
1465 void Shrink();
1466
1467 // True if the address or object lies in the address range of either
1468 // semispace (not necessarily below the allocation pointer).
1469 bool Contains(Address a) {
1470 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1471 == reinterpret_cast<uintptr_t>(start_);
1472 }
1473 bool Contains(Object* o) {
1474 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1475 }
1476
1477 // Return the allocated bytes in the active semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001478 virtual intptr_t Size() { return static_cast<int>(top() - bottom()); }
1479 // The same, but returning an int. We have to have the one that returns
1480 // intptr_t because it is inherited, but if we know we are dealing with the
1481 // new space, which can't get as big as the other spaces then this is useful:
1482 int SizeAsInt() { return static_cast<int>(Size()); }
Steve Block3ce2e202009-11-05 08:53:23 +00001483
Steve Blocka7e24c12009-10-30 11:49:00 +00001484 // Return the current capacity of a semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001485 intptr_t Capacity() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001486 ASSERT(to_space_.Capacity() == from_space_.Capacity());
1487 return to_space_.Capacity();
1488 }
Steve Block3ce2e202009-11-05 08:53:23 +00001489
1490 // Return the total amount of memory committed for new space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001491 intptr_t CommittedMemory() {
Steve Block3ce2e202009-11-05 08:53:23 +00001492 if (from_space_.is_committed()) return 2 * Capacity();
1493 return Capacity();
1494 }
1495
Steve Blocka7e24c12009-10-30 11:49:00 +00001496 // Return the available bytes without growing in the active semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001497 intptr_t Available() { return Capacity() - Size(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001498
1499 // Return the maximum capacity of a semispace.
1500 int MaximumCapacity() {
1501 ASSERT(to_space_.MaximumCapacity() == from_space_.MaximumCapacity());
1502 return to_space_.MaximumCapacity();
1503 }
1504
1505 // Returns the initial capacity of a semispace.
1506 int InitialCapacity() {
1507 ASSERT(to_space_.InitialCapacity() == from_space_.InitialCapacity());
1508 return to_space_.InitialCapacity();
1509 }
1510
1511 // Return the address of the allocation pointer in the active semispace.
1512 Address top() { return allocation_info_.top; }
1513 // Return the address of the first object in the active semispace.
1514 Address bottom() { return to_space_.low(); }
1515
1516 // Get the age mark of the inactive semispace.
1517 Address age_mark() { return from_space_.age_mark(); }
1518 // Set the age mark in the active semispace.
1519 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
1520
1521 // The start address of the space and a bit mask. Anding an address in the
1522 // new space with the mask will result in the start address.
1523 Address start() { return start_; }
1524 uintptr_t mask() { return address_mask_; }
1525
1526 // The allocation top and limit addresses.
1527 Address* allocation_top_address() { return &allocation_info_.top; }
1528 Address* allocation_limit_address() { return &allocation_info_.limit; }
1529
1530 Object* AllocateRaw(int size_in_bytes) {
1531 return AllocateRawInternal(size_in_bytes, &allocation_info_);
1532 }
1533
1534 // Allocate the requested number of bytes for relocation during mark-compact
1535 // collection.
1536 Object* MCAllocateRaw(int size_in_bytes) {
1537 return AllocateRawInternal(size_in_bytes, &mc_forwarding_info_);
1538 }
1539
1540 // Reset the allocation pointer to the beginning of the active semispace.
1541 void ResetAllocationInfo();
1542 // Reset the reloction pointer to the bottom of the inactive semispace in
1543 // preparation for mark-compact collection.
1544 void MCResetRelocationInfo();
1545 // Update the allocation pointer in the active semispace after a
1546 // mark-compact collection.
1547 void MCCommitRelocationInfo();
1548
1549 // Get the extent of the inactive semispace (for use as a marking stack).
1550 Address FromSpaceLow() { return from_space_.low(); }
1551 Address FromSpaceHigh() { return from_space_.high(); }
1552
1553 // Get the extent of the active semispace (to sweep newly copied objects
1554 // during a scavenge collection).
1555 Address ToSpaceLow() { return to_space_.low(); }
1556 Address ToSpaceHigh() { return to_space_.high(); }
1557
1558 // Offsets from the beginning of the semispaces.
1559 int ToSpaceOffsetForAddress(Address a) {
1560 return to_space_.SpaceOffsetForAddress(a);
1561 }
1562 int FromSpaceOffsetForAddress(Address a) {
1563 return from_space_.SpaceOffsetForAddress(a);
1564 }
1565
1566 // True if the object is a heap object in the address range of the
1567 // respective semispace (not necessarily below the allocation pointer of the
1568 // semispace).
1569 bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
1570 bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
1571
1572 bool ToSpaceContains(Address a) { return to_space_.Contains(a); }
1573 bool FromSpaceContains(Address a) { return from_space_.Contains(a); }
1574
Leon Clarkee46be812010-01-19 14:06:41 +00001575 virtual bool ReserveSpace(int bytes);
1576
Steve Blocka7e24c12009-10-30 11:49:00 +00001577#ifdef ENABLE_HEAP_PROTECTION
1578 // Protect/unprotect the space by marking it read-only/writable.
1579 virtual void Protect();
1580 virtual void Unprotect();
1581#endif
1582
1583#ifdef DEBUG
1584 // Verify the active semispace.
1585 virtual void Verify();
1586 // Print the active semispace.
1587 virtual void Print() { to_space_.Print(); }
1588#endif
1589
1590#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1591 // Iterates the active semispace to collect statistics.
1592 void CollectStatistics();
1593 // Reports previously collected statistics of the active semispace.
1594 void ReportStatistics();
1595 // Clears previously collected statistics.
1596 void ClearHistograms();
1597
1598 // Record the allocation or promotion of a heap object. Note that we don't
1599 // record every single allocation, but only those that happen in the
1600 // to space during a scavenge GC.
1601 void RecordAllocation(HeapObject* obj);
1602 void RecordPromotion(HeapObject* obj);
1603#endif
1604
1605 // Return whether the operation succeded.
1606 bool CommitFromSpaceIfNeeded() {
1607 if (from_space_.is_committed()) return true;
1608 return from_space_.Commit();
1609 }
1610
1611 bool UncommitFromSpace() {
1612 if (!from_space_.is_committed()) return true;
1613 return from_space_.Uncommit();
1614 }
1615
1616 private:
1617 // The semispaces.
1618 SemiSpace to_space_;
1619 SemiSpace from_space_;
1620
1621 // Start address and bit mask for containment testing.
1622 Address start_;
1623 uintptr_t address_mask_;
1624 uintptr_t object_mask_;
1625 uintptr_t object_expected_;
1626
1627 // Allocation pointer and limit for normal allocation and allocation during
1628 // mark-compact collection.
1629 AllocationInfo allocation_info_;
1630 AllocationInfo mc_forwarding_info_;
1631
1632#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1633 HistogramInfo* allocated_histogram_;
1634 HistogramInfo* promoted_histogram_;
1635#endif
1636
1637 // Implementation of AllocateRaw and MCAllocateRaw.
1638 inline Object* AllocateRawInternal(int size_in_bytes,
1639 AllocationInfo* alloc_info);
1640
1641 friend class SemiSpaceIterator;
1642
1643 public:
1644 TRACK_MEMORY("NewSpace")
1645};
1646
1647
1648// -----------------------------------------------------------------------------
1649// Free lists for old object spaces
1650//
1651// Free-list nodes are free blocks in the heap. They look like heap objects
1652// (free-list node pointers have the heap object tag, and they have a map like
1653// a heap object). They have a size and a next pointer. The next pointer is
1654// the raw address of the next free list node (or NULL).
1655class FreeListNode: public HeapObject {
1656 public:
1657 // Obtain a free-list node from a raw address. This is not a cast because
1658 // it does not check nor require that the first word at the address is a map
1659 // pointer.
1660 static FreeListNode* FromAddress(Address address) {
1661 return reinterpret_cast<FreeListNode*>(HeapObject::FromAddress(address));
1662 }
1663
Steve Block3ce2e202009-11-05 08:53:23 +00001664 static inline bool IsFreeListNode(HeapObject* object);
1665
Steve Blocka7e24c12009-10-30 11:49:00 +00001666 // Set the size in bytes, which can be read with HeapObject::Size(). This
1667 // function also writes a map to the first word of the block so that it
1668 // looks like a heap object to the garbage collector and heap iteration
1669 // functions.
1670 void set_size(int size_in_bytes);
1671
1672 // Accessors for the next field.
1673 inline Address next();
1674 inline void set_next(Address next);
1675
1676 private:
1677 static const int kNextOffset = POINTER_SIZE_ALIGN(ByteArray::kHeaderSize);
1678
1679 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeListNode);
1680};
1681
1682
1683// The free list for the old space.
1684class OldSpaceFreeList BASE_EMBEDDED {
1685 public:
1686 explicit OldSpaceFreeList(AllocationSpace owner);
1687
1688 // Clear the free list.
1689 void Reset();
1690
1691 // Return the number of bytes available on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001692 intptr_t available() { return available_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001693
1694 // Place a node on the free list. The block of size 'size_in_bytes'
1695 // starting at 'start' is placed on the free list. The return value is the
1696 // number of bytes that have been lost due to internal fragmentation by
1697 // freeing the block. Bookkeeping information will be written to the block,
1698 // ie, its contents will be destroyed. The start address should be word
1699 // aligned, and the size should be a non-zero multiple of the word size.
1700 int Free(Address start, int size_in_bytes);
1701
1702 // Allocate a block of size 'size_in_bytes' from the free list. The block
1703 // is unitialized. A failure is returned if no block is available. The
1704 // number of bytes lost to fragmentation is returned in the output parameter
1705 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
1706 Object* Allocate(int size_in_bytes, int* wasted_bytes);
1707
1708 private:
1709 // The size range of blocks, in bytes. (Smaller allocations are allowed, but
1710 // will always result in waste.)
1711 static const int kMinBlockSize = 2 * kPointerSize;
1712 static const int kMaxBlockSize = Page::kMaxHeapObjectSize;
1713
1714 // The identity of the owning space, for building allocation Failure
1715 // objects.
1716 AllocationSpace owner_;
1717
1718 // Total available bytes in all blocks on this free list.
1719 int available_;
1720
1721 // Blocks are put on exact free lists in an array, indexed by size in words.
1722 // The available sizes are kept in an increasingly ordered list. Entries
1723 // corresponding to sizes < kMinBlockSize always have an empty free list
1724 // (but index kHead is used for the head of the size list).
1725 struct SizeNode {
1726 // Address of the head FreeListNode of the implied block size or NULL.
1727 Address head_node_;
1728 // Size (words) of the next larger available size if head_node_ != NULL.
1729 int next_size_;
1730 };
1731 static const int kFreeListsLength = kMaxBlockSize / kPointerSize + 1;
1732 SizeNode free_[kFreeListsLength];
1733
1734 // Sentinel elements for the size list. Real elements are in ]kHead..kEnd[.
1735 static const int kHead = kMinBlockSize / kPointerSize - 1;
1736 static const int kEnd = kMaxInt;
1737
1738 // We keep a "finger" in the size list to speed up a common pattern:
1739 // repeated requests for the same or increasing sizes.
1740 int finger_;
1741
1742 // Starting from *prev, find and return the smallest size >= index (words),
1743 // or kEnd. Update *prev to be the largest size < index, or kHead.
1744 int FindSize(int index, int* prev) {
1745 int cur = free_[*prev].next_size_;
1746 while (cur < index) {
1747 *prev = cur;
1748 cur = free_[cur].next_size_;
1749 }
1750 return cur;
1751 }
1752
1753 // Remove an existing element from the size list.
1754 void RemoveSize(int index) {
1755 int prev = kHead;
1756 int cur = FindSize(index, &prev);
1757 ASSERT(cur == index);
1758 free_[prev].next_size_ = free_[cur].next_size_;
1759 finger_ = prev;
1760 }
1761
1762 // Insert a new element into the size list.
1763 void InsertSize(int index) {
1764 int prev = kHead;
1765 int cur = FindSize(index, &prev);
1766 ASSERT(cur != index);
1767 free_[prev].next_size_ = index;
1768 free_[index].next_size_ = cur;
1769 }
1770
1771 // The size list is not updated during a sequence of calls to Free, but is
1772 // rebuilt before the next allocation.
1773 void RebuildSizeList();
1774 bool needs_rebuild_;
1775
1776#ifdef DEBUG
1777 // Does this free list contain a free block located at the address of 'node'?
1778 bool Contains(FreeListNode* node);
1779#endif
1780
1781 DISALLOW_COPY_AND_ASSIGN(OldSpaceFreeList);
1782};
1783
1784
1785// The free list for the map space.
1786class FixedSizeFreeList BASE_EMBEDDED {
1787 public:
1788 FixedSizeFreeList(AllocationSpace owner, int object_size);
1789
1790 // Clear the free list.
1791 void Reset();
1792
1793 // Return the number of bytes available on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001794 intptr_t available() { return available_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001795
1796 // Place a node on the free list. The block starting at 'start' (assumed to
1797 // have size object_size_) is placed on the free list. Bookkeeping
1798 // information will be written to the block, ie, its contents will be
1799 // destroyed. The start address should be word aligned.
1800 void Free(Address start);
1801
1802 // Allocate a fixed sized block from the free list. The block is unitialized.
1803 // A failure is returned if no block is available.
1804 Object* Allocate();
1805
1806 private:
1807 // Available bytes on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001808 intptr_t available_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001809
1810 // The head of the free list.
1811 Address head_;
1812
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001813 // The tail of the free list.
1814 Address tail_;
1815
Steve Blocka7e24c12009-10-30 11:49:00 +00001816 // The identity of the owning space, for building allocation Failure
1817 // objects.
1818 AllocationSpace owner_;
1819
1820 // The size of the objects in this space.
1821 int object_size_;
1822
1823 DISALLOW_COPY_AND_ASSIGN(FixedSizeFreeList);
1824};
1825
1826
1827// -----------------------------------------------------------------------------
1828// Old object space (excluding map objects)
1829
1830class OldSpace : public PagedSpace {
1831 public:
1832 // Creates an old space object with a given maximum capacity.
1833 // The constructor does not allocate pages from OS.
Ben Murdochf87a2032010-10-22 12:50:53 +01001834 explicit OldSpace(intptr_t max_capacity,
Steve Blocka7e24c12009-10-30 11:49:00 +00001835 AllocationSpace id,
1836 Executability executable)
1837 : PagedSpace(max_capacity, id, executable), free_list_(id) {
1838 page_extra_ = 0;
1839 }
1840
1841 // The bytes available on the free list (ie, not above the linear allocation
1842 // pointer).
Ben Murdochf87a2032010-10-22 12:50:53 +01001843 intptr_t AvailableFree() { return free_list_.available(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001844
Steve Block6ded16b2010-05-10 14:33:55 +01001845 // The limit of allocation for a page in this space.
1846 virtual Address PageAllocationLimit(Page* page) {
1847 return page->ObjectAreaEnd();
Steve Blocka7e24c12009-10-30 11:49:00 +00001848 }
1849
1850 // Give a block of memory to the space's free list. It might be added to
1851 // the free list or accounted as waste.
Steve Block6ded16b2010-05-10 14:33:55 +01001852 // If add_to_freelist is false then just accounting stats are updated and
1853 // no attempt to add area to free list is made.
1854 void Free(Address start, int size_in_bytes, bool add_to_freelist) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001855 accounting_stats_.DeallocateBytes(size_in_bytes);
Steve Block6ded16b2010-05-10 14:33:55 +01001856
1857 if (add_to_freelist) {
1858 int wasted_bytes = free_list_.Free(start, size_in_bytes);
1859 accounting_stats_.WasteBytes(wasted_bytes);
1860 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001861 }
1862
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001863 virtual void DeallocateBlock(Address start,
1864 int size_in_bytes,
1865 bool add_to_freelist);
1866
Steve Blocka7e24c12009-10-30 11:49:00 +00001867 // Prepare for full garbage collection. Resets the relocation pointer and
1868 // clears the free list.
1869 virtual void PrepareForMarkCompact(bool will_compact);
1870
1871 // Updates the allocation pointer to the relocation top after a mark-compact
1872 // collection.
1873 virtual void MCCommitRelocationInfo();
1874
Leon Clarkee46be812010-01-19 14:06:41 +00001875 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1876
Steve Blocka7e24c12009-10-30 11:49:00 +00001877#ifdef DEBUG
1878 // Reports statistics for the space
1879 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001880#endif
1881
1882 protected:
1883 // Virtual function in the superclass. Slow path of AllocateRaw.
1884 HeapObject* SlowAllocateRaw(int size_in_bytes);
1885
1886 // Virtual function in the superclass. Allocate linearly at the start of
1887 // the page after current_page (there is assumed to be one).
1888 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1889
1890 private:
1891 // The space's free list.
1892 OldSpaceFreeList free_list_;
1893
1894 public:
1895 TRACK_MEMORY("OldSpace")
1896};
1897
1898
1899// -----------------------------------------------------------------------------
1900// Old space for objects of a fixed size
1901
1902class FixedSpace : public PagedSpace {
1903 public:
Ben Murdochf87a2032010-10-22 12:50:53 +01001904 FixedSpace(intptr_t max_capacity,
Steve Blocka7e24c12009-10-30 11:49:00 +00001905 AllocationSpace id,
1906 int object_size_in_bytes,
1907 const char* name)
1908 : PagedSpace(max_capacity, id, NOT_EXECUTABLE),
1909 object_size_in_bytes_(object_size_in_bytes),
1910 name_(name),
1911 free_list_(id, object_size_in_bytes) {
1912 page_extra_ = Page::kObjectAreaSize % object_size_in_bytes;
1913 }
1914
Steve Block6ded16b2010-05-10 14:33:55 +01001915 // The limit of allocation for a page in this space.
1916 virtual Address PageAllocationLimit(Page* page) {
1917 return page->ObjectAreaEnd() - page_extra_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001918 }
1919
1920 int object_size_in_bytes() { return object_size_in_bytes_; }
1921
1922 // Give a fixed sized block of memory to the space's free list.
Steve Block6ded16b2010-05-10 14:33:55 +01001923 // If add_to_freelist is false then just accounting stats are updated and
1924 // no attempt to add area to free list is made.
1925 void Free(Address start, bool add_to_freelist) {
1926 if (add_to_freelist) {
1927 free_list_.Free(start);
1928 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001929 accounting_stats_.DeallocateBytes(object_size_in_bytes_);
1930 }
1931
1932 // Prepares for a mark-compact GC.
1933 virtual void PrepareForMarkCompact(bool will_compact);
1934
1935 // Updates the allocation pointer to the relocation top after a mark-compact
1936 // collection.
1937 virtual void MCCommitRelocationInfo();
1938
Leon Clarkee46be812010-01-19 14:06:41 +00001939 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1940
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001941 virtual void DeallocateBlock(Address start,
1942 int size_in_bytes,
1943 bool add_to_freelist);
Steve Blocka7e24c12009-10-30 11:49:00 +00001944#ifdef DEBUG
1945 // Reports statistic info of the space
1946 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001947#endif
1948
1949 protected:
1950 // Virtual function in the superclass. Slow path of AllocateRaw.
1951 HeapObject* SlowAllocateRaw(int size_in_bytes);
1952
1953 // Virtual function in the superclass. Allocate linearly at the start of
1954 // the page after current_page (there is assumed to be one).
1955 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1956
Leon Clarkee46be812010-01-19 14:06:41 +00001957 void ResetFreeList() {
1958 free_list_.Reset();
1959 }
1960
Steve Blocka7e24c12009-10-30 11:49:00 +00001961 private:
1962 // The size of objects in this space.
1963 int object_size_in_bytes_;
1964
1965 // The name of this space.
1966 const char* name_;
1967
1968 // The space's free list.
1969 FixedSizeFreeList free_list_;
1970};
1971
1972
1973// -----------------------------------------------------------------------------
1974// Old space for all map objects
1975
1976class MapSpace : public FixedSpace {
1977 public:
1978 // Creates a map space object with a maximum capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01001979 MapSpace(intptr_t max_capacity, int max_map_space_pages, AllocationSpace id)
Leon Clarked91b9f72010-01-27 17:25:45 +00001980 : FixedSpace(max_capacity, id, Map::kSize, "map"),
1981 max_map_space_pages_(max_map_space_pages) {
1982 ASSERT(max_map_space_pages < kMaxMapPageIndex);
1983 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001984
1985 // Prepares for a mark-compact GC.
1986 virtual void PrepareForMarkCompact(bool will_compact);
1987
1988 // Given an index, returns the page address.
1989 Address PageAddress(int page_index) { return page_addresses_[page_index]; }
1990
Leon Clarked91b9f72010-01-27 17:25:45 +00001991 static const int kMaxMapPageIndex = 1 << MapWord::kMapPageIndexBits;
Steve Blocka7e24c12009-10-30 11:49:00 +00001992
Leon Clarkee46be812010-01-19 14:06:41 +00001993 // Are map pointers encodable into map word?
1994 bool MapPointersEncodable() {
1995 if (!FLAG_use_big_map_space) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001996 ASSERT(CountPagesToTop() <= kMaxMapPageIndex);
Leon Clarkee46be812010-01-19 14:06:41 +00001997 return true;
1998 }
Leon Clarked91b9f72010-01-27 17:25:45 +00001999 return CountPagesToTop() <= max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002000 }
2001
2002 // Should be called after forced sweep to find out if map space needs
2003 // compaction.
2004 bool NeedsCompaction(int live_maps) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002005 return !MapPointersEncodable() && live_maps <= CompactionThreshold();
Leon Clarkee46be812010-01-19 14:06:41 +00002006 }
2007
2008 Address TopAfterCompaction(int live_maps) {
2009 ASSERT(NeedsCompaction(live_maps));
2010
2011 int pages_left = live_maps / kMapsPerPage;
2012 PageIterator it(this, PageIterator::ALL_PAGES);
2013 while (pages_left-- > 0) {
2014 ASSERT(it.has_next());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002015 it.next()->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00002016 }
2017 ASSERT(it.has_next());
2018 Page* top_page = it.next();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002019 top_page->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00002020 ASSERT(top_page->is_valid());
2021
2022 int offset = live_maps % kMapsPerPage * Map::kSize;
2023 Address top = top_page->ObjectAreaStart() + offset;
2024 ASSERT(top < top_page->ObjectAreaEnd());
2025 ASSERT(Contains(top));
2026
2027 return top;
2028 }
2029
2030 void FinishCompaction(Address new_top, int live_maps) {
2031 Page* top_page = Page::FromAddress(new_top);
2032 ASSERT(top_page->is_valid());
2033
2034 SetAllocationInfo(&allocation_info_, top_page);
2035 allocation_info_.top = new_top;
2036
2037 int new_size = live_maps * Map::kSize;
2038 accounting_stats_.DeallocateBytes(accounting_stats_.Size());
2039 accounting_stats_.AllocateBytes(new_size);
2040
2041#ifdef DEBUG
2042 if (FLAG_enable_slow_asserts) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002043 intptr_t actual_size = 0;
Leon Clarkee46be812010-01-19 14:06:41 +00002044 for (Page* p = first_page_; p != top_page; p = p->next_page())
2045 actual_size += kMapsPerPage * Map::kSize;
2046 actual_size += (new_top - top_page->ObjectAreaStart());
2047 ASSERT(accounting_stats_.Size() == actual_size);
2048 }
2049#endif
2050
2051 Shrink();
2052 ResetFreeList();
2053 }
2054
Steve Blocka7e24c12009-10-30 11:49:00 +00002055 protected:
2056#ifdef DEBUG
2057 virtual void VerifyObject(HeapObject* obj);
2058#endif
2059
2060 private:
Leon Clarkee46be812010-01-19 14:06:41 +00002061 static const int kMapsPerPage = Page::kObjectAreaSize / Map::kSize;
2062
2063 // Do map space compaction if there is a page gap.
Leon Clarked91b9f72010-01-27 17:25:45 +00002064 int CompactionThreshold() {
2065 return kMapsPerPage * (max_map_space_pages_ - 1);
2066 }
2067
2068 const int max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002069
Steve Blocka7e24c12009-10-30 11:49:00 +00002070 // An array of page start address in a map space.
Leon Clarked91b9f72010-01-27 17:25:45 +00002071 Address page_addresses_[kMaxMapPageIndex];
Steve Blocka7e24c12009-10-30 11:49:00 +00002072
2073 public:
2074 TRACK_MEMORY("MapSpace")
2075};
2076
2077
2078// -----------------------------------------------------------------------------
2079// Old space for all global object property cell objects
2080
2081class CellSpace : public FixedSpace {
2082 public:
2083 // Creates a property cell space object with a maximum capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01002084 CellSpace(intptr_t max_capacity, AllocationSpace id)
Steve Blocka7e24c12009-10-30 11:49:00 +00002085 : FixedSpace(max_capacity, id, JSGlobalPropertyCell::kSize, "cell") {}
2086
2087 protected:
2088#ifdef DEBUG
2089 virtual void VerifyObject(HeapObject* obj);
2090#endif
2091
2092 public:
2093 TRACK_MEMORY("CellSpace")
2094};
2095
2096
2097// -----------------------------------------------------------------------------
2098// Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2099// the large object space. A large object is allocated from OS heap with
2100// extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2101// A large object always starts at Page::kObjectStartOffset to a page.
2102// Large objects do not move during garbage collections.
2103
2104// A LargeObjectChunk holds exactly one large object page with exactly one
2105// large object.
2106class LargeObjectChunk {
2107 public:
2108 // Allocates a new LargeObjectChunk that contains a large object page
2109 // (Page::kPageSize aligned) that has at least size_in_bytes (for a large
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002110 // object) bytes after the object area start of that page.
2111 // The allocated chunk size is set in the output parameter chunk_size.
Steve Blocka7e24c12009-10-30 11:49:00 +00002112 static LargeObjectChunk* New(int size_in_bytes,
2113 size_t* chunk_size,
2114 Executability executable);
2115
2116 // Interpret a raw address as a large object chunk.
2117 static LargeObjectChunk* FromAddress(Address address) {
2118 return reinterpret_cast<LargeObjectChunk*>(address);
2119 }
2120
2121 // Returns the address of this chunk.
2122 Address address() { return reinterpret_cast<Address>(this); }
2123
2124 // Accessors for the fields of the chunk.
2125 LargeObjectChunk* next() { return next_; }
2126 void set_next(LargeObjectChunk* chunk) { next_ = chunk; }
2127
Steve Block791712a2010-08-27 10:21:07 +01002128 size_t size() { return size_ & ~Page::kPageFlagMask; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002129 void set_size(size_t size_in_bytes) { size_ = size_in_bytes; }
2130
2131 // Returns the object in this chunk.
2132 inline HeapObject* GetObject();
2133
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002134 // Given a requested size returns the physical size of a chunk to be
2135 // allocated.
Steve Blocka7e24c12009-10-30 11:49:00 +00002136 static int ChunkSizeFor(int size_in_bytes);
2137
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002138 // Given a chunk size, returns the object size it can accommodate. Used by
2139 // LargeObjectSpace::Available.
Ben Murdochf87a2032010-10-22 12:50:53 +01002140 static intptr_t ObjectSizeFor(intptr_t chunk_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002141 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2142 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2143 }
2144
2145 private:
2146 // A pointer to the next large object chunk in the space or NULL.
2147 LargeObjectChunk* next_;
2148
2149 // The size of this chunk.
2150 size_t size_;
2151
2152 public:
2153 TRACK_MEMORY("LargeObjectChunk")
2154};
2155
2156
2157class LargeObjectSpace : public Space {
2158 public:
2159 explicit LargeObjectSpace(AllocationSpace id);
2160 virtual ~LargeObjectSpace() {}
2161
2162 // Initializes internal data structures.
2163 bool Setup();
2164
2165 // Releases internal resources, frees objects in this space.
2166 void TearDown();
2167
2168 // Allocates a (non-FixedArray, non-Code) large object.
2169 Object* AllocateRaw(int size_in_bytes);
2170 // Allocates a large Code object.
2171 Object* AllocateRawCode(int size_in_bytes);
2172 // Allocates a large FixedArray.
2173 Object* AllocateRawFixedArray(int size_in_bytes);
2174
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002175 // Available bytes for objects in this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01002176 intptr_t Available() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002177 return LargeObjectChunk::ObjectSizeFor(MemoryAllocator::Available());
2178 }
2179
Ben Murdochf87a2032010-10-22 12:50:53 +01002180 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002181 return size_;
2182 }
2183
2184 int PageCount() {
2185 return page_count_;
2186 }
2187
2188 // Finds an object for a given address, returns Failure::Exception()
2189 // if it is not found. The function iterates through all objects in this
2190 // space, may be slow.
2191 Object* FindObject(Address a);
2192
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002193 // Finds a large object page containing the given pc, returns NULL
2194 // if such a page doesn't exist.
2195 LargeObjectChunk* FindChunkContainingPc(Address pc);
2196
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002197 // Iterates objects covered by dirty regions.
2198 void IterateDirtyRegions(ObjectSlotCallback func);
Steve Blocka7e24c12009-10-30 11:49:00 +00002199
2200 // Frees unmarked objects.
2201 void FreeUnmarkedObjects();
2202
2203 // Checks whether a heap object is in this space; O(1).
2204 bool Contains(HeapObject* obj);
2205
2206 // Checks whether the space is empty.
2207 bool IsEmpty() { return first_chunk_ == NULL; }
2208
Leon Clarkee46be812010-01-19 14:06:41 +00002209 // See the comments for ReserveSpace in the Space class. This has to be
2210 // called after ReserveSpace has been called on the paged spaces, since they
2211 // may use some memory, leaving less for large objects.
2212 virtual bool ReserveSpace(int bytes);
2213
Steve Blocka7e24c12009-10-30 11:49:00 +00002214#ifdef ENABLE_HEAP_PROTECTION
2215 // Protect/unprotect the space by marking it read-only/writable.
2216 void Protect();
2217 void Unprotect();
2218#endif
2219
2220#ifdef DEBUG
2221 virtual void Verify();
2222 virtual void Print();
2223 void ReportStatistics();
2224 void CollectCodeStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00002225#endif
2226 // Checks whether an address is in the object area in this space. It
2227 // iterates all objects in the space. May be slow.
2228 bool SlowContains(Address addr) { return !FindObject(addr)->IsFailure(); }
2229
2230 private:
2231 // The head of the linked list of large object chunks.
2232 LargeObjectChunk* first_chunk_;
Ben Murdochf87a2032010-10-22 12:50:53 +01002233 intptr_t size_; // allocated bytes
Steve Blocka7e24c12009-10-30 11:49:00 +00002234 int page_count_; // number of chunks
2235
2236
2237 // Shared implementation of AllocateRaw, AllocateRawCode and
2238 // AllocateRawFixedArray.
2239 Object* AllocateRawInternal(int requested_size,
2240 int object_size,
2241 Executability executable);
2242
Steve Blocka7e24c12009-10-30 11:49:00 +00002243 friend class LargeObjectIterator;
2244
2245 public:
2246 TRACK_MEMORY("LargeObjectSpace")
2247};
2248
2249
2250class LargeObjectIterator: public ObjectIterator {
2251 public:
2252 explicit LargeObjectIterator(LargeObjectSpace* space);
2253 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2254
Steve Blocka7e24c12009-10-30 11:49:00 +00002255 HeapObject* next();
2256
2257 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +00002258 virtual HeapObject* next_object() { return next(); }
2259
2260 private:
2261 LargeObjectChunk* current_;
2262 HeapObjectCallback size_func_;
2263};
2264
2265
2266} } // namespace v8::internal
2267
2268#endif // V8_SPACES_H_