blob: b37fe4b5b8154f18155783f862995928c19b517b [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_HEAP_H_
29#define V8_HEAP_H_
30
31#include <math.h>
32
33#include "zone-inl.h"
34
35
36namespace v8 {
37namespace internal {
38
39// Defines all the roots in Heap.
40#define UNCONDITIONAL_STRONG_ROOT_LIST(V) \
Steve Blockd0582a62009-12-15 09:54:21 +000041 /* Put the byte array map early. We need it to be in place by the time */ \
42 /* the deserializer hits the next page, since it wants to put a byte */ \
43 /* array in the unused space at the end of the page. */ \
44 V(Map, byte_array_map, ByteArrayMap) \
45 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
46 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
47 /* Cluster the most popular ones in a few cache lines here at the top. */ \
Steve Blocka7e24c12009-10-30 11:49:00 +000048 V(Smi, stack_limit, StackLimit) \
49 V(Object, undefined_value, UndefinedValue) \
50 V(Object, the_hole_value, TheHoleValue) \
51 V(Object, null_value, NullValue) \
52 V(Object, true_value, TrueValue) \
53 V(Object, false_value, FalseValue) \
54 V(Map, heap_number_map, HeapNumberMap) \
55 V(Map, global_context_map, GlobalContextMap) \
56 V(Map, fixed_array_map, FixedArrayMap) \
57 V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
58 V(Map, meta_map, MetaMap) \
59 V(Object, termination_exception, TerminationException) \
60 V(Map, hash_table_map, HashTableMap) \
61 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
Steve Blockd0582a62009-12-15 09:54:21 +000062 V(Map, string_map, StringMap) \
63 V(Map, ascii_string_map, AsciiStringMap) \
64 V(Map, symbol_map, SymbolMap) \
65 V(Map, ascii_symbol_map, AsciiSymbolMap) \
66 V(Map, cons_symbol_map, ConsSymbolMap) \
67 V(Map, cons_ascii_symbol_map, ConsAsciiSymbolMap) \
68 V(Map, external_symbol_map, ExternalSymbolMap) \
69 V(Map, external_ascii_symbol_map, ExternalAsciiSymbolMap) \
70 V(Map, cons_string_map, ConsStringMap) \
71 V(Map, cons_ascii_string_map, ConsAsciiStringMap) \
72 V(Map, external_string_map, ExternalStringMap) \
73 V(Map, external_ascii_string_map, ExternalAsciiStringMap) \
74 V(Map, undetectable_string_map, UndetectableStringMap) \
75 V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000076 V(Map, pixel_array_map, PixelArrayMap) \
Steve Block3ce2e202009-11-05 08:53:23 +000077 V(Map, external_byte_array_map, ExternalByteArrayMap) \
78 V(Map, external_unsigned_byte_array_map, ExternalUnsignedByteArrayMap) \
79 V(Map, external_short_array_map, ExternalShortArrayMap) \
80 V(Map, external_unsigned_short_array_map, ExternalUnsignedShortArrayMap) \
81 V(Map, external_int_array_map, ExternalIntArrayMap) \
82 V(Map, external_unsigned_int_array_map, ExternalUnsignedIntArrayMap) \
83 V(Map, external_float_array_map, ExternalFloatArrayMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000084 V(Map, context_map, ContextMap) \
85 V(Map, catch_context_map, CatchContextMap) \
86 V(Map, code_map, CodeMap) \
87 V(Map, oddball_map, OddballMap) \
88 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
89 V(Map, boilerplate_function_map, BoilerplateFunctionMap) \
90 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
91 V(Map, proxy_map, ProxyMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000092 V(Object, nan_value, NanValue) \
93 V(Object, minus_zero_value, MinusZeroValue) \
94 V(String, empty_string, EmptyString) \
95 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
96 V(Map, neander_map, NeanderMap) \
97 V(JSObject, message_listeners, MessageListeners) \
98 V(Proxy, prototype_accessors, PrototypeAccessors) \
99 V(NumberDictionary, code_stubs, CodeStubs) \
100 V(NumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
101 V(Code, js_entry_code, JsEntryCode) \
102 V(Code, js_construct_entry_code, JsConstructEntryCode) \
103 V(Code, c_entry_code, CEntryCode) \
104 V(Code, c_entry_debug_break_code, CEntryDebugBreakCode) \
105 V(FixedArray, number_string_cache, NumberStringCache) \
106 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
107 V(FixedArray, natives_source_cache, NativesSourceCache) \
108 V(Object, last_script_id, LastScriptId) \
Steve Blockd0582a62009-12-15 09:54:21 +0000109 V(Smi, real_stack_limit, RealStackLimit) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000110
111#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
112#define STRONG_ROOT_LIST(V) \
113 UNCONDITIONAL_STRONG_ROOT_LIST(V) \
114 V(Code, re_c_entry_code, RegExpCEntryCode)
115#else
116#define STRONG_ROOT_LIST(V) UNCONDITIONAL_STRONG_ROOT_LIST(V)
117#endif
118
119#define ROOT_LIST(V) \
120 STRONG_ROOT_LIST(V) \
121 V(SymbolTable, symbol_table, SymbolTable)
122
123#define SYMBOL_LIST(V) \
124 V(Array_symbol, "Array") \
125 V(Object_symbol, "Object") \
126 V(Proto_symbol, "__proto__") \
127 V(StringImpl_symbol, "StringImpl") \
128 V(arguments_symbol, "arguments") \
129 V(Arguments_symbol, "Arguments") \
130 V(arguments_shadow_symbol, ".arguments") \
131 V(call_symbol, "call") \
132 V(apply_symbol, "apply") \
133 V(caller_symbol, "caller") \
134 V(boolean_symbol, "boolean") \
135 V(Boolean_symbol, "Boolean") \
136 V(callee_symbol, "callee") \
137 V(constructor_symbol, "constructor") \
138 V(code_symbol, ".code") \
139 V(result_symbol, ".result") \
140 V(catch_var_symbol, ".catch-var") \
141 V(empty_symbol, "") \
142 V(eval_symbol, "eval") \
143 V(function_symbol, "function") \
144 V(length_symbol, "length") \
145 V(name_symbol, "name") \
146 V(number_symbol, "number") \
147 V(Number_symbol, "Number") \
148 V(RegExp_symbol, "RegExp") \
149 V(object_symbol, "object") \
150 V(prototype_symbol, "prototype") \
151 V(string_symbol, "string") \
152 V(String_symbol, "String") \
153 V(Date_symbol, "Date") \
154 V(this_symbol, "this") \
155 V(to_string_symbol, "toString") \
156 V(char_at_symbol, "CharAt") \
157 V(undefined_symbol, "undefined") \
158 V(value_of_symbol, "valueOf") \
159 V(InitializeVarGlobal_symbol, "InitializeVarGlobal") \
160 V(InitializeConstGlobal_symbol, "InitializeConstGlobal") \
161 V(stack_overflow_symbol, "kStackOverflowBoilerplate") \
162 V(illegal_access_symbol, "illegal access") \
163 V(out_of_memory_symbol, "out-of-memory") \
164 V(illegal_execution_state_symbol, "illegal execution state") \
165 V(get_symbol, "get") \
166 V(set_symbol, "set") \
167 V(function_class_symbol, "Function") \
168 V(illegal_argument_symbol, "illegal argument") \
169 V(MakeReferenceError_symbol, "MakeReferenceError") \
170 V(MakeSyntaxError_symbol, "MakeSyntaxError") \
171 V(MakeTypeError_symbol, "MakeTypeError") \
172 V(invalid_lhs_in_assignment_symbol, "invalid_lhs_in_assignment") \
173 V(invalid_lhs_in_for_in_symbol, "invalid_lhs_in_for_in") \
174 V(invalid_lhs_in_postfix_op_symbol, "invalid_lhs_in_postfix_op") \
175 V(invalid_lhs_in_prefix_op_symbol, "invalid_lhs_in_prefix_op") \
176 V(illegal_return_symbol, "illegal_return") \
177 V(illegal_break_symbol, "illegal_break") \
178 V(illegal_continue_symbol, "illegal_continue") \
179 V(unknown_label_symbol, "unknown_label") \
180 V(redeclaration_symbol, "redeclaration") \
181 V(failure_symbol, "<failure>") \
182 V(space_symbol, " ") \
183 V(exec_symbol, "exec") \
184 V(zero_symbol, "0") \
185 V(global_eval_symbol, "GlobalEval") \
Steve Blockd0582a62009-12-15 09:54:21 +0000186 V(identity_hash_symbol, "v8::IdentityHash") \
187 V(closure_symbol, "(closure)")
Steve Blocka7e24c12009-10-30 11:49:00 +0000188
189
190// Forward declaration of the GCTracer class.
191class GCTracer;
Steve Blockd0582a62009-12-15 09:54:21 +0000192class HeapStats;
Steve Blocka7e24c12009-10-30 11:49:00 +0000193
194
195// The all static Heap captures the interface to the global object heap.
196// All JavaScript contexts by this process share the same object heap.
197
198class Heap : public AllStatic {
199 public:
200 // Configure heap size before setup. Return false if the heap has been
201 // setup already.
Steve Block3ce2e202009-11-05 08:53:23 +0000202 static bool ConfigureHeap(int max_semispace_size, int max_old_gen_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000203 static bool ConfigureHeapDefault();
204
205 // Initializes the global object heap. If create_heap_objects is true,
206 // also creates the basic non-mutable objects.
207 // Returns whether it succeeded.
208 static bool Setup(bool create_heap_objects);
209
210 // Destroys all memory allocated by the heap.
211 static void TearDown();
212
Steve Blockd0582a62009-12-15 09:54:21 +0000213 // Set the stack limit in the roots_ array. Some architectures generate
214 // code that looks here, because it is faster than loading from the static
215 // jslimit_/real_jslimit_ variable in the StackGuard.
216 static void SetStackLimits();
Steve Blocka7e24c12009-10-30 11:49:00 +0000217
218 // Returns whether Setup has been called.
219 static bool HasBeenSetup();
220
Steve Block3ce2e202009-11-05 08:53:23 +0000221 // Returns the maximum amount of memory reserved for the heap. For
222 // the young generation, we reserve 4 times the amount needed for a
223 // semi space. The young generation consists of two semi spaces and
224 // we reserve twice the amount needed for those in order to ensure
225 // that new space can be aligned to its size.
226 static int MaxReserved() {
227 return 4 * reserved_semispace_size_ + max_old_generation_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000228 }
Steve Block3ce2e202009-11-05 08:53:23 +0000229 static int MaxSemiSpaceSize() { return max_semispace_size_; }
230 static int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000231 static int InitialSemiSpaceSize() { return initial_semispace_size_; }
Steve Block3ce2e202009-11-05 08:53:23 +0000232 static int MaxOldGenerationSize() { return max_old_generation_size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000233
234 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
235 // more spaces are needed until it reaches the limit.
236 static int Capacity();
237
Steve Block3ce2e202009-11-05 08:53:23 +0000238 // Returns the amount of memory currently committed for the heap.
239 static int CommittedMemory();
240
Steve Blocka7e24c12009-10-30 11:49:00 +0000241 // Returns the available bytes in space w/o growing.
242 // Heap doesn't guarantee that it can allocate an object that requires
243 // all available bytes. Check MaxHeapObjectSize() instead.
244 static int Available();
245
246 // Returns the maximum object size in paged space.
247 static inline int MaxObjectSizeInPagedSpace();
248
249 // Returns of size of all objects residing in the heap.
250 static int SizeOfObjects();
251
252 // Return the starting address and a mask for the new space. And-masking an
253 // address with the mask will result in the start address of the new space
254 // for all addresses in either semispace.
255 static Address NewSpaceStart() { return new_space_.start(); }
256 static uintptr_t NewSpaceMask() { return new_space_.mask(); }
257 static Address NewSpaceTop() { return new_space_.top(); }
258
259 static NewSpace* new_space() { return &new_space_; }
260 static OldSpace* old_pointer_space() { return old_pointer_space_; }
261 static OldSpace* old_data_space() { return old_data_space_; }
262 static OldSpace* code_space() { return code_space_; }
263 static MapSpace* map_space() { return map_space_; }
264 static CellSpace* cell_space() { return cell_space_; }
265 static LargeObjectSpace* lo_space() { return lo_space_; }
266
267 static bool always_allocate() { return always_allocate_scope_depth_ != 0; }
268 static Address always_allocate_scope_depth_address() {
269 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
270 }
Steve Blockd0582a62009-12-15 09:54:21 +0000271 static bool linear_allocation() {
272 return linear_allocation_scope_depth_ != 0;
273 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000274
275 static Address* NewSpaceAllocationTopAddress() {
276 return new_space_.allocation_top_address();
277 }
278 static Address* NewSpaceAllocationLimitAddress() {
279 return new_space_.allocation_limit_address();
280 }
281
282 // Uncommit unused semi space.
283 static bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
284
285#ifdef ENABLE_HEAP_PROTECTION
286 // Protect/unprotect the heap by marking all spaces read-only/writable.
287 static void Protect();
288 static void Unprotect();
289#endif
290
291 // Allocates and initializes a new JavaScript object based on a
292 // constructor.
293 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
294 // failed.
295 // Please note this does not perform a garbage collection.
296 static Object* AllocateJSObject(JSFunction* constructor,
297 PretenureFlag pretenure = NOT_TENURED);
298
299 // Allocates and initializes a new global object based on a constructor.
300 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
301 // failed.
302 // Please note this does not perform a garbage collection.
303 static Object* AllocateGlobalObject(JSFunction* constructor);
304
305 // Returns a deep copy of the JavaScript object.
306 // Properties and elements are copied too.
307 // Returns failure if allocation failed.
308 static Object* CopyJSObject(JSObject* source);
309
310 // Allocates the function prototype.
311 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
312 // failed.
313 // Please note this does not perform a garbage collection.
314 static Object* AllocateFunctionPrototype(JSFunction* function);
315
316 // Reinitialize an JSGlobalProxy based on a constructor. The object
317 // must have the same size as objects allocated using the
318 // constructor. The object is reinitialized and behaves as an
319 // object that has been freshly allocated using the constructor.
320 static Object* ReinitializeJSGlobalProxy(JSFunction* constructor,
321 JSGlobalProxy* global);
322
323 // Allocates and initializes a new JavaScript object based on a map.
324 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
325 // failed.
326 // Please note this does not perform a garbage collection.
327 static Object* AllocateJSObjectFromMap(Map* map,
328 PretenureFlag pretenure = NOT_TENURED);
329
330 // Allocates a heap object based on the map.
331 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
332 // failed.
333 // Please note this function does not perform a garbage collection.
334 static Object* Allocate(Map* map, AllocationSpace space);
335
336 // Allocates a JS Map in the heap.
337 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
338 // failed.
339 // Please note this function does not perform a garbage collection.
340 static Object* AllocateMap(InstanceType instance_type, int instance_size);
341
342 // Allocates a partial map for bootstrapping.
343 static Object* AllocatePartialMap(InstanceType instance_type,
344 int instance_size);
345
346 // Allocate a map for the specified function
347 static Object* AllocateInitialMap(JSFunction* fun);
348
349 // Allocates and fully initializes a String. There are two String
350 // encodings: ASCII and two byte. One should choose between the three string
351 // allocation functions based on the encoding of the string buffer used to
352 // initialized the string.
353 // - ...FromAscii initializes the string from a buffer that is ASCII
354 // encoded (it does not check that the buffer is ASCII encoded) and the
355 // result will be ASCII encoded.
356 // - ...FromUTF8 initializes the string from a buffer that is UTF-8
357 // encoded. If the characters are all single-byte characters, the
358 // result will be ASCII encoded, otherwise it will converted to two
359 // byte.
360 // - ...FromTwoByte initializes the string from a buffer that is two-byte
361 // encoded. If the characters are all single-byte characters, the
362 // result will be converted to ASCII, otherwise it will be left as
363 // two-byte.
364 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
365 // failed.
366 // Please note this does not perform a garbage collection.
367 static Object* AllocateStringFromAscii(
368 Vector<const char> str,
369 PretenureFlag pretenure = NOT_TENURED);
370 static Object* AllocateStringFromUtf8(
371 Vector<const char> str,
372 PretenureFlag pretenure = NOT_TENURED);
373 static Object* AllocateStringFromTwoByte(
374 Vector<const uc16> str,
375 PretenureFlag pretenure = NOT_TENURED);
376
377 // Allocates a symbol in old space based on the character stream.
378 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
379 // failed.
380 // Please note this function does not perform a garbage collection.
381 static inline Object* AllocateSymbol(Vector<const char> str,
382 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +0000383 uint32_t hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000384
385 static Object* AllocateInternalSymbol(unibrow::CharacterStream* buffer,
386 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +0000387 uint32_t hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000388
389 static Object* AllocateExternalSymbol(Vector<const char> str,
390 int chars);
391
392
393 // Allocates and partially initializes a String. There are two String
394 // encodings: ASCII and two byte. These functions allocate a string of the
395 // given length and set its map and length fields. The characters of the
396 // string are uninitialized.
397 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
398 // failed.
399 // Please note this does not perform a garbage collection.
400 static Object* AllocateRawAsciiString(
401 int length,
402 PretenureFlag pretenure = NOT_TENURED);
403 static Object* AllocateRawTwoByteString(
404 int length,
405 PretenureFlag pretenure = NOT_TENURED);
406
407 // Computes a single character string where the character has code.
408 // A cache is used for ascii codes.
409 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
410 // failed. Please note this does not perform a garbage collection.
411 static Object* LookupSingleCharacterStringFromCode(uint16_t code);
412
413 // Allocate a byte array of the specified length
414 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
415 // failed.
416 // Please note this does not perform a garbage collection.
417 static Object* AllocateByteArray(int length, PretenureFlag pretenure);
418
419 // Allocate a non-tenured byte array of the specified length
420 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
421 // failed.
422 // Please note this does not perform a garbage collection.
423 static Object* AllocateByteArray(int length);
424
425 // Allocate a pixel array of the specified length
426 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
427 // failed.
428 // Please note this does not perform a garbage collection.
429 static Object* AllocatePixelArray(int length,
430 uint8_t* external_pointer,
431 PretenureFlag pretenure);
432
Steve Block3ce2e202009-11-05 08:53:23 +0000433 // Allocates an external array of the specified length and type.
434 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
435 // failed.
436 // Please note this does not perform a garbage collection.
437 static Object* AllocateExternalArray(int length,
438 ExternalArrayType array_type,
439 void* external_pointer,
440 PretenureFlag pretenure);
441
Steve Blocka7e24c12009-10-30 11:49:00 +0000442 // Allocate a tenured JS global property cell.
443 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
444 // failed.
445 // Please note this does not perform a garbage collection.
446 static Object* AllocateJSGlobalPropertyCell(Object* value);
447
448 // Allocates a fixed array initialized with undefined values
449 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
450 // failed.
451 // Please note this does not perform a garbage collection.
452 static Object* AllocateFixedArray(int length, PretenureFlag pretenure);
453 // Allocate uninitialized, non-tenured fixed array with length elements.
454 static Object* AllocateFixedArray(int length);
455
456 // Make a copy of src and return it. Returns
457 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
458 static Object* CopyFixedArray(FixedArray* src);
459
460 // Allocates a fixed array initialized with the hole values.
461 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
462 // failed.
463 // Please note this does not perform a garbage collection.
464 static Object* AllocateFixedArrayWithHoles(int length);
465
466 // AllocateHashTable is identical to AllocateFixedArray except
467 // that the resulting object has hash_table_map as map.
468 static Object* AllocateHashTable(int length);
469
470 // Allocate a global (but otherwise uninitialized) context.
471 static Object* AllocateGlobalContext();
472
473 // Allocate a function context.
474 static Object* AllocateFunctionContext(int length, JSFunction* closure);
475
476 // Allocate a 'with' context.
477 static Object* AllocateWithContext(Context* previous,
478 JSObject* extension,
479 bool is_catch_context);
480
481 // Allocates a new utility object in the old generation.
482 static Object* AllocateStruct(InstanceType type);
483
484 // Allocates a function initialized with a shared part.
485 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
486 // failed.
487 // Please note this does not perform a garbage collection.
488 static Object* AllocateFunction(Map* function_map,
489 SharedFunctionInfo* shared,
490 Object* prototype);
491
492 // Indicies for direct access into argument objects.
493 static const int arguments_callee_index = 0;
494 static const int arguments_length_index = 1;
495
496 // Allocates an arguments object - optionally with an elements array.
497 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
498 // failed.
499 // Please note this does not perform a garbage collection.
500 static Object* AllocateArgumentsObject(Object* callee, int length);
501
502 // Converts a double into either a Smi or a HeapNumber object.
503 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
504 // failed.
505 // Please note this does not perform a garbage collection.
506 static Object* NewNumberFromDouble(double value,
507 PretenureFlag pretenure = NOT_TENURED);
508
509 // Same as NewNumberFromDouble, but may return a preallocated/immutable
510 // number object (e.g., minus_zero_value_, nan_value_)
511 static Object* NumberFromDouble(double value,
512 PretenureFlag pretenure = NOT_TENURED);
513
514 // Allocated a HeapNumber from value.
515 static Object* AllocateHeapNumber(double value, PretenureFlag pretenure);
516 static Object* AllocateHeapNumber(double value); // pretenure = NOT_TENURED
517
518 // Converts an int into either a Smi or a HeapNumber object.
519 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
520 // failed.
521 // Please note this does not perform a garbage collection.
522 static inline Object* NumberFromInt32(int32_t value);
523
524 // Converts an int into either a Smi or a HeapNumber object.
525 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
526 // failed.
527 // Please note this does not perform a garbage collection.
528 static inline Object* NumberFromUint32(uint32_t value);
529
530 // Allocates a new proxy object.
531 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
532 // failed.
533 // Please note this does not perform a garbage collection.
534 static Object* AllocateProxy(Address proxy,
535 PretenureFlag pretenure = NOT_TENURED);
536
537 // Allocates a new SharedFunctionInfo object.
538 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
539 // failed.
540 // Please note this does not perform a garbage collection.
541 static Object* AllocateSharedFunctionInfo(Object* name);
542
543 // Allocates a new cons string object.
544 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
545 // failed.
546 // Please note this does not perform a garbage collection.
547 static Object* AllocateConsString(String* first, String* second);
548
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 // Allocates a new sub string object which is a substring of an underlying
550 // string buffer stretching from the index start (inclusive) to the index
551 // end (exclusive).
552 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
553 // failed.
554 // Please note this does not perform a garbage collection.
555 static Object* AllocateSubString(String* buffer,
556 int start,
557 int end);
558
559 // Allocate a new external string object, which is backed by a string
560 // resource that resides outside the V8 heap.
561 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
562 // failed.
563 // Please note this does not perform a garbage collection.
564 static Object* AllocateExternalStringFromAscii(
565 ExternalAsciiString::Resource* resource);
566 static Object* AllocateExternalStringFromTwoByte(
567 ExternalTwoByteString::Resource* resource);
568
569 // Allocates an uninitialized object. The memory is non-executable if the
570 // hardware and OS allow.
571 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
572 // failed.
573 // Please note this function does not perform a garbage collection.
574 static inline Object* AllocateRaw(int size_in_bytes,
575 AllocationSpace space,
576 AllocationSpace retry_space);
577
578 // Initialize a filler object to keep the ability to iterate over the heap
579 // when shortening objects.
580 static void CreateFillerObjectAt(Address addr, int size);
581
582 // Makes a new native code object
583 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
584 // failed. On success, the pointer to the Code object is stored in the
585 // self_reference. This allows generated code to reference its own Code
586 // object by containing this pointer.
587 // Please note this function does not perform a garbage collection.
588 static Object* CreateCode(const CodeDesc& desc,
589 ZoneScopeInfo* sinfo,
590 Code::Flags flags,
591 Handle<Object> self_reference);
592
593 static Object* CopyCode(Code* code);
594 // Finds the symbol for string in the symbol table.
595 // If not found, a new symbol is added to the table and returned.
596 // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
597 // failed.
598 // Please note this function does not perform a garbage collection.
599 static Object* LookupSymbol(Vector<const char> str);
600 static Object* LookupAsciiSymbol(const char* str) {
601 return LookupSymbol(CStrVector(str));
602 }
603 static Object* LookupSymbol(String* str);
604 static bool LookupSymbolIfExists(String* str, String** symbol);
Steve Blockd0582a62009-12-15 09:54:21 +0000605 static bool LookupTwoCharsSymbolIfExists(String* str, String** symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000606
607 // Compute the matching symbol map for a string if possible.
608 // NULL is returned if string is in new space or not flattened.
609 static Map* SymbolMapForString(String* str);
610
611 // Converts the given boolean condition to JavaScript boolean value.
612 static Object* ToBoolean(bool condition) {
613 return condition ? true_value() : false_value();
614 }
615
616 // Code that should be run before and after each GC. Includes some
617 // reporting/verification activities when compiled with DEBUG set.
618 static void GarbageCollectionPrologue();
619 static void GarbageCollectionEpilogue();
620
Steve Blocka7e24c12009-10-30 11:49:00 +0000621 // Performs garbage collection operation.
622 // Returns whether required_space bytes are available after the collection.
623 static bool CollectGarbage(int required_space, AllocationSpace space);
624
625 // Performs a full garbage collection. Force compaction if the
626 // parameter is true.
627 static void CollectAllGarbage(bool force_compaction);
628
629 // Performs a full garbage collection if a context has been disposed
630 // since the last time the check was performed.
631 static void CollectAllGarbageIfContextDisposed();
632
633 // Notify the heap that a context has been disposed.
634 static void NotifyContextDisposed();
635
636 // Utility to invoke the scavenger. This is needed in test code to
637 // ensure correct callback for weak global handles.
638 static void PerformScavenge();
639
640#ifdef DEBUG
641 // Utility used with flag gc-greedy.
642 static bool GarbageCollectionGreedyCheck();
643#endif
644
645 static void SetGlobalGCPrologueCallback(GCCallback callback) {
646 global_gc_prologue_callback_ = callback;
647 }
648 static void SetGlobalGCEpilogueCallback(GCCallback callback) {
649 global_gc_epilogue_callback_ = callback;
650 }
651
652 // Heap root getters. We have versions with and without type::cast() here.
653 // You can't use type::cast during GC because the assert fails.
654#define ROOT_ACCESSOR(type, name, camel_name) \
655 static inline type* name() { \
656 return type::cast(roots_[k##camel_name##RootIndex]); \
657 } \
658 static inline type* raw_unchecked_##name() { \
659 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
660 }
661 ROOT_LIST(ROOT_ACCESSOR)
662#undef ROOT_ACCESSOR
663
664// Utility type maps
665#define STRUCT_MAP_ACCESSOR(NAME, Name, name) \
666 static inline Map* name##_map() { \
667 return Map::cast(roots_[k##Name##MapRootIndex]); \
668 }
669 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
670#undef STRUCT_MAP_ACCESSOR
671
672#define SYMBOL_ACCESSOR(name, str) static inline String* name() { \
673 return String::cast(roots_[k##name##RootIndex]); \
674 }
675 SYMBOL_LIST(SYMBOL_ACCESSOR)
676#undef SYMBOL_ACCESSOR
677
678 // The hidden_symbol is special because it is the empty string, but does
679 // not match the empty string.
680 static String* hidden_symbol() { return hidden_symbol_; }
681
682 // Iterates over all roots in the heap.
Steve Blockd0582a62009-12-15 09:54:21 +0000683 static void IterateRoots(ObjectVisitor* v, VisitMode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000684 // Iterates over all strong roots in the heap.
Steve Blockd0582a62009-12-15 09:54:21 +0000685 static void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000686
687 // Iterates remembered set of an old space.
688 static void IterateRSet(PagedSpace* space, ObjectSlotCallback callback);
689
690 // Iterates a range of remembered set addresses starting with rset_start
691 // corresponding to the range of allocated pointers
692 // [object_start, object_end).
693 // Returns the number of bits that were set.
694 static int IterateRSetRange(Address object_start,
695 Address object_end,
696 Address rset_start,
697 ObjectSlotCallback copy_object_func);
698
699 // Returns whether the object resides in new space.
700 static inline bool InNewSpace(Object* object);
701 static inline bool InFromSpace(Object* object);
702 static inline bool InToSpace(Object* object);
703
704 // Checks whether an address/object in the heap (including auxiliary
705 // area and unused area).
706 static bool Contains(Address addr);
707 static bool Contains(HeapObject* value);
708
709 // Checks whether an address/object in a space.
Steve Blockd0582a62009-12-15 09:54:21 +0000710 // Currently used by tests, serialization and heap verification only.
Steve Blocka7e24c12009-10-30 11:49:00 +0000711 static bool InSpace(Address addr, AllocationSpace space);
712 static bool InSpace(HeapObject* value, AllocationSpace space);
713
714 // Finds out which space an object should get promoted to based on its type.
715 static inline OldSpace* TargetSpace(HeapObject* object);
716 static inline AllocationSpace TargetSpaceId(InstanceType type);
717
718 // Sets the stub_cache_ (only used when expanding the dictionary).
719 static void public_set_code_stubs(NumberDictionary* value) {
720 roots_[kCodeStubsRootIndex] = value;
721 }
722
723 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
724 static void public_set_non_monomorphic_cache(NumberDictionary* value) {
725 roots_[kNonMonomorphicCacheRootIndex] = value;
726 }
727
728 // Update the next script id.
729 static inline void SetLastScriptId(Object* last_script_id);
730
731 // Generated code can embed this address to get access to the roots.
732 static Object** roots_address() { return roots_; }
733
734#ifdef DEBUG
735 static void Print();
736 static void PrintHandles();
737
738 // Verify the heap is in its normal state before or after a GC.
739 static void Verify();
740
741 // Report heap statistics.
742 static void ReportHeapStatistics(const char* title);
743 static void ReportCodeStatistics(const char* title);
744
745 // Fill in bogus values in from space
746 static void ZapFromSpace();
747#endif
748
749#if defined(ENABLE_LOGGING_AND_PROFILING)
750 // Print short heap statistics.
751 static void PrintShortHeapStatistics();
752#endif
753
754 // Makes a new symbol object
755 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
756 // failed.
757 // Please note this function does not perform a garbage collection.
758 static Object* CreateSymbol(const char* str, int length, int hash);
759 static Object* CreateSymbol(String* str);
760
761 // Write barrier support for address[offset] = o.
762 static inline void RecordWrite(Address address, int offset);
763
764 // Given an address occupied by a live code object, return that object.
765 static Object* FindCodeObject(Address a);
766
767 // Invoke Shrink on shrinkable spaces.
768 static void Shrink();
769
770 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
771 static inline HeapState gc_state() { return gc_state_; }
772
773#ifdef DEBUG
774 static bool IsAllocationAllowed() { return allocation_allowed_; }
775 static inline bool allow_allocation(bool enable);
776
777 static bool disallow_allocation_failure() {
778 return disallow_allocation_failure_;
779 }
780
781 static void TracePathToObject();
782 static void TracePathToGlobal();
783#endif
784
785 // Callback function passed to Heap::Iterate etc. Copies an object if
786 // necessary, the object might be promoted to an old space. The caller must
787 // ensure the precondition that the object is (a) a heap object and (b) in
788 // the heap's from space.
789 static void ScavengePointer(HeapObject** p);
790 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
791
792 // Clear a range of remembered set addresses corresponding to the object
793 // area address 'start' with size 'size_in_bytes', eg, when adding blocks
794 // to the free list.
795 static void ClearRSetRange(Address start, int size_in_bytes);
796
797 // Rebuild remembered set in old and map spaces.
798 static void RebuildRSets();
799
800 // Commits from space if it is uncommitted.
801 static void EnsureFromSpaceIsCommitted();
802
803 //
804 // Support for the API.
805 //
806
807 static bool CreateApiObjects();
808
809 // Attempt to find the number in a small cache. If we finds it, return
810 // the string representation of the number. Otherwise return undefined.
811 static Object* GetNumberStringCache(Object* number);
812
813 // Update the cache with a new number-string pair.
814 static void SetNumberStringCache(Object* number, String* str);
815
816 // Entries in the cache. Must be a power of 2.
817 static const int kNumberStringCacheSize = 64;
818
819 // Adjusts the amount of registered external memory.
820 // Returns the adjusted value.
821 static inline int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
822
823 // Allocate unitialized fixed array (pretenure == NON_TENURE).
824 static Object* AllocateRawFixedArray(int length);
825
826 // True if we have reached the allocation limit in the old generation that
827 // should force the next GC (caused normally) to be a full one.
828 static bool OldGenerationPromotionLimitReached() {
829 return (PromotedSpaceSize() + PromotedExternalMemorySize())
830 > old_gen_promotion_limit_;
831 }
832
833 // True if we have reached the allocation limit in the old generation that
834 // should artificially cause a GC right now.
835 static bool OldGenerationAllocationLimitReached() {
836 return (PromotedSpaceSize() + PromotedExternalMemorySize())
837 > old_gen_allocation_limit_;
838 }
839
840 // Can be called when the embedding application is idle.
841 static bool IdleNotification();
842
843 // Declare all the root indices.
844 enum RootListIndex {
845#define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
846 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
847#undef ROOT_INDEX_DECLARATION
848
849// Utility type maps
850#define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
851 STRUCT_LIST(DECLARE_STRUCT_MAP)
852#undef DECLARE_STRUCT_MAP
853
854#define SYMBOL_INDEX_DECLARATION(name, str) k##name##RootIndex,
855 SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
856#undef SYMBOL_DECLARATION
857
858 kSymbolTableRootIndex,
859 kStrongRootListLength = kSymbolTableRootIndex,
860 kRootListLength
861 };
862
863 static Object* NumberToString(Object* number);
864
Steve Block3ce2e202009-11-05 08:53:23 +0000865 static Map* MapForExternalArrayType(ExternalArrayType array_type);
866 static RootListIndex RootIndexForExternalArrayType(
867 ExternalArrayType array_type);
868
Steve Blockd0582a62009-12-15 09:54:21 +0000869 static void RecordStats(HeapStats* stats);
870
Steve Blocka7e24c12009-10-30 11:49:00 +0000871 private:
Steve Block3ce2e202009-11-05 08:53:23 +0000872 static int reserved_semispace_size_;
873 static int max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000874 static int initial_semispace_size_;
Steve Block3ce2e202009-11-05 08:53:23 +0000875 static int max_old_generation_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000876 static size_t code_range_size_;
877
878 // For keeping track of how much data has survived
879 // scavenge since last new space expansion.
880 static int survived_since_last_expansion_;
881
882 static int always_allocate_scope_depth_;
Steve Blockd0582a62009-12-15 09:54:21 +0000883 static int linear_allocation_scope_depth_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000884 static bool context_disposed_pending_;
885
Steve Blockd0582a62009-12-15 09:54:21 +0000886 // The number of MapSpace pages is limited by the way we pack
887 // Map pointers during GC.
888 static const int kMaxMapSpaceSize =
889 (1 << MapWord::kMapPageIndexBits) * Page::kPageSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000890
891#if defined(V8_TARGET_ARCH_X64)
892 static const int kMaxObjectSizeInNewSpace = 512*KB;
893#else
894 static const int kMaxObjectSizeInNewSpace = 256*KB;
895#endif
896
897 static NewSpace new_space_;
898 static OldSpace* old_pointer_space_;
899 static OldSpace* old_data_space_;
900 static OldSpace* code_space_;
901 static MapSpace* map_space_;
902 static CellSpace* cell_space_;
903 static LargeObjectSpace* lo_space_;
904 static HeapState gc_state_;
905
906 // Returns the size of object residing in non new spaces.
907 static int PromotedSpaceSize();
908
909 // Returns the amount of external memory registered since last global gc.
910 static int PromotedExternalMemorySize();
911
912 static int mc_count_; // how many mark-compact collections happened
913 static int gc_count_; // how many gc happened
914
915#define ROOT_ACCESSOR(type, name, camel_name) \
916 static inline void set_##name(type* value) { \
917 roots_[k##camel_name##RootIndex] = value; \
918 }
919 ROOT_LIST(ROOT_ACCESSOR)
920#undef ROOT_ACCESSOR
921
922#ifdef DEBUG
923 static bool allocation_allowed_;
924
925 // If the --gc-interval flag is set to a positive value, this
926 // variable holds the value indicating the number of allocations
927 // remain until the next failure and garbage collection.
928 static int allocation_timeout_;
929
930 // Do we expect to be able to handle allocation failure at this
931 // time?
932 static bool disallow_allocation_failure_;
933#endif // DEBUG
934
935 // Limit that triggers a global GC on the next (normally caused) GC. This
936 // is checked when we have already decided to do a GC to help determine
937 // which collector to invoke.
938 static int old_gen_promotion_limit_;
939
940 // Limit that triggers a global GC as soon as is reasonable. This is
941 // checked before expanding a paged space in the old generation and on
942 // every allocation in large object space.
943 static int old_gen_allocation_limit_;
944
945 // Limit on the amount of externally allocated memory allowed
946 // between global GCs. If reached a global GC is forced.
947 static int external_allocation_limit_;
948
949 // The amount of external memory registered through the API kept alive
950 // by global handles
951 static int amount_of_external_allocated_memory_;
952
953 // Caches the amount of external memory registered at the last global gc.
954 static int amount_of_external_allocated_memory_at_last_global_gc_;
955
956 // Indicates that an allocation has failed in the old generation since the
957 // last GC.
958 static int old_gen_exhausted_;
959
960 static Object* roots_[kRootListLength];
961
962 struct StringTypeTable {
963 InstanceType type;
964 int size;
965 RootListIndex index;
966 };
967
968 struct ConstantSymbolTable {
969 const char* contents;
970 RootListIndex index;
971 };
972
973 struct StructTable {
974 InstanceType type;
975 int size;
976 RootListIndex index;
977 };
978
979 static const StringTypeTable string_type_table[];
980 static const ConstantSymbolTable constant_symbol_table[];
981 static const StructTable struct_table[];
982
983 // The special hidden symbol which is an empty string, but does not match
984 // any string when looked up in properties.
985 static String* hidden_symbol_;
986
987 // GC callback function, called before and after mark-compact GC.
988 // Allocations in the callback function are disallowed.
989 static GCCallback global_gc_prologue_callback_;
990 static GCCallback global_gc_epilogue_callback_;
991
992 // Checks whether a global GC is necessary
993 static GarbageCollector SelectGarbageCollector(AllocationSpace space);
994
995 // Performs garbage collection
996 static void PerformGarbageCollection(AllocationSpace space,
997 GarbageCollector collector,
998 GCTracer* tracer);
999
1000 // Returns either a Smi or a Number object from 'value'. If 'new_object'
1001 // is false, it may return a preallocated immutable object.
1002 static Object* SmiOrNumberFromDouble(double value,
1003 bool new_object,
1004 PretenureFlag pretenure = NOT_TENURED);
1005
1006 // Allocate an uninitialized object in map space. The behavior is identical
1007 // to Heap::AllocateRaw(size_in_bytes, MAP_SPACE), except that (a) it doesn't
1008 // have to test the allocation space argument and (b) can reduce code size
1009 // (since both AllocateRaw and AllocateRawMap are inlined).
1010 static inline Object* AllocateRawMap();
1011
1012 // Allocate an uninitialized object in the global property cell space.
1013 static inline Object* AllocateRawCell();
1014
1015 // Initializes a JSObject based on its map.
1016 static void InitializeJSObjectFromMap(JSObject* obj,
1017 FixedArray* properties,
1018 Map* map);
1019
1020 static bool CreateInitialMaps();
1021 static bool CreateInitialObjects();
1022
1023 // These four Create*EntryStub functions are here because of a gcc-4.4 bug
1024 // that assigns wrong vtable entries.
1025 static void CreateCEntryStub();
1026 static void CreateCEntryDebugBreakStub();
1027 static void CreateJSEntryStub();
1028 static void CreateJSConstructEntryStub();
1029 static void CreateRegExpCEntryStub();
1030
1031 static void CreateFixedStubs();
1032
1033 static Object* CreateOddball(Map* map,
1034 const char* to_string,
1035 Object* to_number);
1036
1037 // Allocate empty fixed array.
1038 static Object* AllocateEmptyFixedArray();
1039
1040 // Performs a minor collection in new generation.
1041 static void Scavenge();
1042
1043 // Performs a major collection in the whole heap.
1044 static void MarkCompact(GCTracer* tracer);
1045
1046 // Code to be run before and after mark-compact.
1047 static void MarkCompactPrologue(bool is_compacting);
1048 static void MarkCompactEpilogue(bool is_compacting);
1049
1050 // Helper function used by CopyObject to copy a source object to an
1051 // allocated target object and update the forwarding pointer in the source
1052 // object. Returns the target object.
1053 static HeapObject* MigrateObject(HeapObject* source,
1054 HeapObject* target,
1055 int size);
1056
1057 // Helper function that governs the promotion policy from new space to
1058 // old. If the object's old address lies below the new space's age
1059 // mark or if we've already filled the bottom 1/16th of the to space,
1060 // we try to promote this object.
1061 static inline bool ShouldBePromoted(Address old_address, int object_size);
1062#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1063 // Record the copy of an object in the NewSpace's statistics.
1064 static void RecordCopiedObject(HeapObject* obj);
1065
1066 // Record statistics before and after garbage collection.
1067 static void ReportStatisticsBeforeGC();
1068 static void ReportStatisticsAfterGC();
1069#endif
1070
1071 // Update an old object's remembered set
1072 static int UpdateRSet(HeapObject* obj);
1073
1074 // Rebuild remembered set in an old space.
1075 static void RebuildRSets(PagedSpace* space);
1076
1077 // Rebuild remembered set in the large object space.
1078 static void RebuildRSets(LargeObjectSpace* space);
1079
1080 // Slow part of scavenge object.
1081 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
1082
1083 // Copy memory from src to dst.
1084 static inline void CopyBlock(Object** dst, Object** src, int byte_size);
1085
1086 // Initializes a function with a shared part and prototype.
1087 // Returns the function.
1088 // Note: this code was factored out of AllocateFunction such that
1089 // other parts of the VM could use it. Specifically, a function that creates
1090 // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
1091 // Please note this does not perform a garbage collection.
1092 static inline Object* InitializeFunction(JSFunction* function,
1093 SharedFunctionInfo* shared,
1094 Object* prototype);
1095
1096 static const int kInitialSymbolTableSize = 2048;
1097 static const int kInitialEvalCacheSize = 64;
1098
1099 friend class Factory;
1100 friend class DisallowAllocationFailure;
1101 friend class AlwaysAllocateScope;
Steve Blockd0582a62009-12-15 09:54:21 +00001102 friend class LinearAllocationScope;
1103};
1104
1105
1106class HeapStats {
1107 public:
1108 int *start_marker;
1109 int *new_space_size;
1110 int *new_space_capacity;
1111 int *old_pointer_space_size;
1112 int *old_pointer_space_capacity;
1113 int *old_data_space_size;
1114 int *old_data_space_capacity;
1115 int *code_space_size;
1116 int *code_space_capacity;
1117 int *map_space_size;
1118 int *map_space_capacity;
1119 int *cell_space_size;
1120 int *cell_space_capacity;
1121 int *lo_space_size;
1122 int *global_handle_count;
1123 int *weak_global_handle_count;
1124 int *pending_global_handle_count;
1125 int *near_death_global_handle_count;
1126 int *destroyed_global_handle_count;
1127 int *end_marker;
Steve Blocka7e24c12009-10-30 11:49:00 +00001128};
1129
1130
1131class AlwaysAllocateScope {
1132 public:
1133 AlwaysAllocateScope() {
1134 // We shouldn't hit any nested scopes, because that requires
1135 // non-handle code to call handle code. The code still works but
1136 // performance will degrade, so we want to catch this situation
1137 // in debug mode.
1138 ASSERT(Heap::always_allocate_scope_depth_ == 0);
1139 Heap::always_allocate_scope_depth_++;
1140 }
1141
1142 ~AlwaysAllocateScope() {
1143 Heap::always_allocate_scope_depth_--;
1144 ASSERT(Heap::always_allocate_scope_depth_ == 0);
1145 }
1146};
1147
1148
Steve Blockd0582a62009-12-15 09:54:21 +00001149class LinearAllocationScope {
1150 public:
1151 LinearAllocationScope() {
1152 Heap::linear_allocation_scope_depth_++;
1153 }
1154
1155 ~LinearAllocationScope() {
1156 Heap::linear_allocation_scope_depth_--;
1157 ASSERT(Heap::linear_allocation_scope_depth_ >= 0);
1158 }
1159};
1160
1161
Steve Blocka7e24c12009-10-30 11:49:00 +00001162#ifdef DEBUG
1163// Visitor class to verify interior pointers that do not have remembered set
1164// bits. All heap object pointers have to point into the heap to a location
1165// that has a map pointer at its first word. Caveat: Heap::Contains is an
1166// approximation because it can return true for objects in a heap space but
1167// above the allocation pointer.
1168class VerifyPointersVisitor: public ObjectVisitor {
1169 public:
1170 void VisitPointers(Object** start, Object** end) {
1171 for (Object** current = start; current < end; current++) {
1172 if ((*current)->IsHeapObject()) {
1173 HeapObject* object = HeapObject::cast(*current);
1174 ASSERT(Heap::Contains(object));
1175 ASSERT(object->map()->IsMap());
1176 }
1177 }
1178 }
1179};
1180
1181
1182// Visitor class to verify interior pointers that have remembered set bits.
1183// As VerifyPointersVisitor but also checks that remembered set bits are
1184// always set for pointers into new space.
1185class VerifyPointersAndRSetVisitor: public ObjectVisitor {
1186 public:
1187 void VisitPointers(Object** start, Object** end) {
1188 for (Object** current = start; current < end; current++) {
1189 if ((*current)->IsHeapObject()) {
1190 HeapObject* object = HeapObject::cast(*current);
1191 ASSERT(Heap::Contains(object));
1192 ASSERT(object->map()->IsMap());
1193 if (Heap::InNewSpace(object)) {
1194 ASSERT(Page::IsRSetSet(reinterpret_cast<Address>(current), 0));
1195 }
1196 }
1197 }
1198 }
1199};
1200#endif
1201
1202
1203// Space iterator for iterating over all spaces of the heap.
1204// Returns each space in turn, and null when it is done.
1205class AllSpaces BASE_EMBEDDED {
1206 public:
1207 Space* next();
1208 AllSpaces() { counter_ = FIRST_SPACE; }
1209 private:
1210 int counter_;
1211};
1212
1213
1214// Space iterator for iterating over all old spaces of the heap: Old pointer
1215// space, old data space and code space.
1216// Returns each space in turn, and null when it is done.
1217class OldSpaces BASE_EMBEDDED {
1218 public:
1219 OldSpace* next();
1220 OldSpaces() { counter_ = OLD_POINTER_SPACE; }
1221 private:
1222 int counter_;
1223};
1224
1225
1226// Space iterator for iterating over all the paged spaces of the heap:
1227// Map space, old pointer space, old data space and code space.
1228// Returns each space in turn, and null when it is done.
1229class PagedSpaces BASE_EMBEDDED {
1230 public:
1231 PagedSpace* next();
1232 PagedSpaces() { counter_ = OLD_POINTER_SPACE; }
1233 private:
1234 int counter_;
1235};
1236
1237
1238// Space iterator for iterating over all spaces of the heap.
1239// For each space an object iterator is provided. The deallocation of the
1240// returned object iterators is handled by the space iterator.
1241class SpaceIterator : public Malloced {
1242 public:
1243 SpaceIterator();
1244 virtual ~SpaceIterator();
1245
1246 bool has_next();
1247 ObjectIterator* next();
1248
1249 private:
1250 ObjectIterator* CreateIterator();
1251
1252 int current_space_; // from enum AllocationSpace.
1253 ObjectIterator* iterator_; // object iterator for the current space.
1254};
1255
1256
1257// A HeapIterator provides iteration over the whole heap It aggregates a the
1258// specific iterators for the different spaces as these can only iterate over
1259// one space only.
1260
1261class HeapIterator BASE_EMBEDDED {
1262 public:
1263 explicit HeapIterator();
1264 virtual ~HeapIterator();
1265
1266 bool has_next();
1267 HeapObject* next();
1268 void reset();
1269
1270 private:
1271 // Perform the initialization.
1272 void Init();
1273
1274 // Perform all necessary shutdown (destruction) work.
1275 void Shutdown();
1276
1277 // Space iterator for iterating all the spaces.
1278 SpaceIterator* space_iterator_;
1279 // Object iterator for the space currently being iterated.
1280 ObjectIterator* object_iterator_;
1281};
1282
1283
1284// Cache for mapping (map, property name) into field offset.
1285// Cleared at startup and prior to mark sweep collection.
1286class KeyedLookupCache {
1287 public:
1288 // Lookup field offset for (map, name). If absent, -1 is returned.
1289 static int Lookup(Map* map, String* name);
1290
1291 // Update an element in the cache.
1292 static void Update(Map* map, String* name, int field_offset);
1293
1294 // Clear the cache.
1295 static void Clear();
1296 private:
1297 static inline int Hash(Map* map, String* name);
1298 static const int kLength = 64;
1299 struct Key {
1300 Map* map;
1301 String* name;
1302 };
1303 static Key keys_[kLength];
1304 static int field_offsets_[kLength];
1305};
1306
1307
1308
1309// Cache for mapping (array, property name) into descriptor index.
1310// The cache contains both positive and negative results.
1311// Descriptor index equals kNotFound means the property is absent.
1312// Cleared at startup and prior to any gc.
1313class DescriptorLookupCache {
1314 public:
1315 // Lookup descriptor index for (map, name).
1316 // If absent, kAbsent is returned.
1317 static int Lookup(DescriptorArray* array, String* name) {
1318 if (!StringShape(name).IsSymbol()) return kAbsent;
1319 int index = Hash(array, name);
1320 Key& key = keys_[index];
1321 if ((key.array == array) && (key.name == name)) return results_[index];
1322 return kAbsent;
1323 }
1324
1325 // Update an element in the cache.
1326 static void Update(DescriptorArray* array, String* name, int result) {
1327 ASSERT(result != kAbsent);
1328 if (StringShape(name).IsSymbol()) {
1329 int index = Hash(array, name);
1330 Key& key = keys_[index];
1331 key.array = array;
1332 key.name = name;
1333 results_[index] = result;
1334 }
1335 }
1336
1337 // Clear the cache.
1338 static void Clear();
1339
1340 static const int kAbsent = -2;
1341 private:
1342 static int Hash(DescriptorArray* array, String* name) {
1343 // Uses only lower 32 bits if pointers are larger.
1344 uintptr_t array_hash =
1345 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(array)) >> 2;
1346 uintptr_t name_hash =
1347 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >> 2;
1348 return (array_hash ^ name_hash) % kLength;
1349 }
1350
1351 static const int kLength = 64;
1352 struct Key {
1353 DescriptorArray* array;
1354 String* name;
1355 };
1356
1357 static Key keys_[kLength];
1358 static int results_[kLength];
1359};
1360
1361
1362// ----------------------------------------------------------------------------
1363// Marking stack for tracing live objects.
1364
1365class MarkingStack {
1366 public:
1367 void Initialize(Address low, Address high) {
1368 top_ = low_ = reinterpret_cast<HeapObject**>(low);
1369 high_ = reinterpret_cast<HeapObject**>(high);
1370 overflowed_ = false;
1371 }
1372
1373 bool is_full() { return top_ >= high_; }
1374
1375 bool is_empty() { return top_ <= low_; }
1376
1377 bool overflowed() { return overflowed_; }
1378
1379 void clear_overflowed() { overflowed_ = false; }
1380
1381 // Push the (marked) object on the marking stack if there is room,
1382 // otherwise mark the object as overflowed and wait for a rescan of the
1383 // heap.
1384 void Push(HeapObject* object) {
1385 CHECK(object->IsHeapObject());
1386 if (is_full()) {
1387 object->SetOverflow();
1388 overflowed_ = true;
1389 } else {
1390 *(top_++) = object;
1391 }
1392 }
1393
1394 HeapObject* Pop() {
1395 ASSERT(!is_empty());
1396 HeapObject* object = *(--top_);
1397 CHECK(object->IsHeapObject());
1398 return object;
1399 }
1400
1401 private:
1402 HeapObject** low_;
1403 HeapObject** top_;
1404 HeapObject** high_;
1405 bool overflowed_;
1406};
1407
1408
1409// A helper class to document/test C++ scopes where we do not
1410// expect a GC. Usage:
1411//
1412// /* Allocation not allowed: we cannot handle a GC in this scope. */
1413// { AssertNoAllocation nogc;
1414// ...
1415// }
1416
1417#ifdef DEBUG
1418
1419class DisallowAllocationFailure {
1420 public:
1421 DisallowAllocationFailure() {
1422 old_state_ = Heap::disallow_allocation_failure_;
1423 Heap::disallow_allocation_failure_ = true;
1424 }
1425 ~DisallowAllocationFailure() {
1426 Heap::disallow_allocation_failure_ = old_state_;
1427 }
1428 private:
1429 bool old_state_;
1430};
1431
1432class AssertNoAllocation {
1433 public:
1434 AssertNoAllocation() {
1435 old_state_ = Heap::allow_allocation(false);
1436 }
1437
1438 ~AssertNoAllocation() {
1439 Heap::allow_allocation(old_state_);
1440 }
1441
1442 private:
1443 bool old_state_;
1444};
1445
1446class DisableAssertNoAllocation {
1447 public:
1448 DisableAssertNoAllocation() {
1449 old_state_ = Heap::allow_allocation(true);
1450 }
1451
1452 ~DisableAssertNoAllocation() {
1453 Heap::allow_allocation(old_state_);
1454 }
1455
1456 private:
1457 bool old_state_;
1458};
1459
1460#else // ndef DEBUG
1461
1462class AssertNoAllocation {
1463 public:
1464 AssertNoAllocation() { }
1465 ~AssertNoAllocation() { }
1466};
1467
1468class DisableAssertNoAllocation {
1469 public:
1470 DisableAssertNoAllocation() { }
1471 ~DisableAssertNoAllocation() { }
1472};
1473
1474#endif
1475
1476// GCTracer collects and prints ONE line after each garbage collector
1477// invocation IFF --trace_gc is used.
1478
1479class GCTracer BASE_EMBEDDED {
1480 public:
1481 GCTracer();
1482
1483 ~GCTracer();
1484
1485 // Sets the collector.
1486 void set_collector(GarbageCollector collector) { collector_ = collector; }
1487
1488 // Sets the GC count.
1489 void set_gc_count(int count) { gc_count_ = count; }
1490
1491 // Sets the full GC count.
1492 void set_full_gc_count(int count) { full_gc_count_ = count; }
1493
1494 // Sets the flag that this is a compacting full GC.
1495 void set_is_compacting() { is_compacting_ = true; }
1496
1497 // Increment and decrement the count of marked objects.
1498 void increment_marked_count() { ++marked_count_; }
1499 void decrement_marked_count() { --marked_count_; }
1500
1501 int marked_count() { return marked_count_; }
1502
1503 private:
1504 // Returns a string matching the collector.
1505 const char* CollectorString();
1506
1507 // Returns size of object in heap (in MB).
1508 double SizeOfHeapObjects() {
1509 return (static_cast<double>(Heap::SizeOfObjects())) / MB;
1510 }
1511
1512 double start_time_; // Timestamp set in the constructor.
1513 double start_size_; // Size of objects in heap set in constructor.
1514 GarbageCollector collector_; // Type of collector.
1515
1516 // A count (including this one, eg, the first collection is 1) of the
1517 // number of garbage collections.
1518 int gc_count_;
1519
1520 // A count (including this one) of the number of full garbage collections.
1521 int full_gc_count_;
1522
1523 // True if the current GC is a compacting full collection, false
1524 // otherwise.
1525 bool is_compacting_;
1526
1527 // True if the *previous* full GC cwas a compacting collection (will be
1528 // false if there has not been a previous full GC).
1529 bool previous_has_compacted_;
1530
1531 // On a full GC, a count of the number of marked objects. Incremented
1532 // when an object is marked and decremented when an object's mark bit is
1533 // cleared. Will be zero on a scavenge collection.
1534 int marked_count_;
1535
1536 // The count from the end of the previous full GC. Will be zero if there
1537 // was no previous full GC.
1538 int previous_marked_count_;
1539};
1540
1541
1542class TranscendentalCache {
1543 public:
1544 enum Type {ACOS, ASIN, ATAN, COS, EXP, LOG, SIN, TAN, kNumberOfCaches};
1545
1546 explicit TranscendentalCache(Type t);
1547
1548 // Returns a heap number with f(input), where f is a math function specified
1549 // by the 'type' argument.
1550 static inline Object* Get(Type type, double input) {
1551 TranscendentalCache* cache = caches_[type];
1552 if (cache == NULL) {
1553 caches_[type] = cache = new TranscendentalCache(type);
1554 }
1555 return cache->Get(input);
1556 }
1557
1558 // The cache contains raw Object pointers. This method disposes of
1559 // them before a garbage collection.
1560 static void Clear();
1561
1562 private:
1563 inline Object* Get(double input) {
1564 Converter c;
1565 c.dbl = input;
1566 int hash = Hash(c);
1567 Element e = elements_[hash];
1568 if (e.in[0] == c.integers[0] &&
1569 e.in[1] == c.integers[1]) {
1570 ASSERT(e.output != NULL);
1571 return e.output;
1572 }
1573 double answer = Calculate(input);
1574 Object* heap_number = Heap::AllocateHeapNumber(answer);
1575 if (!heap_number->IsFailure()) {
1576 elements_[hash].in[0] = c.integers[0];
1577 elements_[hash].in[1] = c.integers[1];
1578 elements_[hash].output = heap_number;
1579 }
1580 return heap_number;
1581 }
1582
1583 inline double Calculate(double input) {
1584 switch (type_) {
1585 case ACOS:
1586 return acos(input);
1587 case ASIN:
1588 return asin(input);
1589 case ATAN:
1590 return atan(input);
1591 case COS:
1592 return cos(input);
1593 case EXP:
1594 return exp(input);
1595 case LOG:
1596 return log(input);
1597 case SIN:
1598 return sin(input);
1599 case TAN:
1600 return tan(input);
1601 default:
1602 return 0.0; // Never happens.
1603 }
1604 }
1605 static const int kCacheSize = 512;
1606 struct Element {
1607 uint32_t in[2];
1608 Object* output;
1609 };
1610 union Converter {
1611 double dbl;
1612 uint32_t integers[2];
1613 };
1614 inline static int Hash(const Converter& c) {
1615 uint32_t hash = (c.integers[0] ^ c.integers[1]);
1616 hash ^= hash >> 16;
1617 hash ^= hash >> 8;
1618 return (hash & (kCacheSize - 1));
1619 }
1620 static TranscendentalCache* caches_[kNumberOfCaches];
1621 Element elements_[kCacheSize];
1622 Type type_;
1623};
1624
1625
1626} } // namespace v8::internal
1627
1628#endif // V8_HEAP_H_