1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_HEAP_HEAP_H_
6 #define V8_HEAP_HEAP_H_
11 #include "src/allocation.h"
12 #include "src/assert-scope.h"
13 #include "src/globals.h"
14 #include "src/heap/gc-idle-time-handler.h"
15 #include "src/heap/incremental-marking.h"
16 #include "src/heap/mark-compact.h"
17 #include "src/heap/objects-visiting.h"
18 #include "src/heap/spaces.h"
19 #include "src/heap/store-buffer.h"
25 // Defines all the roots in Heap.
26 #define STRONG_ROOT_LIST(V) \
27 V(Map, byte_array_map, ByteArrayMap) \
28 V(Map, free_space_map, FreeSpaceMap) \
29 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
30 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
31 /* Cluster the most popular ones in a few cache lines here at the top. */ \
32 V(Smi, store_buffer_top, StoreBufferTop) \
33 V(Oddball, undefined_value, UndefinedValue) \
34 V(Oddball, the_hole_value, TheHoleValue) \
35 V(Oddball, null_value, NullValue) \
36 V(Oddball, true_value, TrueValue) \
37 V(Oddball, false_value, FalseValue) \
38 V(String, empty_string, empty_string) \
39 V(String, hidden_string, hidden_string) \
40 V(Oddball, uninitialized_value, UninitializedValue) \
41 V(Map, cell_map, CellMap) \
42 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
43 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
44 V(Map, meta_map, MetaMap) \
45 V(Map, heap_number_map, HeapNumberMap) \
46 V(Map, mutable_heap_number_map, MutableHeapNumberMap) \
47 V(Map, float32x4_map, Float32x4Map) \
48 V(Map, int32x4_map, Int32x4Map) \
49 V(Map, uint32x4_map, Uint32x4Map) \
50 V(Map, bool32x4_map, Bool32x4Map) \
51 V(Map, int16x8_map, Int16x8Map) \
52 V(Map, uint16x8_map, Uint16x8Map) \
53 V(Map, bool16x8_map, Bool16x8Map) \
54 V(Map, int8x16_map, Int8x16Map) \
55 V(Map, uint8x16_map, Uint8x16Map) \
56 V(Map, bool8x16_map, Bool8x16Map) \
57 V(Map, native_context_map, NativeContextMap) \
58 V(Map, fixed_array_map, FixedArrayMap) \
59 V(Map, code_map, CodeMap) \
60 V(Map, scope_info_map, ScopeInfoMap) \
61 V(Map, fixed_cow_array_map, FixedCOWArrayMap) \
62 V(Map, fixed_double_array_map, FixedDoubleArrayMap) \
63 V(Map, weak_cell_map, WeakCellMap) \
64 V(Map, one_byte_string_map, OneByteStringMap) \
65 V(Map, one_byte_internalized_string_map, OneByteInternalizedStringMap) \
66 V(Map, function_context_map, FunctionContextMap) \
67 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
68 V(ByteArray, empty_byte_array, EmptyByteArray) \
69 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
70 /* The roots above this line should be boring from a GC point of view. */ \
71 /* This means they are never in new space and never on a page that is */ \
72 /* being compacted. */ \
73 V(Oddball, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
74 V(Oddball, arguments_marker, ArgumentsMarker) \
75 V(Oddball, exception, Exception) \
76 V(Oddball, termination_exception, TerminationException) \
77 V(FixedArray, number_string_cache, NumberStringCache) \
78 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
79 V(Object, instanceof_cache_map, InstanceofCacheMap) \
80 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
81 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
82 V(FixedArray, string_split_cache, StringSplitCache) \
83 V(FixedArray, regexp_multiple_cache, RegExpMultipleCache) \
84 V(Smi, hash_seed, HashSeed) \
85 V(Map, hash_table_map, HashTableMap) \
86 V(Map, ordered_hash_table_map, OrderedHashTableMap) \
87 V(Map, symbol_map, SymbolMap) \
88 V(Map, string_map, StringMap) \
89 V(Map, cons_one_byte_string_map, ConsOneByteStringMap) \
90 V(Map, cons_string_map, ConsStringMap) \
91 V(Map, sliced_string_map, SlicedStringMap) \
92 V(Map, sliced_one_byte_string_map, SlicedOneByteStringMap) \
93 V(Map, external_string_map, ExternalStringMap) \
94 V(Map, external_string_with_one_byte_data_map, \
95 ExternalStringWithOneByteDataMap) \
96 V(Map, external_one_byte_string_map, ExternalOneByteStringMap) \
97 V(Map, native_source_string_map, NativeSourceStringMap) \
98 V(Map, short_external_string_map, ShortExternalStringMap) \
99 V(Map, short_external_string_with_one_byte_data_map, \
100 ShortExternalStringWithOneByteDataMap) \
101 V(Map, internalized_string_map, InternalizedStringMap) \
102 V(Map, external_internalized_string_map, ExternalInternalizedStringMap) \
103 V(Map, external_internalized_string_with_one_byte_data_map, \
104 ExternalInternalizedStringWithOneByteDataMap) \
105 V(Map, external_one_byte_internalized_string_map, \
106 ExternalOneByteInternalizedStringMap) \
107 V(Map, short_external_internalized_string_map, \
108 ShortExternalInternalizedStringMap) \
109 V(Map, short_external_internalized_string_with_one_byte_data_map, \
110 ShortExternalInternalizedStringWithOneByteDataMap) \
111 V(Map, short_external_one_byte_internalized_string_map, \
112 ShortExternalOneByteInternalizedStringMap) \
113 V(Map, short_external_one_byte_string_map, ShortExternalOneByteStringMap) \
114 V(Map, fixed_uint8_array_map, FixedUint8ArrayMap) \
115 V(Map, fixed_int8_array_map, FixedInt8ArrayMap) \
116 V(Map, fixed_uint16_array_map, FixedUint16ArrayMap) \
117 V(Map, fixed_int16_array_map, FixedInt16ArrayMap) \
118 V(Map, fixed_uint32_array_map, FixedUint32ArrayMap) \
119 V(Map, fixed_int32_array_map, FixedInt32ArrayMap) \
120 V(Map, fixed_float32_array_map, FixedFloat32ArrayMap) \
121 V(Map, fixed_float64_array_map, FixedFloat64ArrayMap) \
122 V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap) \
123 V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array) \
124 V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array) \
125 V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array) \
126 V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array) \
127 V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array) \
128 V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array) \
129 V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array) \
130 V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array) \
131 V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array, \
132 EmptyFixedUint8ClampedArray) \
133 V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap) \
134 V(Map, catch_context_map, CatchContextMap) \
135 V(Map, with_context_map, WithContextMap) \
136 V(Map, block_context_map, BlockContextMap) \
137 V(Map, module_context_map, ModuleContextMap) \
138 V(Map, script_context_map, ScriptContextMap) \
139 V(Map, script_context_table_map, ScriptContextTableMap) \
140 V(Map, undefined_map, UndefinedMap) \
141 V(Map, the_hole_map, TheHoleMap) \
142 V(Map, null_map, NullMap) \
143 V(Map, boolean_map, BooleanMap) \
144 V(Map, uninitialized_map, UninitializedMap) \
145 V(Map, arguments_marker_map, ArgumentsMarkerMap) \
146 V(Map, no_interceptor_result_sentinel_map, NoInterceptorResultSentinelMap) \
147 V(Map, exception_map, ExceptionMap) \
148 V(Map, termination_exception_map, TerminationExceptionMap) \
149 V(Map, message_object_map, JSMessageObjectMap) \
150 V(Map, foreign_map, ForeignMap) \
151 V(Map, neander_map, NeanderMap) \
152 V(Map, external_map, ExternalMap) \
153 V(HeapNumber, nan_value, NanValue) \
154 V(HeapNumber, infinity_value, InfinityValue) \
155 V(HeapNumber, minus_zero_value, MinusZeroValue) \
156 V(HeapNumber, minus_infinity_value, MinusInfinityValue) \
157 V(JSObject, message_listeners, MessageListeners) \
158 V(UnseededNumberDictionary, code_stubs, CodeStubs) \
159 V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
160 V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache) \
161 V(Code, js_entry_code, JsEntryCode) \
162 V(Code, js_construct_entry_code, JsConstructEntryCode) \
163 V(FixedArray, natives_source_cache, NativesSourceCache) \
164 V(FixedArray, experimental_natives_source_cache, \
165 ExperimentalNativesSourceCache) \
166 V(FixedArray, extra_natives_source_cache, ExtraNativesSourceCache) \
167 V(FixedArray, experimental_extra_natives_source_cache, \
168 ExperimentalExtraNativesSourceCache) \
169 V(FixedArray, code_stub_natives_source_cache, CodeStubNativesSourceCache) \
170 V(Script, empty_script, EmptyScript) \
171 V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames) \
172 V(Cell, undefined_cell, UndefinedCell) \
173 V(JSObject, observation_state, ObservationState) \
174 V(Object, symbol_registry, SymbolRegistry) \
175 V(Object, script_list, ScriptList) \
176 V(SeededNumberDictionary, empty_slow_element_dictionary, \
177 EmptySlowElementDictionary) \
178 V(FixedArray, materialized_objects, MaterializedObjects) \
179 V(FixedArray, allocation_sites_scratchpad, AllocationSitesScratchpad) \
180 V(FixedArray, microtask_queue, MicrotaskQueue) \
181 V(FixedArray, dummy_vector, DummyVector) \
182 V(FixedArray, detached_contexts, DetachedContexts) \
183 V(ArrayList, retained_maps, RetainedMaps) \
184 V(WeakHashTable, weak_object_to_code_table, WeakObjectToCodeTable) \
185 V(PropertyCell, array_protector, ArrayProtector) \
186 V(PropertyCell, empty_property_cell, EmptyPropertyCell) \
187 V(Object, weak_stack_trace_list, WeakStackTraceList) \
188 V(Object, code_stub_context, CodeStubContext) \
189 V(JSObject, code_stub_exports_object, CodeStubExportsObject) \
190 V(FixedArray, interpreter_table, InterpreterTable) \
191 V(Map, bytecode_array_map, BytecodeArrayMap) \
192 V(BytecodeArray, empty_bytecode_array, EmptyBytecodeArray)
195 // Entries in this list are limited to Smis and are not visited during GC.
196 #define SMI_ROOT_LIST(V) \
197 V(Smi, stack_limit, StackLimit) \
198 V(Smi, real_stack_limit, RealStackLimit) \
199 V(Smi, last_script_id, LastScriptId) \
200 V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset) \
201 V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset) \
202 V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset) \
203 V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
206 #define ROOT_LIST(V) \
207 STRONG_ROOT_LIST(V) \
209 V(StringTable, string_table, StringTable)
211 #define INTERNALIZED_STRING_LIST(V) \
212 V(Object_string, "Object") \
213 V(proto_string, "__proto__") \
214 V(arguments_string, "arguments") \
215 V(Arguments_string, "Arguments") \
216 V(caller_string, "caller") \
217 V(boolean_string, "boolean") \
218 V(Boolean_string, "Boolean") \
219 V(callee_string, "callee") \
220 V(constructor_string, "constructor") \
221 V(dot_result_string, ".result") \
222 V(eval_string, "eval") \
223 V(float32x4_string, "float32x4") \
224 V(Float32x4_string, "Float32x4") \
225 V(int32x4_string, "int32x4") \
226 V(Int32x4_string, "Int32x4") \
227 V(uint32x4_string, "uint32x4") \
228 V(Uint32x4_string, "Uint32x4") \
229 V(bool32x4_string, "bool32x4") \
230 V(Bool32x4_string, "Bool32x4") \
231 V(int16x8_string, "int16x8") \
232 V(Int16x8_string, "Int16x8") \
233 V(uint16x8_string, "uint16x8") \
234 V(Uint16x8_string, "Uint16x8") \
235 V(bool16x8_string, "bool16x8") \
236 V(Bool16x8_string, "Bool16x8") \
237 V(int8x16_string, "int8x16") \
238 V(Int8x16_string, "Int8x16") \
239 V(uint8x16_string, "uint8x16") \
240 V(Uint8x16_string, "Uint8x16") \
241 V(bool8x16_string, "bool8x16") \
242 V(Bool8x16_string, "Bool8x16") \
243 V(function_string, "function") \
244 V(Function_string, "Function") \
245 V(length_string, "length") \
246 V(name_string, "name") \
247 V(null_string, "null") \
248 V(number_string, "number") \
249 V(Number_string, "Number") \
250 V(nan_string, "NaN") \
251 V(source_string, "source") \
252 V(source_url_string, "source_url") \
253 V(source_mapping_url_string, "source_mapping_url") \
254 V(this_string, "this") \
255 V(global_string, "global") \
256 V(ignore_case_string, "ignoreCase") \
257 V(multiline_string, "multiline") \
258 V(sticky_string, "sticky") \
259 V(unicode_string, "unicode") \
260 V(harmony_regexps_string, "harmony_regexps") \
261 V(harmony_tostring_string, "harmony_tostring") \
262 V(harmony_unicode_regexps_string, "harmony_unicode_regexps") \
263 V(input_string, "input") \
264 V(index_string, "index") \
265 V(last_index_string, "lastIndex") \
266 V(object_string, "object") \
267 V(prototype_string, "prototype") \
268 V(string_string, "string") \
269 V(String_string, "String") \
270 V(symbol_string, "symbol") \
271 V(Symbol_string, "Symbol") \
272 V(Map_string, "Map") \
273 V(Set_string, "Set") \
274 V(WeakMap_string, "WeakMap") \
275 V(WeakSet_string, "WeakSet") \
276 V(for_string, "for") \
277 V(for_api_string, "for_api") \
278 V(Date_string, "Date") \
279 V(char_at_string, "CharAt") \
280 V(undefined_string, "undefined") \
281 V(value_of_string, "valueOf") \
282 V(stack_string, "stack") \
283 V(toJSON_string, "toJSON") \
284 V(KeyedLoadMonomorphic_string, "KeyedLoadMonomorphic") \
285 V(KeyedStoreMonomorphic_string, "KeyedStoreMonomorphic") \
286 V(illegal_access_string, "illegal access") \
287 V(cell_value_string, "%cell_value") \
288 V(illegal_argument_string, "illegal argument") \
289 V(closure_string, "(closure)") \
291 V(compare_ic_string, "==") \
292 V(strict_compare_ic_string, "===") \
293 V(infinity_string, "Infinity") \
294 V(minus_infinity_string, "-Infinity") \
295 V(query_colon_string, "(?:)") \
296 V(Generator_string, "Generator") \
297 V(throw_string, "throw") \
298 V(done_string, "done") \
299 V(value_string, "value") \
300 V(next_string, "next") \
301 V(byte_length_string, "byteLength") \
302 V(byte_offset_string, "byteOffset") \
303 V(minus_zero_string, "-0") \
304 V(Array_string, "Array") \
305 V(Error_string, "Error") \
306 V(RegExp_string, "RegExp")
308 #define PRIVATE_SYMBOL_LIST(V) \
309 V(array_iteration_kind_symbol) \
310 V(array_iterator_next_symbol) \
311 V(array_iterator_object_symbol) \
312 V(call_site_function_symbol) \
313 V(call_site_position_symbol) \
314 V(call_site_receiver_symbol) \
315 V(call_site_strict_symbol) \
316 V(class_end_position_symbol) \
317 V(class_start_position_symbol) \
318 V(detailed_stack_trace_symbol) \
319 V(elements_transition_symbol) \
320 V(error_end_pos_symbol) \
321 V(error_script_symbol) \
322 V(error_start_pos_symbol) \
323 V(formatted_stack_trace_symbol) \
325 V(hash_code_symbol) \
326 V(home_object_symbol) \
327 V(internal_error_symbol) \
328 V(intl_impl_object_symbol) \
329 V(intl_initialized_marker_symbol) \
330 V(megamorphic_symbol) \
331 V(nonexistent_symbol) \
332 V(nonextensible_symbol) \
333 V(normal_ic_symbol) \
335 V(premonomorphic_symbol) \
336 V(promise_debug_marker_symbol) \
337 V(promise_has_handler_symbol) \
338 V(promise_on_resolve_symbol) \
339 V(promise_on_reject_symbol) \
340 V(promise_raw_symbol) \
341 V(promise_status_symbol) \
342 V(promise_value_symbol) \
344 V(stack_trace_symbol) \
345 V(string_iterator_iterated_string_symbol) \
346 V(string_iterator_next_index_symbol) \
347 V(uninitialized_symbol)
350 #define PUBLIC_SYMBOL_LIST(V) \
351 V(has_instance_symbol, symbolHasInstance, Symbol.hasInstance) \
352 V(is_concat_spreadable_symbol, symbolIsConcatSpreadable, \
353 Symbol.isConcatSpreadable) \
354 V(is_regexp_symbol, symbolIsRegExp, Symbol.isRegExp) \
355 V(iterator_symbol, symbolIterator, Symbol.iterator) \
356 V(to_string_tag_symbol, symbolToStringTag, Symbol.toStringTag) \
357 V(unscopables_symbol, symbolUnscopables, Symbol.unscopables)
359 // Heap roots that are known to be immortal immovable, for which we can safely
360 // skip write barriers. This list is not complete and has omissions.
361 #define IMMORTAL_IMMOVABLE_ROOT_LIST(V) \
363 V(BytecodeArrayMap) \
365 V(OnePointerFillerMap) \
366 V(TwoPointerFillerMap) \
372 V(UninitializedValue) \
374 V(GlobalPropertyCellMap) \
375 V(SharedFunctionInfoMap) \
378 V(MutableHeapNumberMap) \
389 V(NativeContextMap) \
393 V(FixedCOWArrayMap) \
394 V(FixedDoubleArrayMap) \
396 V(NoInterceptorResultSentinel) \
398 V(OrderedHashTableMap) \
401 V(EmptyBytecodeArray) \
402 V(EmptyDescriptorArray) \
405 V(SloppyArgumentsElementsMap) \
406 V(FunctionContextMap) \
410 V(ModuleContextMap) \
411 V(ScriptContextMap) \
416 V(UninitializedMap) \
417 V(ArgumentsMarkerMap) \
418 V(JSMessageObjectMap) \
422 PRIVATE_SYMBOL_LIST(V)
424 // Forward declarations.
428 class WeakObjectRetainer;
431 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
435 // A queue of objects promoted during scavenge. Each object is accompanied
436 // by it's size to avoid dereferencing a map pointer for scanning.
437 // The last page in to-space is used for the promotion queue. On conflict
438 // during scavenge, the promotion queue is allocated externally and all
439 // entries are copied to the external queue.
440 class PromotionQueue {
442 explicit PromotionQueue(Heap* heap)
453 delete emergency_stack_;
454 emergency_stack_ = NULL;
457 Page* GetHeadPage() {
458 return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
461 void SetNewLimit(Address limit) {
462 // If we are already using an emergency stack, we can ignore it.
463 if (emergency_stack_) return;
465 // If the limit is not on the same page, we can ignore it.
466 if (Page::FromAllocationTop(limit) != GetHeadPage()) return;
468 limit_ = reinterpret_cast<intptr_t*>(limit);
470 if (limit_ <= rear_) {
477 bool IsBelowPromotionQueue(Address to_space_top) {
478 // If an emergency stack is used, the to-space address cannot interfere
479 // with the promotion queue.
480 if (emergency_stack_) return true;
482 // If the given to-space top pointer and the head of the promotion queue
483 // are not on the same page, then the to-space objects are below the
485 if (GetHeadPage() != Page::FromAddress(to_space_top)) {
488 // If the to space top pointer is smaller or equal than the promotion
489 // queue head, then the to-space objects are below the promotion queue.
490 return reinterpret_cast<intptr_t*>(to_space_top) <= rear_;
494 return (front_ == rear_) &&
495 (emergency_stack_ == NULL || emergency_stack_->length() == 0);
498 inline void insert(HeapObject* target, int size);
500 void remove(HeapObject** target, int* size) {
502 if (front_ == rear_) {
503 Entry e = emergency_stack_->RemoveLast();
509 *target = reinterpret_cast<HeapObject*>(*(--front_));
510 *size = static_cast<int>(*(--front_));
511 // Assert no underflow.
512 SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
513 reinterpret_cast<Address>(front_));
517 // The front of the queue is higher in the memory page chain than the rear.
522 static const int kEntrySizeInWords = 2;
525 Entry(HeapObject* obj, int size) : obj_(obj), size_(size) {}
530 List<Entry>* emergency_stack_;
534 void RelocateQueueHead();
536 DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
540 typedef void (*ScavengingCallback)(Map* map, HeapObject** slot,
544 // External strings table is a place where all external strings are
545 // registered. We need to keep track of such strings to properly
547 class ExternalStringTable {
549 // Registers an external string.
550 inline void AddString(String* string);
552 inline void Iterate(ObjectVisitor* v);
554 // Restores internal invariant and gets rid of collected strings.
555 // Must be called after each Iterate() that modified the strings.
558 // Destroys all allocated memory.
562 explicit ExternalStringTable(Heap* heap) : heap_(heap) {}
566 inline void Verify();
568 inline void AddOldString(String* string);
570 // Notifies the table that only a prefix of the new list is valid.
571 inline void ShrinkNewStrings(int position);
573 // To speed up scavenge collections new space string are kept
574 // separate from old space strings.
575 List<Object*> new_space_strings_;
576 List<Object*> old_space_strings_;
580 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
584 enum ArrayStorageAllocationMode {
585 DONT_INITIALIZE_ARRAY_ELEMENTS,
586 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
592 // Configure heap size in MB before setup. Return false if the heap has been
594 bool ConfigureHeap(int max_semi_space_size, int max_old_space_size,
595 int max_executable_size, size_t code_range_size);
596 bool ConfigureHeapDefault();
598 // Prepares the heap, setting up memory areas that are needed in the isolate
599 // without actually creating any objects.
602 // Bootstraps the object heap with the core set of objects required to run.
603 // Returns whether it succeeded.
604 bool CreateHeapObjects();
606 // Destroys all memory allocated by the heap.
609 // Set the stack limit in the roots_ array. Some architectures generate
610 // code that looks here, because it is faster than loading from the static
611 // jslimit_/real_jslimit_ variable in the StackGuard.
612 void SetStackLimits();
614 // Notifies the heap that is ok to start marking or other activities that
615 // should not happen during deserialization.
616 void NotifyDeserializationComplete();
618 // Returns whether SetUp has been called.
621 // Returns the maximum amount of memory reserved for the heap. For
622 // the young generation, we reserve 4 times the amount needed for a
623 // semi space. The young generation consists of two semi spaces and
624 // we reserve twice the amount needed for those in order to ensure
625 // that new space can be aligned to its size.
626 intptr_t MaxReserved() {
627 return 4 * reserved_semispace_size_ + max_old_generation_size_;
629 int MaxSemiSpaceSize() { return max_semi_space_size_; }
630 int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
631 int InitialSemiSpaceSize() { return initial_semispace_size_; }
632 int TargetSemiSpaceSize() { return target_semispace_size_; }
633 intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
634 intptr_t MaxExecutableSize() { return max_executable_size_; }
636 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
637 // more spaces are needed until it reaches the limit.
640 // Returns the amount of memory currently committed for the heap.
641 intptr_t CommittedMemory();
643 // Returns the amount of memory currently committed for the old space.
644 intptr_t CommittedOldGenerationMemory();
646 // Returns the amount of executable memory currently committed for the heap.
647 intptr_t CommittedMemoryExecutable();
649 // Returns the amount of phyical memory currently committed for the heap.
650 size_t CommittedPhysicalMemory();
652 // Returns the maximum amount of memory ever committed for the heap.
653 intptr_t MaximumCommittedMemory() { return maximum_committed_; }
655 // Updates the maximum committed memory for the heap. Should be called
656 // whenever a space grows.
657 void UpdateMaximumCommitted();
659 // Returns the available bytes in space w/o growing.
660 // Heap doesn't guarantee that it can allocate an object that requires
661 // all available bytes. Check MaxHeapObjectSize() instead.
662 intptr_t Available();
664 // Returns of size of all objects residing in the heap.
665 intptr_t SizeOfObjects();
667 intptr_t old_generation_allocation_limit() const {
668 return old_generation_allocation_limit_;
671 // Return the starting address and a mask for the new space. And-masking an
672 // address with the mask will result in the start address of the new space
673 // for all addresses in either semispace.
674 Address NewSpaceStart() { return new_space_.start(); }
675 uintptr_t NewSpaceMask() { return new_space_.mask(); }
676 Address NewSpaceTop() { return new_space_.top(); }
678 NewSpace* new_space() { return &new_space_; }
679 OldSpace* old_space() { return old_space_; }
680 OldSpace* code_space() { return code_space_; }
681 MapSpace* map_space() { return map_space_; }
682 LargeObjectSpace* lo_space() { return lo_space_; }
683 PagedSpace* paged_space(int idx) {
697 Space* space(int idx) {
704 return paged_space(idx);
708 // Returns name of the space.
709 const char* GetSpaceName(int idx);
711 bool always_allocate() { return always_allocate_scope_depth_ != 0; }
712 Address always_allocate_scope_depth_address() {
713 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
716 Address* NewSpaceAllocationTopAddress() {
717 return new_space_.allocation_top_address();
719 Address* NewSpaceAllocationLimitAddress() {
720 return new_space_.allocation_limit_address();
723 Address* OldSpaceAllocationTopAddress() {
724 return old_space_->allocation_top_address();
726 Address* OldSpaceAllocationLimitAddress() {
727 return old_space_->allocation_limit_address();
730 // TODO(hpayer): There is still a missmatch between capacity and actual
731 // committed memory size.
732 bool CanExpandOldGeneration(int size) {
733 return (CommittedOldGenerationMemory() + size) < MaxOldGenerationSize();
736 // Returns a deep copy of the JavaScript object.
737 // Properties and elements are copied too.
738 // Optionally takes an AllocationSite to be appended in an AllocationMemento.
739 MUST_USE_RESULT AllocationResult
740 CopyJSObject(JSObject* source, AllocationSite* site = NULL);
742 // Calculates the maximum amount of filler that could be required by the
744 static int GetMaximumFillToAlign(AllocationAlignment alignment);
745 // Calculates the actual amount of filler required for a given address at the
747 static int GetFillToAlign(Address address, AllocationAlignment alignment);
749 // Creates a filler object and returns a heap object immediately after it.
750 MUST_USE_RESULT HeapObject* PrecedeWithFiller(HeapObject* object,
752 // Creates a filler object if needed for alignment and returns a heap object
753 // immediately after it. If any space is left after the returned object,
754 // another filler object is created so the over allocated memory is iterable.
755 MUST_USE_RESULT HeapObject* AlignWithFiller(HeapObject* object,
758 AllocationAlignment alignment);
760 // Clear the Instanceof cache (used when a prototype changes).
761 inline void ClearInstanceofCache();
763 // Iterates the whole code space to clear all ICs of the given kind.
764 void ClearAllICsByKind(Code::Kind kind);
766 // FreeSpace objects have a null map after deserialization. Update the map.
767 void RepairFreeListsAfterDeserialization();
769 template <typename T>
770 static inline bool IsOneByte(T t, int chars);
772 // Move len elements within a given array from src_index index to dst_index
774 void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
776 // Sloppy mode arguments object size.
777 static const int kSloppyArgumentsObjectSize =
778 JSObject::kHeaderSize + 2 * kPointerSize;
779 // Strict mode arguments has no callee so it is smaller.
780 static const int kStrictArgumentsObjectSize =
781 JSObject::kHeaderSize + 1 * kPointerSize;
782 // Indicies for direct access into argument objects.
783 static const int kArgumentsLengthIndex = 0;
784 // callee is only valid in sloppy mode.
785 static const int kArgumentsCalleeIndex = 1;
787 // Finalizes an external string by deleting the associated external
788 // data and clearing the resource pointer.
789 inline void FinalizeExternalString(String* string);
791 // Initialize a filler object to keep the ability to iterate over the heap
792 // when introducing gaps within pages.
793 void CreateFillerObjectAt(Address addr, int size);
795 bool CanMoveObjectStart(HeapObject* object);
797 // Indicates whether live bytes adjustment is triggered
798 // - from within the GC code before sweeping started (SEQUENTIAL_TO_SWEEPER),
799 // - or from within GC (CONCURRENT_TO_SWEEPER),
800 // - or mutator code (CONCURRENT_TO_SWEEPER).
801 enum InvocationMode { SEQUENTIAL_TO_SWEEPER, CONCURRENT_TO_SWEEPER };
803 // Maintain consistency of live bytes during incremental marking.
804 void AdjustLiveBytes(HeapObject* object, int by, InvocationMode mode);
806 // Trim the given array from the left. Note that this relocates the object
807 // start and hence is only valid if there is only a single reference to it.
808 FixedArrayBase* LeftTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
810 // Trim the given array from the right.
811 template<Heap::InvocationMode mode>
812 void RightTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
814 // Converts the given boolean condition to JavaScript boolean value.
815 inline Object* ToBoolean(bool condition);
817 // Performs garbage collection operation.
818 // Returns whether there is a chance that another major GC could
819 // collect more garbage.
820 inline bool CollectGarbage(
821 AllocationSpace space, const char* gc_reason = NULL,
822 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
824 static const int kNoGCFlags = 0;
825 static const int kReduceMemoryFootprintMask = 1;
826 static const int kAbortIncrementalMarkingMask = 2;
827 static const int kFinalizeIncrementalMarkingMask = 4;
829 // Making the heap iterable requires us to abort incremental marking.
830 static const int kMakeHeapIterableMask = kAbortIncrementalMarkingMask;
832 // Invoked when GC was requested via the stack guard.
833 void HandleGCRequest();
835 // Attempt to over-approximate the weak closure by marking object groups and
836 // implicit references from global handles, but don't atomically complete
837 // marking. If we continue to mark incrementally, we might have marked
838 // objects that die later.
839 void OverApproximateWeakClosure(const char* gc_reason);
841 // Performs a full garbage collection. If (flags & kMakeHeapIterableMask) is
842 // non-zero, then the slower precise sweeper is used, which leaves the heap
843 // in a state where we can iterate over the heap visiting all objects.
844 void CollectAllGarbage(
845 int flags = kFinalizeIncrementalMarkingMask, const char* gc_reason = NULL,
846 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
848 // Last hope GC, should try to squeeze as much as possible.
849 void CollectAllAvailableGarbage(const char* gc_reason = NULL);
851 // Check whether the heap is currently iterable.
852 bool IsHeapIterable();
854 // Notify the heap that a context has been disposed.
855 int NotifyContextDisposed(bool dependant_context);
857 // Start incremental marking and ensure that idle time handler can perform
858 // incremental steps.
859 void StartIdleIncrementalMarking();
861 // Starts incremental marking assuming incremental marking is currently
863 void StartIncrementalMarking(int gc_flags,
864 const GCCallbackFlags gc_callback_flags,
865 const char* reason = nullptr);
867 // Performs incremental marking steps of step_size_in_bytes as long as
868 // deadline_ins_ms is not reached. step_size_in_bytes can be 0 to compute
869 // an estimate increment. Returns the remaining time that cannot be used
870 // for incremental marking anymore because a single step would exceed the
872 double AdvanceIncrementalMarking(
873 intptr_t step_size_in_bytes, double deadline_in_ms,
874 IncrementalMarking::StepActions step_actions);
876 void FinalizeIncrementalMarkingIfComplete(const char* comment);
878 inline void increment_scan_on_scavenge_pages() {
879 scan_on_scavenge_pages_++;
880 if (FLAG_gc_verbose) {
881 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
885 inline void decrement_scan_on_scavenge_pages() {
886 scan_on_scavenge_pages_--;
887 if (FLAG_gc_verbose) {
888 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
892 PromotionQueue* promotion_queue() { return &promotion_queue_; }
894 void AddGCPrologueCallback(v8::Isolate::GCCallback callback,
895 GCType gc_type_filter, bool pass_isolate = true);
896 void RemoveGCPrologueCallback(v8::Isolate::GCCallback callback);
898 void AddGCEpilogueCallback(v8::Isolate::GCCallback callback,
899 GCType gc_type_filter, bool pass_isolate = true);
900 void RemoveGCEpilogueCallback(v8::Isolate::GCCallback callback);
902 // Heap root getters. We have versions with and without type::cast() here.
903 // You can't use type::cast during GC because the assert fails.
904 // TODO(1490): Try removing the unchecked accessors, now that GC marking does
905 // not corrupt the map.
906 #define ROOT_ACCESSOR(type, name, camel_name) \
907 inline type* name(); \
908 type* raw_unchecked_##name() { \
909 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
911 ROOT_LIST(ROOT_ACCESSOR)
915 #define STRUCT_MAP_ACCESSOR(NAME, Name, name) inline Map* name##_map();
916 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
917 #undef STRUCT_MAP_ACCESSOR
919 #define STRING_ACCESSOR(name, str) inline String* name();
920 INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
921 #undef STRING_ACCESSOR
923 #define SYMBOL_ACCESSOR(name) inline Symbol* name();
924 PRIVATE_SYMBOL_LIST(SYMBOL_ACCESSOR)
925 #undef SYMBOL_ACCESSOR
927 #define SYMBOL_ACCESSOR(name, varname, description) inline Symbol* name();
928 PUBLIC_SYMBOL_LIST(SYMBOL_ACCESSOR)
929 #undef SYMBOL_ACCESSOR
931 void set_native_contexts_list(Object* object) {
932 native_contexts_list_ = object;
934 Object* native_contexts_list() const { return native_contexts_list_; }
936 void set_allocation_sites_list(Object* object) {
937 allocation_sites_list_ = object;
939 Object* allocation_sites_list() { return allocation_sites_list_; }
941 // Used in CreateAllocationSiteStub and the (de)serializer.
942 Object** allocation_sites_list_address() { return &allocation_sites_list_; }
944 void set_encountered_weak_collections(Object* weak_collection) {
945 encountered_weak_collections_ = weak_collection;
947 Object* encountered_weak_collections() const {
948 return encountered_weak_collections_;
951 void set_encountered_weak_cells(Object* weak_cell) {
952 encountered_weak_cells_ = weak_cell;
954 Object* encountered_weak_cells() const { return encountered_weak_cells_; }
956 // Number of mark-sweeps.
957 int ms_count() const { return ms_count_; }
959 // Iterates over all roots in the heap.
960 void IterateRoots(ObjectVisitor* v, VisitMode mode);
961 // Iterates over all strong roots in the heap.
962 void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
963 // Iterates over entries in the smi roots list. Only interesting to the
964 // serializer/deserializer, since GC does not care about smis.
965 void IterateSmiRoots(ObjectVisitor* v);
966 // Iterates over all the other roots in the heap.
967 void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
969 // Iterate pointers to from semispace of new space found in memory interval
970 // from start to end within |object|.
971 void IterateAndMarkPointersToFromSpace(HeapObject* object, Address start,
972 Address end, bool record_slots,
973 ObjectSlotCallback callback);
975 // Returns whether the object resides in new space.
976 inline bool InNewSpace(Object* object);
977 inline bool InNewSpace(Address address);
978 inline bool InNewSpacePage(Address address);
979 inline bool InFromSpace(Object* object);
980 inline bool InToSpace(Object* object);
982 // Returns whether the object resides in old space.
983 inline bool InOldSpace(Address address);
984 inline bool InOldSpace(Object* object);
986 // Checks whether an address/object in the heap (including auxiliary
987 // area and unused area).
988 bool Contains(Address addr);
989 bool Contains(HeapObject* value);
991 // Checks whether an address/object in a space.
992 // Currently used by tests, serialization and heap verification only.
993 bool InSpace(Address addr, AllocationSpace space);
994 bool InSpace(HeapObject* value, AllocationSpace space);
996 // Checks whether the space is valid.
997 static bool IsValidAllocationSpace(AllocationSpace space);
999 // Checks whether the given object is allowed to be migrated from it's
1000 // current space into the given destination space. Used for debugging.
1001 inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
1003 // Sets the stub_cache_ (only used when expanding the dictionary).
1004 void public_set_code_stubs(UnseededNumberDictionary* value) {
1005 roots_[kCodeStubsRootIndex] = value;
1008 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
1009 void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
1010 roots_[kNonMonomorphicCacheRootIndex] = value;
1013 void public_set_empty_script(Script* script) {
1014 roots_[kEmptyScriptRootIndex] = script;
1017 void public_set_store_buffer_top(Address* top) {
1018 roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1021 void public_set_materialized_objects(FixedArray* objects) {
1022 roots_[kMaterializedObjectsRootIndex] = objects;
1025 // Generated code can embed this address to get access to the roots.
1026 Object** roots_array_start() { return roots_; }
1028 Address* store_buffer_top_address() {
1029 return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1032 static bool RootIsImmortalImmovable(int root_index);
1033 void CheckHandleCount();
1036 // Verify the heap is in its normal state before or after a GC.
1042 void PrintHandles();
1044 // Report heap statistics.
1045 void ReportHeapStatistics(const char* title);
1046 void ReportCodeStatistics(const char* title);
1049 // Zapping is needed for verify heap, and always done in debug builds.
1050 static inline bool ShouldZapGarbage() {
1055 return FLAG_verify_heap;
1062 // Number of "runtime allocations" done so far.
1063 uint32_t allocations_count() { return allocations_count_; }
1065 // Returns deterministic "time" value in ms. Works only with
1066 // FLAG_verify_predictable.
1067 double synthetic_time() { return allocations_count_ / 2.0; }
1069 // Print short heap statistics.
1070 void PrintShortHeapStatistics();
1072 size_t object_count_last_gc(size_t index) {
1073 return index < OBJECT_STATS_COUNT ? object_counts_last_time_[index] : 0;
1075 size_t object_size_last_gc(size_t index) {
1076 return index < OBJECT_STATS_COUNT ? object_sizes_last_time_[index] : 0;
1079 // Write barrier support for address[offset] = o.
1080 INLINE(void RecordWrite(Address address, int offset));
1082 // Write barrier support for address[start : start + len[ = o.
1083 INLINE(void RecordWrites(Address address, int start, int len));
1085 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1086 inline HeapState gc_state() { return gc_state_; }
1088 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1091 void set_allocation_timeout(int timeout) { allocation_timeout_ = timeout; }
1093 void TracePathToObjectFrom(Object* target, Object* root);
1094 void TracePathToObject(Object* target);
1095 void TracePathToGlobal();
1098 // Callback function passed to Heap::Iterate etc. Copies an object if
1099 // necessary, the object might be promoted to an old space. The caller must
1100 // ensure the precondition that the object is (a) a heap object and (b) in
1101 // the heap's from space.
1102 static inline void ScavengePointer(HeapObject** p);
1103 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1105 // Slow part of scavenge object.
1106 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
1108 enum ScratchpadSlotMode { IGNORE_SCRATCHPAD_SLOT, RECORD_SCRATCHPAD_SLOT };
1110 // If an object has an AllocationMemento trailing it, return it, otherwise
1112 inline AllocationMemento* FindAllocationMemento(HeapObject* object);
1114 // An object may have an AllocationSite associated with it through a trailing
1115 // AllocationMemento. Its feedback should be updated when objects are found
1117 static inline void UpdateAllocationSiteFeedback(HeapObject* object,
1118 ScratchpadSlotMode mode);
1120 // Support for partial snapshots. After calling this we have a linear
1121 // space to write objects in each space.
1128 typedef List<Chunk> Reservation;
1130 // Returns false if not able to reserve.
1131 bool ReserveSpace(Reservation* reservations);
1134 // Support for the API.
1137 void CreateApiObjects();
1139 inline intptr_t PromotedTotalSize() {
1140 int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1141 if (total > std::numeric_limits<intptr_t>::max()) {
1142 // TODO(erikcorry): Use uintptr_t everywhere we do heap size calculations.
1143 return std::numeric_limits<intptr_t>::max();
1145 if (total < 0) return 0;
1146 return static_cast<intptr_t>(total);
1149 inline intptr_t OldGenerationSpaceAvailable() {
1150 return old_generation_allocation_limit_ - PromotedTotalSize();
1153 inline intptr_t OldGenerationCapacityAvailable() {
1154 return max_old_generation_size_ - PromotedTotalSize();
1157 static const intptr_t kMinimumOldGenerationAllocationLimit =
1158 8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1160 static const int kInitalOldGenerationLimitFactor = 2;
1163 // Don't apply pointer multiplier on Android since it has no swap space and
1164 // should instead adapt it's heap size based on available physical memory.
1165 static const int kPointerMultiplier = 1;
1167 static const int kPointerMultiplier = i::kPointerSize / 4;
1170 // The new space size has to be a power of 2. Sizes are in MB.
1171 static const int kMaxSemiSpaceSizeLowMemoryDevice = 1 * kPointerMultiplier;
1172 static const int kMaxSemiSpaceSizeMediumMemoryDevice = 4 * kPointerMultiplier;
1173 static const int kMaxSemiSpaceSizeHighMemoryDevice = 8 * kPointerMultiplier;
1174 static const int kMaxSemiSpaceSizeHugeMemoryDevice = 8 * kPointerMultiplier;
1176 // The old space size has to be a multiple of Page::kPageSize.
1178 static const int kMaxOldSpaceSizeLowMemoryDevice = 128 * kPointerMultiplier;
1179 static const int kMaxOldSpaceSizeMediumMemoryDevice =
1180 256 * kPointerMultiplier;
1181 static const int kMaxOldSpaceSizeHighMemoryDevice = 512 * kPointerMultiplier;
1182 static const int kMaxOldSpaceSizeHugeMemoryDevice = 700 * kPointerMultiplier;
1184 // The executable size has to be a multiple of Page::kPageSize.
1186 static const int kMaxExecutableSizeLowMemoryDevice = 96 * kPointerMultiplier;
1187 static const int kMaxExecutableSizeMediumMemoryDevice =
1188 192 * kPointerMultiplier;
1189 static const int kMaxExecutableSizeHighMemoryDevice =
1190 256 * kPointerMultiplier;
1191 static const int kMaxExecutableSizeHugeMemoryDevice =
1192 256 * kPointerMultiplier;
1194 static const int kTraceRingBufferSize = 512;
1195 static const int kStacktraceBufferSize = 512;
1197 static const double kMinHeapGrowingFactor;
1198 static const double kMaxHeapGrowingFactor;
1199 static const double kMaxHeapGrowingFactorMemoryConstrained;
1200 static const double kMaxHeapGrowingFactorIdle;
1201 static const double kTargetMutatorUtilization;
1203 static double HeapGrowingFactor(double gc_speed, double mutator_speed);
1205 // Calculates the allocation limit based on a given growing factor and a
1206 // given old generation size.
1207 intptr_t CalculateOldGenerationAllocationLimit(double factor,
1208 intptr_t old_gen_size);
1210 // Sets the allocation limit to trigger the next full garbage collection.
1211 void SetOldGenerationAllocationLimit(intptr_t old_gen_size, double gc_speed,
1212 double mutator_speed);
1214 // Decrease the allocation limit if the new limit based on the given
1215 // parameters is lower than the current limit.
1216 void DampenOldGenerationAllocationLimit(intptr_t old_gen_size,
1218 double mutator_speed);
1220 // Indicates whether inline bump-pointer allocation has been disabled.
1221 bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1223 // Switch whether inline bump-pointer allocation should be used.
1224 void EnableInlineAllocation();
1225 void DisableInlineAllocation();
1227 // Implements the corresponding V8 API function.
1228 bool IdleNotification(double deadline_in_seconds);
1229 bool IdleNotification(int idle_time_in_ms);
1231 double MonotonicallyIncreasingTimeInMs();
1233 // Declare all the root indices. This defines the root list order.
1234 enum RootListIndex {
1235 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1236 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1237 #undef ROOT_INDEX_DECLARATION
1239 #define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
1240 INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
1241 #undef STRING_DECLARATION
1243 #define SYMBOL_INDEX_DECLARATION(name) k##name##RootIndex,
1244 PRIVATE_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1245 #undef SYMBOL_INDEX_DECLARATION
1247 #define SYMBOL_INDEX_DECLARATION(name, varname, description) k##name##RootIndex,
1248 PUBLIC_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1249 #undef SYMBOL_INDEX_DECLARATION
1251 // Utility type maps
1252 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1253 STRUCT_LIST(DECLARE_STRUCT_MAP)
1254 #undef DECLARE_STRUCT_MAP
1255 kStringTableRootIndex,
1257 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1258 SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
1259 #undef ROOT_INDEX_DECLARATION
1261 kStrongRootListLength = kStringTableRootIndex,
1262 kSmiRootsStart = kStringTableRootIndex + 1
1265 Object* root(RootListIndex index) { return roots_[index]; }
1267 STATIC_ASSERT(kUndefinedValueRootIndex ==
1268 Internals::kUndefinedValueRootIndex);
1269 STATIC_ASSERT(kNullValueRootIndex == Internals::kNullValueRootIndex);
1270 STATIC_ASSERT(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1271 STATIC_ASSERT(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1272 STATIC_ASSERT(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
1274 // Generated code can embed direct references to non-writable roots if
1275 // they are in new space.
1276 static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
1277 // Generated code can treat direct references to this root as constant.
1278 bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1280 Map* MapForFixedTypedArray(ExternalArrayType array_type);
1281 RootListIndex RootIndexForFixedTypedArray(ExternalArrayType array_type);
1283 RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1284 FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1286 void RecordStats(HeapStats* stats, bool take_snapshot = false);
1288 // Copy block of memory from src to dst. Size of block should be aligned
1290 static inline void CopyBlock(Address dst, Address src, int byte_size);
1292 // Optimized version of memmove for blocks with pointer size aligned sizes and
1293 // pointer size aligned addresses.
1294 static inline void MoveBlock(Address dst, Address src, int byte_size);
1296 // Check new space expansion criteria and expand semispaces if it was hit.
1297 void CheckNewSpaceExpansionCriteria();
1299 inline void IncrementPromotedObjectsSize(int object_size) {
1300 DCHECK(object_size > 0);
1301 promoted_objects_size_ += object_size;
1304 inline void IncrementSemiSpaceCopiedObjectSize(int object_size) {
1305 DCHECK(object_size > 0);
1306 semi_space_copied_object_size_ += object_size;
1309 inline intptr_t SurvivedNewSpaceObjectSize() {
1310 return promoted_objects_size_ + semi_space_copied_object_size_;
1313 inline void IncrementNodesDiedInNewSpace() { nodes_died_in_new_space_++; }
1315 inline void IncrementNodesCopiedInNewSpace() { nodes_copied_in_new_space_++; }
1317 inline void IncrementNodesPromoted() { nodes_promoted_++; }
1319 inline void IncrementYoungSurvivorsCounter(int survived) {
1320 DCHECK(survived >= 0);
1321 survived_last_scavenge_ = survived;
1322 survived_since_last_expansion_ += survived;
1325 inline bool HeapIsFullEnoughToStartIncrementalMarking(intptr_t limit) {
1326 if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1328 intptr_t adjusted_allocation_limit = limit - new_space_.Capacity();
1330 if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
1335 void UpdateNewSpaceReferencesInExternalStringTable(
1336 ExternalStringTableUpdaterCallback updater_func);
1338 void UpdateReferencesInExternalStringTable(
1339 ExternalStringTableUpdaterCallback updater_func);
1341 void ProcessAllWeakReferences(WeakObjectRetainer* retainer);
1342 void ProcessYoungWeakReferences(WeakObjectRetainer* retainer);
1344 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1346 // An object should be promoted if the object has survived a
1347 // scavenge operation.
1348 inline bool ShouldBePromoted(Address old_address, int object_size);
1350 void ClearNormalizedMapCaches();
1352 GCTracer* tracer() { return tracer_; }
1354 // Returns the size of objects residing in non new spaces.
1355 intptr_t PromotedSpaceSizeOfObjects();
1357 double total_regexp_code_generated() { return total_regexp_code_generated_; }
1358 void IncreaseTotalRegexpCodeGenerated(int size) {
1359 total_regexp_code_generated_ += size;
1362 void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1363 if (is_crankshafted) {
1364 crankshaft_codegen_bytes_generated_ += size;
1366 full_codegen_bytes_generated_ += size;
1370 void UpdateNewSpaceAllocationCounter() {
1371 new_space_allocation_counter_ = NewSpaceAllocationCounter();
1374 size_t NewSpaceAllocationCounter() {
1375 return new_space_allocation_counter_ + new_space()->AllocatedSinceLastGC();
1378 // This should be used only for testing.
1379 void set_new_space_allocation_counter(size_t new_value) {
1380 new_space_allocation_counter_ = new_value;
1383 void UpdateOldGenerationAllocationCounter() {
1384 old_generation_allocation_counter_ = OldGenerationAllocationCounter();
1387 size_t OldGenerationAllocationCounter() {
1388 return old_generation_allocation_counter_ + PromotedSinceLastGC();
1391 // This should be used only for testing.
1392 void set_old_generation_allocation_counter(size_t new_value) {
1393 old_generation_allocation_counter_ = new_value;
1396 size_t PromotedSinceLastGC() {
1397 return PromotedSpaceSizeOfObjects() - old_generation_size_at_last_gc_;
1400 // Update GC statistics that are tracked on the Heap.
1401 void UpdateCumulativeGCStatistics(double duration, double spent_in_mutator,
1402 double marking_time);
1404 // Returns maximum GC pause.
1405 double get_max_gc_pause() { return max_gc_pause_; }
1407 // Returns maximum size of objects alive after GC.
1408 intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1410 // Returns minimal interval between two subsequent collections.
1411 double get_min_in_mutator() { return min_in_mutator_; }
1413 void IncrementDeferredCount(v8::Isolate::UseCounterFeature feature);
1415 MarkCompactCollector* mark_compact_collector() {
1416 return &mark_compact_collector_;
1419 StoreBuffer* store_buffer() { return &store_buffer_; }
1421 IncrementalMarking* incremental_marking() { return &incremental_marking_; }
1423 ExternalStringTable* external_string_table() {
1424 return &external_string_table_;
1427 bool concurrent_sweeping_enabled() { return concurrent_sweeping_enabled_; }
1429 inline Isolate* isolate();
1431 void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1432 void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1434 inline bool OldGenerationAllocationLimitReached();
1436 void QueueMemoryChunkForFree(MemoryChunk* chunk);
1437 void FilterStoreBufferEntriesOnAboutToBeFreedPages();
1438 void FreeQueuedChunks();
1440 int gc_count() const { return gc_count_; }
1442 bool RecentIdleNotificationHappened();
1444 // Completely clear the Instanceof cache (to stop it keeping objects alive
1446 inline void CompletelyClearInstanceofCache();
1448 // The roots that have an index less than this are always in old space.
1449 static const int kOldSpaceRoots = 0x20;
1451 inline uint32_t HashSeed();
1453 inline Smi* NextScriptId();
1455 inline void SetArgumentsAdaptorDeoptPCOffset(int pc_offset);
1456 inline void SetConstructStubDeoptPCOffset(int pc_offset);
1457 inline void SetGetterStubDeoptPCOffset(int pc_offset);
1458 inline void SetSetterStubDeoptPCOffset(int pc_offset);
1460 // For post mortem debugging.
1461 void RememberUnmappedPage(Address page, bool compacted);
1463 // Global inline caching age: it is incremented on some GCs after context
1464 // disposal. We use it to flush inline caches.
1465 int global_ic_age() { return global_ic_age_; }
1467 void AgeInlineCaches() {
1468 global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
1471 int64_t amount_of_external_allocated_memory() {
1472 return amount_of_external_allocated_memory_;
1475 void DeoptMarkedAllocationSites();
1477 bool MaximumSizeScavenge() { return maximum_size_scavenges_ > 0; }
1479 bool DeoptMaybeTenuredAllocationSites() {
1480 return new_space_.IsAtMaximumCapacity() && maximum_size_scavenges_ == 0;
1483 // ObjectStats are kept in two arrays, counts and sizes. Related stats are
1484 // stored in a contiguous linear buffer. Stats groups are stored one after
1487 FIRST_CODE_KIND_SUB_TYPE = LAST_TYPE + 1,
1488 FIRST_FIXED_ARRAY_SUB_TYPE =
1489 FIRST_CODE_KIND_SUB_TYPE + Code::NUMBER_OF_KINDS,
1490 FIRST_CODE_AGE_SUB_TYPE =
1491 FIRST_FIXED_ARRAY_SUB_TYPE + LAST_FIXED_ARRAY_SUB_TYPE + 1,
1492 OBJECT_STATS_COUNT = FIRST_CODE_AGE_SUB_TYPE + Code::kCodeAgeCount + 1
1495 void RecordObjectStats(InstanceType type, size_t size) {
1496 DCHECK(type <= LAST_TYPE);
1497 object_counts_[type]++;
1498 object_sizes_[type] += size;
1501 void RecordCodeSubTypeStats(int code_sub_type, int code_age, size_t size) {
1502 int code_sub_type_index = FIRST_CODE_KIND_SUB_TYPE + code_sub_type;
1503 int code_age_index =
1504 FIRST_CODE_AGE_SUB_TYPE + code_age - Code::kFirstCodeAge;
1505 DCHECK(code_sub_type_index >= FIRST_CODE_KIND_SUB_TYPE &&
1506 code_sub_type_index < FIRST_CODE_AGE_SUB_TYPE);
1507 DCHECK(code_age_index >= FIRST_CODE_AGE_SUB_TYPE &&
1508 code_age_index < OBJECT_STATS_COUNT);
1509 object_counts_[code_sub_type_index]++;
1510 object_sizes_[code_sub_type_index] += size;
1511 object_counts_[code_age_index]++;
1512 object_sizes_[code_age_index] += size;
1515 void RecordFixedArraySubTypeStats(int array_sub_type, size_t size) {
1516 DCHECK(array_sub_type <= LAST_FIXED_ARRAY_SUB_TYPE);
1517 object_counts_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type]++;
1518 object_sizes_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type] += size;
1521 void TraceObjectStats();
1522 void TraceObjectStat(const char* name, int count, int size, double time);
1523 void CheckpointObjectStats();
1524 bool GetObjectTypeName(size_t index, const char** object_type,
1525 const char** object_sub_type);
1527 void RegisterStrongRoots(Object** start, Object** end);
1528 void UnregisterStrongRoots(Object** start);
1530 // Taking this lock prevents the GC from entering a phase that relocates
1531 // object references.
1532 class RelocationLock {
1534 explicit RelocationLock(Heap* heap) : heap_(heap) {
1535 heap_->relocation_mutex_.Lock();
1538 ~RelocationLock() { heap_->relocation_mutex_.Unlock(); }
1544 // An optional version of the above lock that can be used for some critical
1545 // sections on the mutator thread; only safe since the GC currently does not
1546 // do concurrent compaction.
1547 class OptionalRelocationLock {
1549 OptionalRelocationLock(Heap* heap, bool concurrent)
1550 : heap_(heap), concurrent_(concurrent) {
1551 if (concurrent_) heap_->relocation_mutex_.Lock();
1554 ~OptionalRelocationLock() {
1555 if (concurrent_) heap_->relocation_mutex_.Unlock();
1563 void AddWeakObjectToCodeDependency(Handle<HeapObject> obj,
1564 Handle<DependentCode> dep);
1566 DependentCode* LookupWeakObjectToCodeDependency(Handle<HeapObject> obj);
1568 void AddRetainedMap(Handle<Map> map);
1570 static void FatalProcessOutOfMemory(const char* location,
1571 bool take_snapshot = false);
1573 // This event is triggered after successful allocation of a new object made
1574 // by runtime. Allocations of target space for object evacuation do not
1575 // trigger the event. In order to track ALL allocations one must turn off
1576 // FLAG_inline_new and FLAG_use_allocation_folding.
1577 inline void OnAllocationEvent(HeapObject* object, int size_in_bytes);
1579 // This event is triggered after object is moved to a new place.
1580 inline void OnMoveEvent(HeapObject* target, HeapObject* source,
1583 bool deserialization_complete() const { return deserialization_complete_; }
1585 // The following methods are used to track raw C++ pointers to externally
1586 // allocated memory used as backing store in live array buffers.
1588 // A new ArrayBuffer was created with |data| as backing store.
1589 void RegisterNewArrayBuffer(bool in_new_space, void* data, size_t length);
1591 // The backing store |data| is no longer owned by V8.
1592 void UnregisterArrayBuffer(bool in_new_space, void* data);
1594 // A live ArrayBuffer was discovered during marking/scavenge.
1595 void RegisterLiveArrayBuffer(bool from_scavenge, void* data);
1597 // Frees all backing store pointers that weren't discovered in the previous
1598 // marking or scavenge phase.
1599 void FreeDeadArrayBuffers(bool from_scavenge);
1601 // Prepare for a new scavenge phase. A new marking phase is implicitly
1602 // prepared by finishing the previous one.
1603 void PrepareArrayBufferDiscoveryInNewSpace();
1605 // An ArrayBuffer moved from new space to old space.
1606 void PromoteArrayBuffer(Object* buffer);
1608 bool HasLowAllocationRate();
1609 bool HasHighFragmentation();
1610 bool HasHighFragmentation(intptr_t used, intptr_t committed);
1612 bool ShouldOptimizeForMemoryUsage() { return optimize_for_memory_usage_; }
1615 static const int kInitialStringTableSize = 2048;
1616 static const int kInitialEvalCacheSize = 64;
1617 static const int kInitialNumberStringCacheSize = 256;
1621 int current_gc_flags() { return current_gc_flags_; }
1622 void set_current_gc_flags(int flags) {
1623 current_gc_flags_ = flags;
1624 DCHECK(!ShouldFinalizeIncrementalMarking() ||
1625 !ShouldAbortIncrementalMarking());
1628 inline bool ShouldReduceMemory() const {
1629 return current_gc_flags_ & kReduceMemoryFootprintMask;
1632 inline bool ShouldAbortIncrementalMarking() const {
1633 return current_gc_flags_ & kAbortIncrementalMarkingMask;
1636 inline bool ShouldFinalizeIncrementalMarking() const {
1637 return current_gc_flags_ & kFinalizeIncrementalMarkingMask;
1640 // Allocates a JS Map in the heap.
1641 MUST_USE_RESULT AllocationResult
1642 AllocateMap(InstanceType instance_type, int instance_size,
1643 ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
1645 // Allocates and initializes a new JavaScript object based on a
1647 // If allocation_site is non-null, then a memento is emitted after the object
1648 // that points to the site.
1649 MUST_USE_RESULT AllocationResult
1650 AllocateJSObject(JSFunction* constructor,
1651 PretenureFlag pretenure = NOT_TENURED,
1652 AllocationSite* allocation_site = NULL);
1654 // Allocates and initializes a new JavaScript object based on a map.
1655 // Passing an allocation site means that a memento will be created that
1656 // points to the site.
1657 MUST_USE_RESULT AllocationResult
1658 AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure = NOT_TENURED,
1659 AllocationSite* allocation_site = NULL);
1661 // Allocates a HeapNumber from value.
1662 MUST_USE_RESULT AllocationResult
1663 AllocateHeapNumber(double value, MutableMode mode = IMMUTABLE,
1664 PretenureFlag pretenure = NOT_TENURED);
1666 // Allocates SIMD values from the given lane values.
1667 #define SIMD_ALLOCATE_DECLARATION(TYPE, Type, type, lane_count, lane_type) \
1668 AllocationResult Allocate##Type(lane_type lanes[lane_count], \
1669 PretenureFlag pretenure = NOT_TENURED);
1670 SIMD128_TYPES(SIMD_ALLOCATE_DECLARATION)
1671 #undef SIMD_ALLOCATE_DECLARATION
1673 // Allocates a byte array of the specified length
1674 MUST_USE_RESULT AllocationResult
1675 AllocateByteArray(int length, PretenureFlag pretenure = NOT_TENURED);
1677 // Allocates a bytecode array with given contents.
1678 MUST_USE_RESULT AllocationResult
1679 AllocateBytecodeArray(int length, const byte* raw_bytecodes,
1682 // Copy the code and scope info part of the code object, but insert
1683 // the provided data as the relocation information.
1684 MUST_USE_RESULT AllocationResult
1685 CopyCode(Code* code, Vector<byte> reloc_info);
1687 MUST_USE_RESULT AllocationResult CopyCode(Code* code);
1689 // Allocates a fixed array initialized with undefined values
1690 MUST_USE_RESULT AllocationResult
1691 AllocateFixedArray(int length, PretenureFlag pretenure = NOT_TENURED);
1693 // The amount of external memory registered through the API kept alive
1694 // by global handles
1695 int64_t amount_of_external_allocated_memory_;
1697 // Caches the amount of external memory registered at the last global gc.
1698 int64_t amount_of_external_allocated_memory_at_last_global_gc_;
1700 // This can be calculated directly from a pointer to the heap; however, it is
1701 // more expedient to get at the isolate directly from within Heap methods.
1704 Object* roots_[kRootListLength];
1706 size_t code_range_size_;
1707 int reserved_semispace_size_;
1708 int max_semi_space_size_;
1709 int initial_semispace_size_;
1710 int target_semispace_size_;
1711 intptr_t max_old_generation_size_;
1712 intptr_t initial_old_generation_size_;
1713 bool old_generation_size_configured_;
1714 intptr_t max_executable_size_;
1715 intptr_t maximum_committed_;
1717 // For keeping track of how much data has survived
1718 // scavenge since last new space expansion.
1719 int survived_since_last_expansion_;
1721 // ... and since the last scavenge.
1722 int survived_last_scavenge_;
1724 int always_allocate_scope_depth_;
1726 // For keeping track of context disposals.
1727 int contexts_disposed_;
1731 int scan_on_scavenge_pages_;
1733 NewSpace new_space_;
1734 OldSpace* old_space_;
1735 OldSpace* code_space_;
1736 MapSpace* map_space_;
1737 LargeObjectSpace* lo_space_;
1738 HeapState gc_state_;
1739 int gc_post_processing_depth_;
1740 Address new_space_top_after_last_gc_;
1742 // Returns the amount of external memory registered since last global gc.
1743 int64_t PromotedExternalMemorySize();
1745 // How many "runtime allocations" happened.
1746 uint32_t allocations_count_;
1748 // Running hash over allocations performed.
1749 uint32_t raw_allocations_hash_;
1751 // Countdown counter, dumps allocation hash when 0.
1752 uint32_t dump_allocations_hash_countdown_;
1754 // How many mark-sweep collections happened.
1755 unsigned int ms_count_;
1757 // How many gc happened.
1758 unsigned int gc_count_;
1760 // For post mortem debugging.
1761 static const int kRememberedUnmappedPages = 128;
1762 int remembered_unmapped_pages_index_;
1763 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
1765 #define ROOT_ACCESSOR(type, name, camel_name) \
1766 inline void set_##name(type* value);
1767 ROOT_LIST(ROOT_ACCESSOR)
1768 #undef ROOT_ACCESSOR
1771 // If the --gc-interval flag is set to a positive value, this
1772 // variable holds the value indicating the number of allocations
1773 // remain until the next failure and garbage collection.
1774 int allocation_timeout_;
1777 // Limit that triggers a global GC on the next (normally caused) GC. This
1778 // is checked when we have already decided to do a GC to help determine
1779 // which collector to invoke, before expanding a paged space in the old
1780 // generation and on every allocation in large object space.
1781 intptr_t old_generation_allocation_limit_;
1783 // Indicates that an allocation has failed in the old generation since the
1785 bool old_gen_exhausted_;
1787 // Indicates that memory usage is more important than latency.
1788 // TODO(ulan): Merge it with memory reducer once chromium:490559 is fixed.
1789 bool optimize_for_memory_usage_;
1791 // Indicates that inline bump-pointer allocation has been globally disabled
1792 // for all spaces. This is used to disable allocations in generated code.
1793 bool inline_allocation_disabled_;
1795 // Weak list heads, threaded through the objects.
1796 // List heads are initialized lazily and contain the undefined_value at start.
1797 Object* native_contexts_list_;
1798 Object* allocation_sites_list_;
1800 // List of encountered weak collections (JSWeakMap and JSWeakSet) during
1801 // marking. It is initialized during marking, destroyed after marking and
1802 // contains Smi(0) while marking is not active.
1803 Object* encountered_weak_collections_;
1805 Object* encountered_weak_cells_;
1807 StoreBufferRebuilder store_buffer_rebuilder_;
1809 struct StringTypeTable {
1812 RootListIndex index;
1815 struct ConstantStringTable {
1816 const char* contents;
1817 RootListIndex index;
1820 struct StructTable {
1823 RootListIndex index;
1826 static const StringTypeTable string_type_table[];
1827 static const ConstantStringTable constant_string_table[];
1828 static const StructTable struct_table[];
1830 struct GCCallbackPair {
1831 GCCallbackPair(v8::Isolate::GCCallback callback, GCType gc_type,
1833 : callback(callback), gc_type(gc_type), pass_isolate(pass_isolate) {}
1835 bool operator==(const GCCallbackPair& other) const {
1836 return other.callback == callback;
1839 v8::Isolate::GCCallback callback;
1844 List<GCCallbackPair> gc_epilogue_callbacks_;
1845 List<GCCallbackPair> gc_prologue_callbacks_;
1847 // Code that should be run before and after each GC. Includes some
1848 // reporting/verification activities when compiled with DEBUG set.
1849 void GarbageCollectionPrologue();
1850 void GarbageCollectionEpilogue();
1852 void PreprocessStackTraces();
1854 // Pretenuring decisions are made based on feedback collected during new
1855 // space evacuation. Note that between feedback collection and calling this
1856 // method object in old space must not move.
1857 // Right now we only process pretenuring feedback in high promotion mode.
1858 bool ProcessPretenuringFeedback();
1860 // Checks whether a global GC is necessary
1861 GarbageCollector SelectGarbageCollector(AllocationSpace space,
1862 const char** reason);
1864 // Make sure there is a filler value behind the top of the new space
1865 // so that the GC does not confuse some unintialized/stale memory
1866 // with the allocation memento of the object at the top
1867 void EnsureFillerObjectAtTop();
1869 // Ensure that we have swept all spaces in such a way that we can iterate
1870 // over all objects. May cause a GC.
1871 void MakeHeapIterable();
1873 // Performs garbage collection operation.
1874 // Returns whether there is a chance that another major GC could
1875 // collect more garbage.
1876 bool CollectGarbage(
1877 GarbageCollector collector, const char* gc_reason,
1878 const char* collector_reason,
1879 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1881 // Performs garbage collection
1882 // Returns whether there is a chance another major GC could
1883 // collect more garbage.
1884 bool PerformGarbageCollection(
1885 GarbageCollector collector,
1886 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1888 inline void UpdateOldSpaceLimits();
1890 // Selects the proper allocation space depending on the given object
1891 // size and pretenuring decision.
1892 static AllocationSpace SelectSpace(int object_size,
1893 PretenureFlag pretenure) {
1894 if (object_size > Page::kMaxRegularHeapObjectSize) return LO_SPACE;
1895 return (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1898 HeapObject* DoubleAlignForDeserialization(HeapObject* object, int size);
1900 // Allocate an uninitialized object. The memory is non-executable if the
1901 // hardware and OS allow. This is the single choke-point for allocations
1902 // performed by the runtime and should not be bypassed (to extend this to
1903 // inlined allocations, use the Heap::DisableInlineAllocation() support).
1904 MUST_USE_RESULT inline AllocationResult AllocateRaw(
1905 int size_in_bytes, AllocationSpace space, AllocationSpace retry_space,
1906 AllocationAlignment aligment = kWordAligned);
1908 // Allocates a heap object based on the map.
1909 MUST_USE_RESULT AllocationResult
1910 Allocate(Map* map, AllocationSpace space,
1911 AllocationSite* allocation_site = NULL);
1913 // Allocates a partial map for bootstrapping.
1914 MUST_USE_RESULT AllocationResult
1915 AllocatePartialMap(InstanceType instance_type, int instance_size);
1917 // Initializes a JSObject based on its map.
1918 void InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties,
1920 void InitializeAllocationMemento(AllocationMemento* memento,
1921 AllocationSite* allocation_site);
1923 // Allocate a block of memory in the given space (filled with a filler).
1924 // Used as a fall-back for generated code when the space is full.
1925 MUST_USE_RESULT AllocationResult
1926 AllocateFillerObject(int size, bool double_align, AllocationSpace space);
1928 // Allocate an uninitialized fixed array.
1929 MUST_USE_RESULT AllocationResult
1930 AllocateRawFixedArray(int length, PretenureFlag pretenure);
1932 // Allocate an uninitialized fixed double array.
1933 MUST_USE_RESULT AllocationResult
1934 AllocateRawFixedDoubleArray(int length, PretenureFlag pretenure);
1936 // Allocate an initialized fixed array with the given filler value.
1937 MUST_USE_RESULT AllocationResult
1938 AllocateFixedArrayWithFiller(int length, PretenureFlag pretenure,
1941 // Allocate and partially initializes a String. There are two String
1942 // encodings: one-byte and two-byte. These functions allocate a string of
1943 // the given length and set its map and length fields. The characters of
1944 // the string are uninitialized.
1945 MUST_USE_RESULT AllocationResult
1946 AllocateRawOneByteString(int length, PretenureFlag pretenure);
1947 MUST_USE_RESULT AllocationResult
1948 AllocateRawTwoByteString(int length, PretenureFlag pretenure);
1950 bool CreateInitialMaps();
1951 void CreateInitialObjects();
1953 // Allocates an internalized string in old space based on the character
1955 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringFromUtf8(
1956 Vector<const char> str, int chars, uint32_t hash_field);
1958 MUST_USE_RESULT inline AllocationResult AllocateOneByteInternalizedString(
1959 Vector<const uint8_t> str, uint32_t hash_field);
1961 MUST_USE_RESULT inline AllocationResult AllocateTwoByteInternalizedString(
1962 Vector<const uc16> str, uint32_t hash_field);
1964 template <bool is_one_byte, typename T>
1965 MUST_USE_RESULT AllocationResult
1966 AllocateInternalizedStringImpl(T t, int chars, uint32_t hash_field);
1968 template <typename T>
1969 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringImpl(
1970 T t, int chars, uint32_t hash_field);
1972 // Allocates an uninitialized fixed array. It must be filled by the caller.
1973 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedArray(int length);
1975 // Make a copy of src and return it.
1976 MUST_USE_RESULT inline AllocationResult CopyFixedArray(FixedArray* src);
1978 // Make a copy of src, also grow the copy, and return the copy.
1979 MUST_USE_RESULT AllocationResult
1980 CopyFixedArrayAndGrow(FixedArray* src, int grow_by, PretenureFlag pretenure);
1982 // Make a copy of src, set the map, and return the copy.
1983 MUST_USE_RESULT AllocationResult
1984 CopyFixedArrayWithMap(FixedArray* src, Map* map);
1986 // Make a copy of src and return it.
1987 MUST_USE_RESULT inline AllocationResult CopyFixedDoubleArray(
1988 FixedDoubleArray* src);
1990 // Computes a single character string where the character has code.
1991 // A cache is used for one-byte (Latin1) codes.
1992 MUST_USE_RESULT AllocationResult
1993 LookupSingleCharacterStringFromCode(uint16_t code);
1995 // Allocate a symbol in old space.
1996 MUST_USE_RESULT AllocationResult AllocateSymbol();
1998 // Allocates an external array of the specified length and type.
1999 MUST_USE_RESULT AllocationResult AllocateFixedTypedArrayWithExternalPointer(
2000 int length, ExternalArrayType array_type, void* external_pointer,
2001 PretenureFlag pretenure);
2003 // Allocates a fixed typed array of the specified length and type.
2004 MUST_USE_RESULT AllocationResult
2005 AllocateFixedTypedArray(int length, ExternalArrayType array_type,
2006 bool initialize, PretenureFlag pretenure);
2008 // Make a copy of src and return it.
2009 MUST_USE_RESULT AllocationResult CopyAndTenureFixedCOWArray(FixedArray* src);
2011 // Make a copy of src, set the map, and return the copy.
2012 MUST_USE_RESULT AllocationResult
2013 CopyFixedDoubleArrayWithMap(FixedDoubleArray* src, Map* map);
2015 // Allocates a fixed double array with uninitialized values. Returns
2016 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedDoubleArray(
2017 int length, PretenureFlag pretenure = NOT_TENURED);
2019 // These five Create*EntryStub functions are here and forced to not be inlined
2020 // because of a gcc-4.4 bug that assigns wrong vtable entries.
2021 NO_INLINE(void CreateJSEntryStub());
2022 NO_INLINE(void CreateJSConstructEntryStub());
2024 void CreateFixedStubs();
2026 // Allocate empty fixed array.
2027 MUST_USE_RESULT AllocationResult AllocateEmptyFixedArray();
2029 // Allocate empty fixed typed array of given type.
2030 MUST_USE_RESULT AllocationResult
2031 AllocateEmptyFixedTypedArray(ExternalArrayType array_type);
2033 // Allocate a tenured simple cell.
2034 MUST_USE_RESULT AllocationResult AllocateCell(Object* value);
2036 // Allocate a tenured JS global property cell initialized with the hole.
2037 MUST_USE_RESULT AllocationResult AllocatePropertyCell();
2039 MUST_USE_RESULT AllocationResult AllocateWeakCell(HeapObject* value);
2041 // Allocates a new utility object in the old generation.
2042 MUST_USE_RESULT AllocationResult AllocateStruct(InstanceType type);
2044 // Allocates a new foreign object.
2045 MUST_USE_RESULT AllocationResult
2046 AllocateForeign(Address address, PretenureFlag pretenure = NOT_TENURED);
2048 MUST_USE_RESULT AllocationResult
2049 AllocateCode(int object_size, bool immovable);
2051 MUST_USE_RESULT AllocationResult InternalizeStringWithKey(HashTableKey* key);
2053 MUST_USE_RESULT AllocationResult InternalizeString(String* str);
2055 // Performs a minor collection in new generation.
2058 // Commits from space if it is uncommitted.
2059 void EnsureFromSpaceIsCommitted();
2061 // Uncommit unused semi space.
2062 bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
2064 // Fill in bogus values in from space
2065 void ZapFromSpace();
2067 static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
2068 Heap* heap, Object** pointer);
2070 Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
2071 static void ScavengeStoreBufferCallback(Heap* heap, MemoryChunk* page,
2072 StoreBufferEvent event);
2074 // Performs a major collection in the whole heap.
2077 // Code to be run before and after mark-compact.
2078 void MarkCompactPrologue();
2079 void MarkCompactEpilogue();
2081 void ProcessNativeContexts(WeakObjectRetainer* retainer);
2082 void ProcessAllocationSites(WeakObjectRetainer* retainer);
2084 // Deopts all code that contains allocation instruction which are tenured or
2085 // not tenured. Moreover it clears the pretenuring allocation site statistics.
2086 void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
2088 // Evaluates local pretenuring for the old space and calls
2089 // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
2091 void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
2093 // Called on heap tear-down. Frees all remaining ArrayBuffer backing stores.
2094 void TearDownArrayBuffers();
2096 // These correspond to the non-Helper versions.
2097 void RegisterNewArrayBufferHelper(std::map<void*, size_t>& live_buffers,
2098 void* data, size_t length);
2099 void UnregisterArrayBufferHelper(
2100 std::map<void*, size_t>& live_buffers,
2101 std::map<void*, size_t>& not_yet_discovered_buffers, void* data);
2102 void RegisterLiveArrayBufferHelper(
2103 std::map<void*, size_t>& not_yet_discovered_buffers, void* data);
2104 size_t FreeDeadArrayBuffersHelper(
2105 Isolate* isolate, std::map<void*, size_t>& live_buffers,
2106 std::map<void*, size_t>& not_yet_discovered_buffers);
2107 void TearDownArrayBuffersHelper(
2108 Isolate* isolate, std::map<void*, size_t>& live_buffers,
2109 std::map<void*, size_t>& not_yet_discovered_buffers);
2111 // Record statistics before and after garbage collection.
2112 void ReportStatisticsBeforeGC();
2113 void ReportStatisticsAfterGC();
2115 // Total RegExp code ever generated
2116 double total_regexp_code_generated_;
2118 int deferred_counters_[v8::Isolate::kUseCounterFeatureCount];
2122 // Creates and installs the full-sized number string cache.
2123 int FullSizeNumberStringCacheLength();
2124 // Flush the number to string cache.
2125 void FlushNumberStringCache();
2127 // Sets used allocation sites entries to undefined.
2128 void FlushAllocationSitesScratchpad();
2130 // Initializes the allocation sites scratchpad with undefined values.
2131 void InitializeAllocationSitesScratchpad();
2133 // Adds an allocation site to the scratchpad if there is space left.
2134 void AddAllocationSiteToScratchpad(AllocationSite* site,
2135 ScratchpadSlotMode mode);
2137 void UpdateSurvivalStatistics(int start_new_space_size);
2139 static const int kYoungSurvivalRateHighThreshold = 90;
2140 static const int kYoungSurvivalRateAllowedDeviation = 15;
2142 static const int kOldSurvivalRateLowThreshold = 10;
2144 int high_survival_rate_period_length_;
2145 intptr_t promoted_objects_size_;
2146 double promotion_ratio_;
2147 double promotion_rate_;
2148 intptr_t semi_space_copied_object_size_;
2149 intptr_t previous_semi_space_copied_object_size_;
2150 double semi_space_copied_rate_;
2151 int nodes_died_in_new_space_;
2152 int nodes_copied_in_new_space_;
2153 int nodes_promoted_;
2155 // This is the pretenuring trigger for allocation sites that are in maybe
2156 // tenure state. When we switched to the maximum new space size we deoptimize
2157 // the code that belongs to the allocation site and derive the lifetime
2158 // of the allocation site.
2159 unsigned int maximum_size_scavenges_;
2161 // TODO(hpayer): Allocation site pretenuring may make this method obsolete.
2162 // Re-visit incremental marking heuristics.
2163 bool IsHighSurvivalRate() { return high_survival_rate_period_length_ > 0; }
2165 void ConfigureInitialOldGenerationSize();
2167 void SelectScavengingVisitorsTable();
2169 bool HasLowYoungGenerationAllocationRate();
2170 bool HasLowOldGenerationAllocationRate();
2171 double YoungGenerationMutatorUtilization();
2172 double OldGenerationMutatorUtilization();
2174 void ReduceNewSpaceSize();
2176 bool TryFinalizeIdleIncrementalMarking(
2177 double idle_time_in_ms, size_t size_of_objects,
2178 size_t mark_compact_speed_in_bytes_per_ms);
2180 GCIdleTimeHandler::HeapState ComputeHeapState();
2182 bool PerformIdleTimeAction(GCIdleTimeAction action,
2183 GCIdleTimeHandler::HeapState heap_state,
2184 double deadline_in_ms);
2186 void IdleNotificationEpilogue(GCIdleTimeAction action,
2187 GCIdleTimeHandler::HeapState heap_state,
2188 double start_ms, double deadline_in_ms);
2189 void CheckAndNotifyBackgroundIdleNotification(double idle_time_in_ms,
2192 void ClearObjectStats(bool clear_last_time_stats = false);
2194 inline void UpdateAllocationsHash(HeapObject* object);
2195 inline void UpdateAllocationsHash(uint32_t value);
2196 inline void PrintAlloctionsHash();
2198 void AddToRingBuffer(const char* string);
2199 void GetFromRingBuffer(char* buffer);
2201 // Object counts and used memory by InstanceType
2202 size_t object_counts_[OBJECT_STATS_COUNT];
2203 size_t object_counts_last_time_[OBJECT_STATS_COUNT];
2204 size_t object_sizes_[OBJECT_STATS_COUNT];
2205 size_t object_sizes_last_time_[OBJECT_STATS_COUNT];
2207 // Maximum GC pause.
2208 double max_gc_pause_;
2210 // Total time spent in GC.
2211 double total_gc_time_ms_;
2213 // Maximum size of objects alive after GC.
2214 intptr_t max_alive_after_gc_;
2216 // Minimal interval between two subsequent collections.
2217 double min_in_mutator_;
2219 // Cumulative GC time spent in marking.
2220 double marking_time_;
2222 // Cumulative GC time spent in sweeping.
2223 double sweeping_time_;
2225 // Last time an idle notification happened.
2226 double last_idle_notification_time_;
2228 // Last time a garbage collection happened.
2229 double last_gc_time_;
2231 MarkCompactCollector mark_compact_collector_;
2233 StoreBuffer store_buffer_;
2235 IncrementalMarking incremental_marking_;
2237 GCIdleTimeHandler gc_idle_time_handler_;
2239 MemoryReducer* memory_reducer_;
2241 // These two counters are monotomically increasing and never reset.
2242 size_t full_codegen_bytes_generated_;
2243 size_t crankshaft_codegen_bytes_generated_;
2245 // This counter is increased before each GC and never reset.
2246 // To account for the bytes allocated since the last GC, use the
2247 // NewSpaceAllocationCounter() function.
2248 size_t new_space_allocation_counter_;
2250 // This counter is increased before each GC and never reset. To
2251 // account for the bytes allocated since the last GC, use the
2252 // OldGenerationAllocationCounter() function.
2253 size_t old_generation_allocation_counter_;
2255 // The size of objects in old generation after the last MarkCompact GC.
2256 size_t old_generation_size_at_last_gc_;
2258 // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2259 // this variable holds the number of garbage collections since the last
2260 // deoptimization triggered by garbage collection.
2261 int gcs_since_last_deopt_;
2263 static const int kAllocationSiteScratchpadSize = 256;
2264 int allocation_sites_scratchpad_length_;
2266 char trace_ring_buffer_[kTraceRingBufferSize];
2267 // If it's not full then the data is from 0 to ring_buffer_end_. If it's
2268 // full then the data is from ring_buffer_end_ to the end of the buffer and
2269 // from 0 to ring_buffer_end_.
2270 bool ring_buffer_full_;
2271 size_t ring_buffer_end_;
2273 static const int kMaxMarkCompactsInIdleRound = 7;
2274 static const int kIdleScavengeThreshold = 5;
2276 // Shared state read by the scavenge collector and set by ScavengeObject.
2277 PromotionQueue promotion_queue_;
2279 // Flag is set when the heap has been configured. The heap can be repeatedly
2280 // configured through the API until it is set up.
2283 // Currently set GC flags that are respected by all GC components.
2284 int current_gc_flags_;
2286 ExternalStringTable external_string_table_;
2288 VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2290 MemoryChunk* chunks_queued_for_free_;
2292 base::Mutex relocation_mutex_;
2294 int gc_callbacks_depth_;
2296 bool deserialization_complete_;
2298 bool concurrent_sweeping_enabled_;
2300 // |live_array_buffers_| maps externally allocated memory used as backing
2301 // store for ArrayBuffers to the length of the respective memory blocks.
2303 // At the beginning of mark/compact, |not_yet_discovered_array_buffers_| is
2304 // a copy of |live_array_buffers_| and we remove pointers as we discover live
2305 // ArrayBuffer objects during marking. At the end of mark/compact, the
2306 // remaining memory blocks can be freed.
2307 std::map<void*, size_t> live_array_buffers_;
2308 std::map<void*, size_t> not_yet_discovered_array_buffers_;
2310 // To be able to free memory held by ArrayBuffers during scavenge as well, we
2311 // have a separate list of allocated memory held by ArrayBuffers in new space.
2313 // Since mark/compact also evacuates the new space, all pointers in the
2314 // |live_array_buffers_for_scavenge_| list are also in the
2315 // |live_array_buffers_| list.
2316 std::map<void*, size_t> live_array_buffers_for_scavenge_;
2317 std::map<void*, size_t> not_yet_discovered_array_buffers_for_scavenge_;
2319 struct StrongRootsList;
2320 StrongRootsList* strong_roots_list_;
2322 friend class AlwaysAllocateScope;
2323 friend class Bootstrapper;
2324 friend class Deserializer;
2325 friend class Factory;
2326 friend class GCCallbacksScope;
2327 friend class GCTracer;
2328 friend class HeapIterator;
2329 friend class IncrementalMarking;
2330 friend class Isolate;
2331 friend class MarkCompactCollector;
2332 friend class MarkCompactMarkingVisitor;
2333 friend class MapCompact;
2337 friend class HeapTester;
2339 DISALLOW_COPY_AND_ASSIGN(Heap);
2345 static const int kStartMarker = 0xDECADE00;
2346 static const int kEndMarker = 0xDECADE01;
2348 int* start_marker; // 0
2349 int* new_space_size; // 1
2350 int* new_space_capacity; // 2
2351 intptr_t* old_space_size; // 3
2352 intptr_t* old_space_capacity; // 4
2353 intptr_t* code_space_size; // 5
2354 intptr_t* code_space_capacity; // 6
2355 intptr_t* map_space_size; // 7
2356 intptr_t* map_space_capacity; // 8
2357 intptr_t* lo_space_size; // 9
2358 int* global_handle_count; // 10
2359 int* weak_global_handle_count; // 11
2360 int* pending_global_handle_count; // 12
2361 int* near_death_global_handle_count; // 13
2362 int* free_global_handle_count; // 14
2363 intptr_t* memory_allocator_size; // 15
2364 intptr_t* memory_allocator_capacity; // 16
2365 int* objects_per_type; // 17
2366 int* size_per_type; // 18
2367 int* os_error; // 19
2368 char* last_few_messages; // 20
2369 char* js_stacktrace; // 21
2370 int* end_marker; // 22
2374 class AlwaysAllocateScope {
2376 explicit inline AlwaysAllocateScope(Isolate* isolate);
2377 inline ~AlwaysAllocateScope();
2380 // Implicitly disable artificial allocation failures.
2382 DisallowAllocationFailure daf_;
2386 class GCCallbacksScope {
2388 explicit inline GCCallbacksScope(Heap* heap);
2389 inline ~GCCallbacksScope();
2391 inline bool CheckReenter();
2398 // Visitor class to verify interior pointers in spaces that do not contain
2399 // or care about intergenerational references. All heap object pointers have to
2400 // point into the heap to a location that has a map pointer at its first word.
2401 // Caveat: Heap::Contains is an approximation because it can return true for
2402 // objects in a heap space but above the allocation pointer.
2403 class VerifyPointersVisitor : public ObjectVisitor {
2405 inline void VisitPointers(Object** start, Object** end);
2409 // Verify that all objects are Smis.
2410 class VerifySmisVisitor : public ObjectVisitor {
2412 inline void VisitPointers(Object** start, Object** end);
2416 // Space iterator for iterating over all spaces of the heap. Returns each space
2417 // in turn, and null when it is done.
2418 class AllSpaces BASE_EMBEDDED {
2420 explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2429 // Space iterator for iterating over all old spaces of the heap: Old space
2430 // and code space. Returns each space in turn, and null when it is done.
2431 class OldSpaces BASE_EMBEDDED {
2433 explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
2442 // Space iterator for iterating over all the paged spaces of the heap: Map
2443 // space, old space, code space and cell space. Returns
2444 // each space in turn, and null when it is done.
2445 class PagedSpaces BASE_EMBEDDED {
2447 explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
2456 // Space iterator for iterating over all spaces of the heap.
2457 // For each space an object iterator is provided. The deallocation of the
2458 // returned object iterators is handled by the space iterator.
2459 class SpaceIterator : public Malloced {
2461 explicit SpaceIterator(Heap* heap);
2462 virtual ~SpaceIterator();
2465 ObjectIterator* next();
2468 ObjectIterator* CreateIterator();
2471 int current_space_; // from enum AllocationSpace.
2472 ObjectIterator* iterator_; // object iterator for the current space.
2476 // A HeapIterator provides iteration over the whole heap. It
2477 // aggregates the specific iterators for the different spaces as
2478 // these can only iterate over one space only.
2480 // HeapIterator ensures there is no allocation during its lifetime
2481 // (using an embedded DisallowHeapAllocation instance).
2483 // HeapIterator can skip free list nodes (that is, de-allocated heap
2484 // objects that still remain in the heap). As implementation of free
2485 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2486 // phases. Also, it is forbidden to interrupt iteration in this mode,
2487 // as this will leave heap objects marked (and thus, unusable).
2488 class HeapObjectsFilter;
2490 class HeapIterator BASE_EMBEDDED {
2492 enum HeapObjectsFiltering { kNoFiltering, kFilterUnreachable };
2494 explicit HeapIterator(Heap* heap);
2495 HeapIterator(Heap* heap, HeapObjectsFiltering filtering);
2502 struct MakeHeapIterableHelper {
2503 explicit MakeHeapIterableHelper(Heap* heap) { heap->MakeHeapIterable(); }
2506 // Perform the initialization.
2508 // Perform all necessary shutdown (destruction) work.
2510 HeapObject* NextObject();
2512 MakeHeapIterableHelper make_heap_iterable_helper_;
2513 DisallowHeapAllocation no_heap_allocation_;
2515 HeapObjectsFiltering filtering_;
2516 HeapObjectsFilter* filter_;
2517 // Space iterator for iterating all the spaces.
2518 SpaceIterator* space_iterator_;
2519 // Object iterator for the space currently being iterated.
2520 ObjectIterator* object_iterator_;
2524 // Cache for mapping (map, property name) into field offset.
2525 // Cleared at startup and prior to mark sweep collection.
2526 class KeyedLookupCache {
2528 // Lookup field offset for (map, name). If absent, -1 is returned.
2529 int Lookup(Handle<Map> map, Handle<Name> name);
2531 // Update an element in the cache.
2532 void Update(Handle<Map> map, Handle<Name> name, int field_offset);
2537 static const int kLength = 256;
2538 static const int kCapacityMask = kLength - 1;
2539 static const int kMapHashShift = 5;
2540 static const int kHashMask = -4; // Zero the last two bits.
2541 static const int kEntriesPerBucket = 4;
2542 static const int kEntryLength = 2;
2543 static const int kMapIndex = 0;
2544 static const int kKeyIndex = 1;
2545 static const int kNotFound = -1;
2547 // kEntriesPerBucket should be a power of 2.
2548 STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2549 STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2552 KeyedLookupCache() {
2553 for (int i = 0; i < kLength; ++i) {
2554 keys_[i].map = NULL;
2555 keys_[i].name = NULL;
2556 field_offsets_[i] = kNotFound;
2560 static inline int Hash(Handle<Map> map, Handle<Name> name);
2562 // Get the address of the keys and field_offsets arrays. Used in
2563 // generated code to perform cache lookups.
2564 Address keys_address() { return reinterpret_cast<Address>(&keys_); }
2566 Address field_offsets_address() {
2567 return reinterpret_cast<Address>(&field_offsets_);
2576 int field_offsets_[kLength];
2578 friend class ExternalReference;
2579 friend class Isolate;
2580 DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2584 // Cache for mapping (map, property name) into descriptor index.
2585 // The cache contains both positive and negative results.
2586 // Descriptor index equals kNotFound means the property is absent.
2587 // Cleared at startup and prior to any gc.
2588 class DescriptorLookupCache {
2590 // Lookup descriptor index for (map, name).
2591 // If absent, kAbsent is returned.
2592 inline int Lookup(Map* source, Name* name);
2594 // Update an element in the cache.
2595 inline void Update(Map* source, Name* name, int result);
2600 static const int kAbsent = -2;
2603 DescriptorLookupCache() {
2604 for (int i = 0; i < kLength; ++i) {
2605 keys_[i].source = NULL;
2606 keys_[i].name = NULL;
2607 results_[i] = kAbsent;
2611 static int Hash(Object* source, Name* name) {
2612 // Uses only lower 32 bits if pointers are larger.
2613 uint32_t source_hash =
2614 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(source)) >>
2616 uint32_t name_hash =
2617 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >>
2619 return (source_hash ^ name_hash) % kLength;
2622 static const int kLength = 64;
2629 int results_[kLength];
2631 friend class Isolate;
2632 DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2636 // Abstract base class for checking whether a weak object should be retained.
2637 class WeakObjectRetainer {
2639 virtual ~WeakObjectRetainer() {}
2641 // Return whether this object should be retained. If NULL is returned the
2642 // object has no references. Otherwise the address of the retained object
2643 // should be returned as in some GC situations the object has been moved.
2644 virtual Object* RetainAs(Object* object) = 0;
2649 // Helper class for tracing paths to a search target Object from all roots.
2650 // The TracePathFrom() method can be used to trace paths from a specific
2651 // object to the search target object.
2652 class PathTracer : public ObjectVisitor {
2655 FIND_ALL, // Will find all matches.
2656 FIND_FIRST // Will stop the search after first match.
2659 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2660 static const int kMarkTag = 2;
2662 // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2663 // after the first match. If FIND_ALL is specified, then tracing will be
2664 // done for all matches.
2665 PathTracer(Object* search_target, WhatToFind what_to_find,
2666 VisitMode visit_mode)
2667 : search_target_(search_target),
2668 found_target_(false),
2669 found_target_in_trace_(false),
2670 what_to_find_(what_to_find),
2671 visit_mode_(visit_mode),
2675 virtual void VisitPointers(Object** start, Object** end);
2678 void TracePathFrom(Object** root);
2680 bool found() const { return found_target_; }
2682 static Object* const kAnyGlobalObject;
2686 class UnmarkVisitor;
2688 void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2689 void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2690 virtual void ProcessResults();
2692 Object* search_target_;
2694 bool found_target_in_trace_;
2695 WhatToFind what_to_find_;
2696 VisitMode visit_mode_;
2697 List<Object*> object_stack_;
2699 DisallowHeapAllocation no_allocation; // i.e. no gc allowed.
2702 DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2706 } // namespace v8::internal
2708 #endif // V8_HEAP_HEAP_H_