Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / v8 / src / heap.h
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.
4
5 #ifndef V8_HEAP_H_
6 #define V8_HEAP_H_
7
8 #include <cmath>
9
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/counters.h"
13 #include "src/globals.h"
14 #include "src/incremental-marking.h"
15 #include "src/list.h"
16 #include "src/mark-compact.h"
17 #include "src/objects-visiting.h"
18 #include "src/spaces.h"
19 #include "src/splay-tree-inl.h"
20 #include "src/store-buffer.h"
21
22 namespace v8 {
23 namespace internal {
24
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(Oddball, uninitialized_value, UninitializedValue)                          \
39   V(Oddball, exception, Exception)                                             \
40   V(Map, cell_map, CellMap)                                                    \
41   V(Map, global_property_cell_map, GlobalPropertyCellMap)                      \
42   V(Map, shared_function_info_map, SharedFunctionInfoMap)                      \
43   V(Map, meta_map, MetaMap)                                                    \
44   V(Map, heap_number_map, HeapNumberMap)                                       \
45   V(Map, native_context_map, NativeContextMap)                                 \
46   V(Map, fixed_array_map, FixedArrayMap)                                       \
47   V(Map, code_map, CodeMap)                                                    \
48   V(Map, scope_info_map, ScopeInfoMap)                                         \
49   V(Map, fixed_cow_array_map, FixedCOWArrayMap)                                \
50   V(Map, fixed_double_array_map, FixedDoubleArrayMap)                          \
51   V(Map, constant_pool_array_map, ConstantPoolArrayMap)                        \
52   V(Oddball, no_interceptor_result_sentinel, NoInterceptorResultSentinel)      \
53   V(Map, hash_table_map, HashTableMap)                                         \
54   V(Map, ordered_hash_table_map, OrderedHashTableMap)                          \
55   V(FixedArray, empty_fixed_array, EmptyFixedArray)                            \
56   V(ByteArray, empty_byte_array, EmptyByteArray)                               \
57   V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray)             \
58   V(ConstantPoolArray, empty_constant_pool_array, EmptyConstantPoolArray)      \
59   V(Oddball, arguments_marker, ArgumentsMarker)                                \
60   /* The roots above this line should be boring from a GC point of view.    */ \
61   /* This means they are never in new space and never on a page that is     */ \
62   /* being compacted.                                                       */ \
63   V(FixedArray, number_string_cache, NumberStringCache)                        \
64   V(Object, instanceof_cache_function, InstanceofCacheFunction)                \
65   V(Object, instanceof_cache_map, InstanceofCacheMap)                          \
66   V(Object, instanceof_cache_answer, InstanceofCacheAnswer)                    \
67   V(FixedArray, single_character_string_cache, SingleCharacterStringCache)     \
68   V(FixedArray, string_split_cache, StringSplitCache)                          \
69   V(FixedArray, regexp_multiple_cache, RegExpMultipleCache)                    \
70   V(Oddball, termination_exception, TerminationException)                      \
71   V(Smi, hash_seed, HashSeed)                                                  \
72   V(Map, symbol_map, SymbolMap)                                                \
73   V(Map, string_map, StringMap)                                                \
74   V(Map, ascii_string_map, AsciiStringMap)                                     \
75   V(Map, cons_string_map, ConsStringMap)                                       \
76   V(Map, cons_ascii_string_map, ConsAsciiStringMap)                            \
77   V(Map, sliced_string_map, SlicedStringMap)                                   \
78   V(Map, sliced_ascii_string_map, SlicedAsciiStringMap)                        \
79   V(Map, external_string_map, ExternalStringMap)                               \
80   V(Map,                                                                       \
81     external_string_with_one_byte_data_map,                                    \
82     ExternalStringWithOneByteDataMap)                                          \
83   V(Map, external_ascii_string_map, ExternalAsciiStringMap)                    \
84   V(Map, short_external_string_map, ShortExternalStringMap)                    \
85   V(Map,                                                                       \
86     short_external_string_with_one_byte_data_map,                              \
87     ShortExternalStringWithOneByteDataMap)                                     \
88   V(Map, internalized_string_map, InternalizedStringMap)                       \
89   V(Map, ascii_internalized_string_map, AsciiInternalizedStringMap)            \
90   V(Map,                                                                       \
91     external_internalized_string_map,                                          \
92     ExternalInternalizedStringMap)                                             \
93   V(Map,                                                                       \
94     external_internalized_string_with_one_byte_data_map,                       \
95     ExternalInternalizedStringWithOneByteDataMap)                              \
96   V(Map,                                                                       \
97     external_ascii_internalized_string_map,                                    \
98     ExternalAsciiInternalizedStringMap)                                        \
99   V(Map,                                                                       \
100     short_external_internalized_string_map,                                    \
101     ShortExternalInternalizedStringMap)                                        \
102   V(Map,                                                                       \
103     short_external_internalized_string_with_one_byte_data_map,                 \
104     ShortExternalInternalizedStringWithOneByteDataMap)                         \
105   V(Map,                                                                       \
106     short_external_ascii_internalized_string_map,                              \
107     ShortExternalAsciiInternalizedStringMap)                                   \
108   V(Map, short_external_ascii_string_map, ShortExternalAsciiStringMap)         \
109   V(Map, undetectable_string_map, UndetectableStringMap)                       \
110   V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap)            \
111   V(Map, external_int8_array_map, ExternalInt8ArrayMap)                        \
112   V(Map, external_uint8_array_map, ExternalUint8ArrayMap)                      \
113   V(Map, external_int16_array_map, ExternalInt16ArrayMap)                      \
114   V(Map, external_uint16_array_map, ExternalUint16ArrayMap)                    \
115   V(Map, external_int32_array_map, ExternalInt32ArrayMap)                      \
116   V(Map, external_int32x4_array_map, ExternalInt32x4ArrayMap)                  \
117   V(Map, external_uint32_array_map, ExternalUint32ArrayMap)                    \
118   V(Map, external_float32_array_map, ExternalFloat32ArrayMap)                  \
119   V(Map, external_float32x4_array_map, ExternalFloat32x4ArrayMap)              \
120   V(Map, external_float64x2_array_map, ExternalFloat64x2ArrayMap)              \
121   V(Map, external_float64_array_map, ExternalFloat64ArrayMap)                  \
122   V(Map, external_uint8_clamped_array_map, ExternalUint8ClampedArrayMap)       \
123   V(ExternalArray, empty_external_int8_array,                                  \
124       EmptyExternalInt8Array)                                                  \
125   V(ExternalArray, empty_external_uint8_array,                                 \
126       EmptyExternalUint8Array)                                                 \
127   V(ExternalArray, empty_external_int16_array, EmptyExternalInt16Array)        \
128   V(ExternalArray, empty_external_uint16_array,                                \
129       EmptyExternalUint16Array)                                                \
130   V(ExternalArray, empty_external_int32_array, EmptyExternalInt32Array)        \
131   V(ExternalArray, empty_external_int32x4_array, EmptyExternalInt32x4Array)    \
132   V(ExternalArray, empty_external_uint32_array,                                \
133       EmptyExternalUint32Array)                                                \
134   V(ExternalArray, empty_external_float32_array, EmptyExternalFloat32Array)    \
135   V(ExternalArray, empty_external_float32x4_array, EmptyExternalFloat32x4Array)\
136   V(ExternalArray, empty_external_float64x2_array, EmptyExternalFloat64x2Array)\
137   V(ExternalArray, empty_external_float64_array, EmptyExternalFloat64Array)    \
138   V(ExternalArray, empty_external_uint8_clamped_array,                         \
139       EmptyExternalUint8ClampedArray)                                          \
140   V(Map, fixed_uint8_array_map, FixedUint8ArrayMap)                            \
141   V(Map, fixed_int8_array_map, FixedInt8ArrayMap)                              \
142   V(Map, fixed_uint16_array_map, FixedUint16ArrayMap)                          \
143   V(Map, fixed_int16_array_map, FixedInt16ArrayMap)                            \
144   V(Map, fixed_uint32_array_map, FixedUint32ArrayMap)                          \
145   V(Map, fixed_int32_array_map, FixedInt32ArrayMap)                            \
146   V(Map, fixed_int32x4_array_map, FixedInt32x4ArrayMap)                        \
147   V(Map, fixed_float32_array_map, FixedFloat32ArrayMap)                        \
148   V(Map, fixed_float32x4_array_map, FixedFloat32x4ArrayMap)                    \
149   V(Map, fixed_float64x2_array_map, FixedFloat64x2ArrayMap)                    \
150   V(Map, fixed_float64_array_map, FixedFloat64ArrayMap)                        \
151   V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap)             \
152   V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array)        \
153   V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array)          \
154   V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array)      \
155   V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array)        \
156   V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array)      \
157   V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array)        \
158   V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array)    \
159   V(FixedTypedArrayBase, empty_fixed_float32x4_array,                          \
160       EmptyFixedFloat32x4Array)                                                \
161   V(FixedTypedArrayBase, empty_fixed_float64x2_array,                          \
162       EmptyFixedFloat64x2Array)                                                \
163   V(FixedTypedArrayBase, empty_fixed_int32x4_array, EmptyFixedInt32x4Array)    \
164   V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array)    \
165   V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array,                      \
166       EmptyFixedUint8ClampedArray)                                             \
167   V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap)            \
168   V(Map, function_context_map, FunctionContextMap)                             \
169   V(Map, catch_context_map, CatchContextMap)                                   \
170   V(Map, with_context_map, WithContextMap)                                     \
171   V(Map, block_context_map, BlockContextMap)                                   \
172   V(Map, module_context_map, ModuleContextMap)                                 \
173   V(Map, global_context_map, GlobalContextMap)                                 \
174   V(Map, undefined_map, UndefinedMap)                                          \
175   V(Map, the_hole_map, TheHoleMap)                                             \
176   V(Map, null_map, NullMap)                                                    \
177   V(Map, boolean_map, BooleanMap)                                              \
178   V(Map, uninitialized_map, UninitializedMap)                                  \
179   V(Map, arguments_marker_map, ArgumentsMarkerMap)                             \
180   V(Map, no_interceptor_result_sentinel_map, NoInterceptorResultSentinelMap)   \
181   V(Map, exception_map, ExceptionMap)                                          \
182   V(Map, termination_exception_map, TerminationExceptionMap)                   \
183   V(Map, message_object_map, JSMessageObjectMap)                               \
184   V(Map, foreign_map, ForeignMap)                                              \
185   V(HeapNumber, nan_value, NanValue)                                           \
186   V(HeapNumber, infinity_value, InfinityValue)                                 \
187   V(HeapNumber, minus_zero_value, MinusZeroValue)                              \
188   V(Map, neander_map, NeanderMap)                                              \
189   V(JSObject, message_listeners, MessageListeners)                             \
190   V(UnseededNumberDictionary, code_stubs, CodeStubs)                           \
191   V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache)      \
192   V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache)        \
193   V(Code, js_entry_code, JsEntryCode)                                          \
194   V(Code, js_construct_entry_code, JsConstructEntryCode)                       \
195   V(FixedArray, natives_source_cache, NativesSourceCache)                      \
196   V(Script, empty_script, EmptyScript)                                         \
197   V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames)          \
198   V(Cell, undefined_cell, UndefineCell)                                        \
199   V(JSObject, observation_state, ObservationState)                             \
200   V(Map, external_map, ExternalMap)                                            \
201   V(Object, symbol_registry, SymbolRegistry)                                   \
202   V(Symbol, frozen_symbol, FrozenSymbol)                                       \
203   V(Symbol, nonexistent_symbol, NonExistentSymbol)                             \
204   V(Symbol, elements_transition_symbol, ElementsTransitionSymbol)              \
205   V(SeededNumberDictionary, empty_slow_element_dictionary,                     \
206       EmptySlowElementDictionary)                                              \
207   V(Symbol, observed_symbol, ObservedSymbol)                                   \
208   V(Symbol, uninitialized_symbol, UninitializedSymbol)                         \
209   V(Symbol, megamorphic_symbol, MegamorphicSymbol)                             \
210   V(FixedArray, materialized_objects, MaterializedObjects)                     \
211   V(FixedArray, allocation_sites_scratchpad, AllocationSitesScratchpad)        \
212   V(FixedArray, microtask_queue, MicrotaskQueue)
213
214 // Entries in this list are limited to Smis and are not visited during GC.
215 #define SMI_ROOT_LIST(V)                                                       \
216   V(Smi, stack_limit, StackLimit)                                              \
217   V(Smi, real_stack_limit, RealStackLimit)                                     \
218   V(Smi, last_script_id, LastScriptId)                                         \
219   V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset)     \
220   V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset)           \
221   V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset)                 \
222   V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
223
224 #define ROOT_LIST(V)                                  \
225   STRONG_ROOT_LIST(V)                                 \
226   SMI_ROOT_LIST(V)                                    \
227   V(StringTable, string_table, StringTable)
228
229 // Heap roots that are known to be immortal immovable, for which we can safely
230 // skip write barriers.
231 #define IMMORTAL_IMMOVABLE_ROOT_LIST(V)   \
232   V(byte_array_map)                       \
233   V(free_space_map)                       \
234   V(one_pointer_filler_map)               \
235   V(two_pointer_filler_map)               \
236   V(undefined_value)                      \
237   V(the_hole_value)                       \
238   V(null_value)                           \
239   V(true_value)                           \
240   V(false_value)                          \
241   V(uninitialized_value)                  \
242   V(cell_map)                             \
243   V(global_property_cell_map)             \
244   V(shared_function_info_map)             \
245   V(meta_map)                             \
246   V(heap_number_map)                      \
247   V(native_context_map)                   \
248   V(fixed_array_map)                      \
249   V(code_map)                             \
250   V(scope_info_map)                       \
251   V(fixed_cow_array_map)                  \
252   V(fixed_double_array_map)               \
253   V(constant_pool_array_map)              \
254   V(no_interceptor_result_sentinel)       \
255   V(hash_table_map)                       \
256   V(ordered_hash_table_map)               \
257   V(empty_fixed_array)                    \
258   V(empty_byte_array)                     \
259   V(empty_descriptor_array)               \
260   V(empty_constant_pool_array)            \
261   V(arguments_marker)                     \
262   V(symbol_map)                           \
263   V(sloppy_arguments_elements_map)        \
264   V(function_context_map)                 \
265   V(catch_context_map)                    \
266   V(with_context_map)                     \
267   V(block_context_map)                    \
268   V(module_context_map)                   \
269   V(global_context_map)                   \
270   V(undefined_map)                        \
271   V(the_hole_map)                         \
272   V(null_map)                             \
273   V(boolean_map)                          \
274   V(uninitialized_map)                    \
275   V(message_object_map)                   \
276   V(foreign_map)                          \
277   V(neander_map)
278
279 #define INTERNALIZED_STRING_LIST(V)                                      \
280   V(Array_string, "Array")                                               \
281   V(Object_string, "Object")                                             \
282   V(proto_string, "__proto__")                                           \
283   V(arguments_string, "arguments")                                       \
284   V(Arguments_string, "Arguments")                                       \
285   V(call_string, "call")                                                 \
286   V(apply_string, "apply")                                               \
287   V(caller_string, "caller")                                             \
288   V(boolean_string, "boolean")                                           \
289   V(Boolean_string, "Boolean")                                           \
290   V(callee_string, "callee")                                             \
291   V(constructor_string, "constructor")                                   \
292   V(dot_result_string, ".result")                                        \
293   V(dot_for_string, ".for.")                                             \
294   V(dot_iterable_string, ".iterable")                                    \
295   V(dot_iterator_string, ".iterator")                                    \
296   V(dot_generator_object_string, ".generator_object")                    \
297   V(eval_string, "eval")                                                 \
298   V(empty_string, "")                                                    \
299   V(function_string, "function")                                         \
300   V(length_string, "length")                                             \
301   V(module_string, "module")                                             \
302   V(name_string, "name")                                                 \
303   V(native_string, "native")                                             \
304   V(null_string, "null")                                                 \
305   V(number_string, "number")                                             \
306   V(Number_string, "Number")                                             \
307   V(float32x4_string, "float32x4")                                       \
308   V(float64x2_string, "float64x2")                                       \
309   V(int32x4_string, "int32x4")                                           \
310   V(nan_string, "NaN")                                                   \
311   V(RegExp_string, "RegExp")                                             \
312   V(source_string, "source")                                             \
313   V(global_string, "global")                                             \
314   V(ignore_case_string, "ignoreCase")                                    \
315   V(multiline_string, "multiline")                                       \
316   V(input_string, "input")                                               \
317   V(index_string, "index")                                               \
318   V(last_index_string, "lastIndex")                                      \
319   V(object_string, "object")                                             \
320   V(literals_string, "literals")                                         \
321   V(prototype_string, "prototype")                                       \
322   V(string_string, "string")                                             \
323   V(String_string, "String")                                             \
324   V(symbol_string, "symbol")                                             \
325   V(Symbol_string, "Symbol")                                             \
326   V(for_string, "for")                                                   \
327   V(for_api_string, "for_api")                                           \
328   V(for_intern_string, "for_intern")                                     \
329   V(private_api_string, "private_api")                                   \
330   V(private_intern_string, "private_intern")                             \
331   V(Date_string, "Date")                                                 \
332   V(this_string, "this")                                                 \
333   V(to_string_string, "toString")                                        \
334   V(char_at_string, "CharAt")                                            \
335   V(undefined_string, "undefined")                                       \
336   V(value_of_string, "valueOf")                                          \
337   V(stack_string, "stack")                                               \
338   V(toJSON_string, "toJSON")                                             \
339   V(InitializeVarGlobal_string, "InitializeVarGlobal")                   \
340   V(InitializeConstGlobal_string, "InitializeConstGlobal")               \
341   V(KeyedLoadElementMonomorphic_string,                                  \
342     "KeyedLoadElementMonomorphic")                                       \
343   V(KeyedStoreElementMonomorphic_string,                                 \
344     "KeyedStoreElementMonomorphic")                                      \
345   V(stack_overflow_string, "kStackOverflowBoilerplate")                  \
346   V(illegal_access_string, "illegal access")                             \
347   V(get_string, "get")                                                   \
348   V(set_string, "set")                                                   \
349   V(map_field_string, "%map")                                            \
350   V(elements_field_string, "%elements")                                  \
351   V(length_field_string, "%length")                                      \
352   V(cell_value_string, "%cell_value")                                    \
353   V(function_class_string, "Function")                                   \
354   V(illegal_argument_string, "illegal argument")                         \
355   V(MakeReferenceError_string, "MakeReferenceError")                     \
356   V(MakeSyntaxError_string, "MakeSyntaxError")                           \
357   V(MakeTypeError_string, "MakeTypeError")                               \
358   V(unknown_label_string, "unknown_label")                               \
359   V(space_string, " ")                                                   \
360   V(exec_string, "exec")                                                 \
361   V(zero_string, "0")                                                    \
362   V(global_eval_string, "GlobalEval")                                    \
363   V(identity_hash_string, "v8::IdentityHash")                            \
364   V(closure_string, "(closure)")                                         \
365   V(use_strict_string, "use strict")                                     \
366   V(dot_string, ".")                                                     \
367   V(anonymous_function_string, "(anonymous function)")                   \
368   V(compare_ic_string, "==")                                             \
369   V(strict_compare_ic_string, "===")                                     \
370   V(infinity_string, "Infinity")                                         \
371   V(minus_infinity_string, "-Infinity")                                  \
372   V(hidden_stack_trace_string, "v8::hidden_stack_trace")                 \
373   V(query_colon_string, "(?:)")                                          \
374   V(Generator_string, "Generator")                                       \
375   V(throw_string, "throw")                                               \
376   V(done_string, "done")                                                 \
377   V(value_string, "value")                                               \
378   V(signMask, "signMask")                                                \
379   V(x, "x")                                                              \
380   V(y, "y")                                                              \
381   V(z, "z")                                                              \
382   V(w, "w")                                                              \
383   V(flagX, "flagX")                                                      \
384   V(flagY, "flagY")                                                      \
385   V(flagZ, "flagZ")                                                      \
386   V(flagW, "flagW")                                                      \
387   V(simd, "SIMD")                                                        \
388   V(next_string, "next")                                                 \
389   V(byte_length_string, "byteLength")                                    \
390   V(byte_offset_string, "byteOffset")                                    \
391   V(buffer_string, "buffer")                                             \
392   V(intl_initialized_marker_string, "v8::intl_initialized_marker")       \
393   V(intl_impl_object_string, "v8::intl_object")
394
395 // Forward declarations.
396 class GCTracer;
397 class HeapStats;
398 class Isolate;
399 class WeakObjectRetainer;
400
401
402 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
403                                                       Object** pointer);
404
405 class StoreBufferRebuilder {
406  public:
407   explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
408       : store_buffer_(store_buffer) {
409   }
410
411   void Callback(MemoryChunk* page, StoreBufferEvent event);
412
413  private:
414   StoreBuffer* store_buffer_;
415
416   // We record in this variable how full the store buffer was when we started
417   // iterating over the current page, finding pointers to new space.  If the
418   // store buffer overflows again we can exempt the page from the store buffer
419   // by rewinding to this point instead of having to search the store buffer.
420   Object*** start_of_current_page_;
421   // The current page we are scanning in the store buffer iterator.
422   MemoryChunk* current_page_;
423 };
424
425
426
427 // A queue of objects promoted during scavenge. Each object is accompanied
428 // by it's size to avoid dereferencing a map pointer for scanning.
429 class PromotionQueue {
430  public:
431   explicit PromotionQueue(Heap* heap)
432       : front_(NULL),
433         rear_(NULL),
434         limit_(NULL),
435         emergency_stack_(0),
436         heap_(heap) { }
437
438   void Initialize();
439
440   void Destroy() {
441     ASSERT(is_empty());
442     delete emergency_stack_;
443     emergency_stack_ = NULL;
444   }
445
446   inline void ActivateGuardIfOnTheSamePage();
447
448   Page* GetHeadPage() {
449     return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
450   }
451
452   void SetNewLimit(Address limit) {
453     if (!guard_) {
454       return;
455     }
456
457     ASSERT(GetHeadPage() == Page::FromAllocationTop(limit));
458     limit_ = reinterpret_cast<intptr_t*>(limit);
459
460     if (limit_ <= rear_) {
461       return;
462     }
463
464     RelocateQueueHead();
465   }
466
467   bool is_empty() {
468     return (front_ == rear_) &&
469         (emergency_stack_ == NULL || emergency_stack_->length() == 0);
470   }
471
472   inline void insert(HeapObject* target, int size);
473
474   void remove(HeapObject** target, int* size) {
475     ASSERT(!is_empty());
476     if (front_ == rear_) {
477       Entry e = emergency_stack_->RemoveLast();
478       *target = e.obj_;
479       *size = e.size_;
480       return;
481     }
482
483     if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(front_))) {
484       NewSpacePage* front_page =
485           NewSpacePage::FromAddress(reinterpret_cast<Address>(front_));
486       ASSERT(!front_page->prev_page()->is_anchor());
487       front_ =
488           reinterpret_cast<intptr_t*>(front_page->prev_page()->area_end());
489     }
490     *target = reinterpret_cast<HeapObject*>(*(--front_));
491     *size = static_cast<int>(*(--front_));
492     // Assert no underflow.
493     SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
494                                 reinterpret_cast<Address>(front_));
495   }
496
497  private:
498   // The front of the queue is higher in the memory page chain than the rear.
499   intptr_t* front_;
500   intptr_t* rear_;
501   intptr_t* limit_;
502
503   bool guard_;
504
505   static const int kEntrySizeInWords = 2;
506
507   struct Entry {
508     Entry(HeapObject* obj, int size) : obj_(obj), size_(size) { }
509
510     HeapObject* obj_;
511     int size_;
512   };
513   List<Entry>* emergency_stack_;
514
515   Heap* heap_;
516
517   void RelocateQueueHead();
518
519   DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
520 };
521
522
523 typedef void (*ScavengingCallback)(Map* map,
524                                    HeapObject** slot,
525                                    HeapObject* object);
526
527
528 // External strings table is a place where all external strings are
529 // registered.  We need to keep track of such strings to properly
530 // finalize them.
531 class ExternalStringTable {
532  public:
533   // Registers an external string.
534   inline void AddString(String* string);
535
536   inline void Iterate(ObjectVisitor* v);
537
538   // Restores internal invariant and gets rid of collected strings.
539   // Must be called after each Iterate() that modified the strings.
540   void CleanUp();
541
542   // Destroys all allocated memory.
543   void TearDown();
544
545  private:
546   explicit ExternalStringTable(Heap* heap) : heap_(heap) { }
547
548   friend class Heap;
549
550   inline void Verify();
551
552   inline void AddOldString(String* string);
553
554   // Notifies the table that only a prefix of the new list is valid.
555   inline void ShrinkNewStrings(int position);
556
557   // To speed up scavenge collections new space string are kept
558   // separate from old space strings.
559   List<Object*> new_space_strings_;
560   List<Object*> old_space_strings_;
561
562   Heap* heap_;
563
564   DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
565 };
566
567
568 enum ArrayStorageAllocationMode {
569   DONT_INITIALIZE_ARRAY_ELEMENTS,
570   INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
571 };
572
573
574 class Heap {
575  public:
576   // Configure heap size in MB before setup. Return false if the heap has been
577   // set up already.
578   bool ConfigureHeap(int max_semi_space_size,
579                      int max_old_space_size,
580                      int max_executable_size,
581                      size_t code_range_size);
582   bool ConfigureHeapDefault();
583
584   // Prepares the heap, setting up memory areas that are needed in the isolate
585   // without actually creating any objects.
586   bool SetUp();
587
588   // Bootstraps the object heap with the core set of objects required to run.
589   // Returns whether it succeeded.
590   bool CreateHeapObjects();
591
592   // Destroys all memory allocated by the heap.
593   void TearDown();
594
595   // Set the stack limit in the roots_ array.  Some architectures generate
596   // code that looks here, because it is faster than loading from the static
597   // jslimit_/real_jslimit_ variable in the StackGuard.
598   void SetStackLimits();
599
600   // Returns whether SetUp has been called.
601   bool HasBeenSetUp();
602
603   // Returns the maximum amount of memory reserved for the heap.  For
604   // the young generation, we reserve 4 times the amount needed for a
605   // semi space.  The young generation consists of two semi spaces and
606   // we reserve twice the amount needed for those in order to ensure
607   // that new space can be aligned to its size.
608   intptr_t MaxReserved() {
609     return 4 * reserved_semispace_size_ + max_old_generation_size_;
610   }
611   int MaxSemiSpaceSize() { return max_semi_space_size_; }
612   int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
613   int InitialSemiSpaceSize() { return initial_semispace_size_; }
614   intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
615   intptr_t MaxExecutableSize() { return max_executable_size_; }
616
617   // Returns the capacity of the heap in bytes w/o growing. Heap grows when
618   // more spaces are needed until it reaches the limit.
619   intptr_t Capacity();
620
621   // Returns the amount of memory currently committed for the heap.
622   intptr_t CommittedMemory();
623
624   // Returns the amount of executable memory currently committed for the heap.
625   intptr_t CommittedMemoryExecutable();
626
627   // Returns the amount of phyical memory currently committed for the heap.
628   size_t CommittedPhysicalMemory();
629
630   // Returns the maximum amount of memory ever committed for the heap.
631   intptr_t MaximumCommittedMemory() { return maximum_committed_; }
632
633   // Updates the maximum committed memory for the heap. Should be called
634   // whenever a space grows.
635   void UpdateMaximumCommitted();
636
637   // Returns the available bytes in space w/o growing.
638   // Heap doesn't guarantee that it can allocate an object that requires
639   // all available bytes. Check MaxHeapObjectSize() instead.
640   intptr_t Available();
641
642   // Returns of size of all objects residing in the heap.
643   intptr_t SizeOfObjects();
644
645   // Return the starting address and a mask for the new space.  And-masking an
646   // address with the mask will result in the start address of the new space
647   // for all addresses in either semispace.
648   Address NewSpaceStart() { return new_space_.start(); }
649   uintptr_t NewSpaceMask() { return new_space_.mask(); }
650   Address NewSpaceTop() { return new_space_.top(); }
651
652   NewSpace* new_space() { return &new_space_; }
653   OldSpace* old_pointer_space() { return old_pointer_space_; }
654   OldSpace* old_data_space() { return old_data_space_; }
655   OldSpace* code_space() { return code_space_; }
656   MapSpace* map_space() { return map_space_; }
657   CellSpace* cell_space() { return cell_space_; }
658   PropertyCellSpace* property_cell_space() {
659     return property_cell_space_;
660   }
661   LargeObjectSpace* lo_space() { return lo_space_; }
662   PagedSpace* paged_space(int idx) {
663     switch (idx) {
664       case OLD_POINTER_SPACE:
665         return old_pointer_space();
666       case OLD_DATA_SPACE:
667         return old_data_space();
668       case MAP_SPACE:
669         return map_space();
670       case CELL_SPACE:
671         return cell_space();
672       case PROPERTY_CELL_SPACE:
673         return property_cell_space();
674       case CODE_SPACE:
675         return code_space();
676       case NEW_SPACE:
677       case LO_SPACE:
678         UNREACHABLE();
679     }
680     return NULL;
681   }
682
683   bool always_allocate() { return always_allocate_scope_depth_ != 0; }
684   Address always_allocate_scope_depth_address() {
685     return reinterpret_cast<Address>(&always_allocate_scope_depth_);
686   }
687   bool linear_allocation() {
688     return linear_allocation_scope_depth_ != 0;
689   }
690
691   Address* NewSpaceAllocationTopAddress() {
692     return new_space_.allocation_top_address();
693   }
694   Address* NewSpaceAllocationLimitAddress() {
695     return new_space_.allocation_limit_address();
696   }
697
698   Address* OldPointerSpaceAllocationTopAddress() {
699     return old_pointer_space_->allocation_top_address();
700   }
701   Address* OldPointerSpaceAllocationLimitAddress() {
702     return old_pointer_space_->allocation_limit_address();
703   }
704
705   Address* OldDataSpaceAllocationTopAddress() {
706     return old_data_space_->allocation_top_address();
707   }
708   Address* OldDataSpaceAllocationLimitAddress() {
709     return old_data_space_->allocation_limit_address();
710   }
711
712   // Returns a deep copy of the JavaScript object.
713   // Properties and elements are copied too.
714   // Optionally takes an AllocationSite to be appended in an AllocationMemento.
715   MUST_USE_RESULT AllocationResult CopyJSObject(JSObject* source,
716                                                 AllocationSite* site = NULL);
717
718   // Clear the Instanceof cache (used when a prototype changes).
719   inline void ClearInstanceofCache();
720
721   // Iterates the whole code space to clear all ICs of the given kind.
722   void ClearAllICsByKind(Code::Kind kind);
723
724   // For use during bootup.
725   void RepairFreeListsAfterBoot();
726
727   template<typename T>
728   static inline bool IsOneByte(T t, int chars);
729
730   // Move len elements within a given array from src_index index to dst_index
731   // index.
732   void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
733
734   // Sloppy mode arguments object size.
735   static const int kSloppyArgumentsObjectSize =
736       JSObject::kHeaderSize + 2 * kPointerSize;
737   // Strict mode arguments has no callee so it is smaller.
738   static const int kStrictArgumentsObjectSize =
739       JSObject::kHeaderSize + 1 * kPointerSize;
740   // Indicies for direct access into argument objects.
741   static const int kArgumentsLengthIndex = 0;
742   // callee is only valid in sloppy mode.
743   static const int kArgumentsCalleeIndex = 1;
744
745   // Finalizes an external string by deleting the associated external
746   // data and clearing the resource pointer.
747   inline void FinalizeExternalString(String* string);
748
749   // Initialize a filler object to keep the ability to iterate over the heap
750   // when shortening objects.
751   void CreateFillerObjectAt(Address addr, int size);
752
753   bool CanMoveObjectStart(HeapObject* object);
754
755   enum InvocationMode { FROM_GC, FROM_MUTATOR };
756
757   // Maintain marking consistency for IncrementalMarking.
758   void AdjustLiveBytes(Address address, int by, InvocationMode mode);
759
760   // Converts the given boolean condition to JavaScript boolean value.
761   inline Object* ToBoolean(bool condition);
762
763   // Performs garbage collection operation.
764   // Returns whether there is a chance that another major GC could
765   // collect more garbage.
766   inline bool CollectGarbage(
767       AllocationSpace space,
768       const char* gc_reason = NULL,
769       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
770
771   static const int kNoGCFlags = 0;
772   static const int kSweepPreciselyMask = 1;
773   static const int kReduceMemoryFootprintMask = 2;
774   static const int kAbortIncrementalMarkingMask = 4;
775
776   // Making the heap iterable requires us to sweep precisely and abort any
777   // incremental marking as well.
778   static const int kMakeHeapIterableMask =
779       kSweepPreciselyMask | kAbortIncrementalMarkingMask;
780
781   // Performs a full garbage collection.  If (flags & kMakeHeapIterableMask) is
782   // non-zero, then the slower precise sweeper is used, which leaves the heap
783   // in a state where we can iterate over the heap visiting all objects.
784   void CollectAllGarbage(
785       int flags,
786       const char* gc_reason = NULL,
787       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
788
789   // Last hope GC, should try to squeeze as much as possible.
790   void CollectAllAvailableGarbage(const char* gc_reason = NULL);
791
792   // Check whether the heap is currently iterable.
793   bool IsHeapIterable();
794
795   // Notify the heap that a context has been disposed.
796   int NotifyContextDisposed();
797
798   inline void increment_scan_on_scavenge_pages() {
799     scan_on_scavenge_pages_++;
800     if (FLAG_gc_verbose) {
801       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
802     }
803   }
804
805   inline void decrement_scan_on_scavenge_pages() {
806     scan_on_scavenge_pages_--;
807     if (FLAG_gc_verbose) {
808       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
809     }
810   }
811
812   PromotionQueue* promotion_queue() { return &promotion_queue_; }
813
814   void AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
815                              GCType gc_type_filter,
816                              bool pass_isolate = true);
817   void RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback);
818
819   void AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
820                              GCType gc_type_filter,
821                              bool pass_isolate = true);
822   void RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback);
823
824   // Heap root getters.  We have versions with and without type::cast() here.
825   // You can't use type::cast during GC because the assert fails.
826   // TODO(1490): Try removing the unchecked accessors, now that GC marking does
827   // not corrupt the map.
828 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
829   type* name() {                                                               \
830     return type::cast(roots_[k##camel_name##RootIndex]);                       \
831   }                                                                            \
832   type* raw_unchecked_##name() {                                               \
833     return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]);          \
834   }
835   ROOT_LIST(ROOT_ACCESSOR)
836 #undef ROOT_ACCESSOR
837
838 // Utility type maps
839 #define STRUCT_MAP_ACCESSOR(NAME, Name, name)                                  \
840     Map* name##_map() {                                                        \
841       return Map::cast(roots_[k##Name##MapRootIndex]);                         \
842     }
843   STRUCT_LIST(STRUCT_MAP_ACCESSOR)
844 #undef STRUCT_MAP_ACCESSOR
845
846 #define STRING_ACCESSOR(name, str) String* name() {                            \
847     return String::cast(roots_[k##name##RootIndex]);                           \
848   }
849   INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
850 #undef STRING_ACCESSOR
851
852   // The hidden_string is special because it is the empty string, but does
853   // not match the empty string.
854   String* hidden_string() { return hidden_string_; }
855
856   void set_native_contexts_list(Object* object) {
857     native_contexts_list_ = object;
858   }
859   Object* native_contexts_list() const { return native_contexts_list_; }
860
861   void set_array_buffers_list(Object* object) {
862     array_buffers_list_ = object;
863   }
864   Object* array_buffers_list() const { return array_buffers_list_; }
865
866   void set_allocation_sites_list(Object* object) {
867     allocation_sites_list_ = object;
868   }
869   Object* allocation_sites_list() { return allocation_sites_list_; }
870
871   // Used in CreateAllocationSiteStub and the (de)serializer.
872   Object** allocation_sites_list_address() { return &allocation_sites_list_; }
873
874   Object* weak_object_to_code_table() { return weak_object_to_code_table_; }
875
876   void set_encountered_weak_collections(Object* weak_collection) {
877     encountered_weak_collections_ = weak_collection;
878   }
879   Object* encountered_weak_collections() const {
880     return encountered_weak_collections_;
881   }
882
883   // Number of mark-sweeps.
884   unsigned int ms_count() { return ms_count_; }
885
886   // Iterates over all roots in the heap.
887   void IterateRoots(ObjectVisitor* v, VisitMode mode);
888   // Iterates over all strong roots in the heap.
889   void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
890   // Iterates over entries in the smi roots list.  Only interesting to the
891   // serializer/deserializer, since GC does not care about smis.
892   void IterateSmiRoots(ObjectVisitor* v);
893   // Iterates over all the other roots in the heap.
894   void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
895
896   // Iterate pointers to from semispace of new space found in memory interval
897   // from start to end.
898   void IterateAndMarkPointersToFromSpace(Address start,
899                                          Address end,
900                                          ObjectSlotCallback callback);
901
902   // Returns whether the object resides in new space.
903   inline bool InNewSpace(Object* object);
904   inline bool InNewSpace(Address address);
905   inline bool InNewSpacePage(Address address);
906   inline bool InFromSpace(Object* object);
907   inline bool InToSpace(Object* object);
908
909   // Returns whether the object resides in old pointer space.
910   inline bool InOldPointerSpace(Address address);
911   inline bool InOldPointerSpace(Object* object);
912
913   // Returns whether the object resides in old data space.
914   inline bool InOldDataSpace(Address address);
915   inline bool InOldDataSpace(Object* object);
916
917   // Checks whether an address/object in the heap (including auxiliary
918   // area and unused area).
919   bool Contains(Address addr);
920   bool Contains(HeapObject* value);
921
922   // Checks whether an address/object in a space.
923   // Currently used by tests, serialization and heap verification only.
924   bool InSpace(Address addr, AllocationSpace space);
925   bool InSpace(HeapObject* value, AllocationSpace space);
926
927   // Finds out which space an object should get promoted to based on its type.
928   inline OldSpace* TargetSpace(HeapObject* object);
929   static inline AllocationSpace TargetSpaceId(InstanceType type);
930
931   // Checks whether the given object is allowed to be migrated from it's
932   // current space into the given destination space. Used for debugging.
933   inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
934
935   // Sets the stub_cache_ (only used when expanding the dictionary).
936   void public_set_code_stubs(UnseededNumberDictionary* value) {
937     roots_[kCodeStubsRootIndex] = value;
938   }
939
940   // Support for computing object sizes for old objects during GCs. Returns
941   // a function that is guaranteed to be safe for computing object sizes in
942   // the current GC phase.
943   HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
944     return gc_safe_size_of_old_object_;
945   }
946
947   // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
948   void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
949     roots_[kNonMonomorphicCacheRootIndex] = value;
950   }
951
952   void public_set_empty_script(Script* script) {
953     roots_[kEmptyScriptRootIndex] = script;
954   }
955
956   void public_set_store_buffer_top(Address* top) {
957     roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
958   }
959
960   void public_set_materialized_objects(FixedArray* objects) {
961     roots_[kMaterializedObjectsRootIndex] = objects;
962   }
963
964   // Generated code can embed this address to get access to the roots.
965   Object** roots_array_start() { return roots_; }
966
967   Address* store_buffer_top_address() {
968     return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
969   }
970
971 #ifdef VERIFY_HEAP
972   // Verify the heap is in its normal state before or after a GC.
973   void Verify();
974
975
976   bool weak_embedded_objects_verification_enabled() {
977     return no_weak_object_verification_scope_depth_ == 0;
978   }
979 #endif
980
981 #ifdef DEBUG
982   void Print();
983   void PrintHandles();
984
985   void OldPointerSpaceCheckStoreBuffer();
986   void MapSpaceCheckStoreBuffer();
987   void LargeObjectSpaceCheckStoreBuffer();
988
989   // Report heap statistics.
990   void ReportHeapStatistics(const char* title);
991   void ReportCodeStatistics(const char* title);
992 #endif
993
994   // Zapping is needed for verify heap, and always done in debug builds.
995   static inline bool ShouldZapGarbage() {
996 #ifdef DEBUG
997     return true;
998 #else
999 #ifdef VERIFY_HEAP
1000     return FLAG_verify_heap;
1001 #else
1002     return false;
1003 #endif
1004 #endif
1005   }
1006
1007   // Print short heap statistics.
1008   void PrintShortHeapStatistics();
1009
1010   // Write barrier support for address[offset] = o.
1011   INLINE(void RecordWrite(Address address, int offset));
1012
1013   // Write barrier support for address[start : start + len[ = o.
1014   INLINE(void RecordWrites(Address address, int start, int len));
1015
1016   enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1017   inline HeapState gc_state() { return gc_state_; }
1018
1019   inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1020
1021 #ifdef DEBUG
1022   void set_allocation_timeout(int timeout) {
1023     allocation_timeout_ = timeout;
1024   }
1025
1026   void TracePathToObjectFrom(Object* target, Object* root);
1027   void TracePathToObject(Object* target);
1028   void TracePathToGlobal();
1029 #endif
1030
1031   // Callback function passed to Heap::Iterate etc.  Copies an object if
1032   // necessary, the object might be promoted to an old space.  The caller must
1033   // ensure the precondition that the object is (a) a heap object and (b) in
1034   // the heap's from space.
1035   static inline void ScavengePointer(HeapObject** p);
1036   static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1037
1038   enum ScratchpadSlotMode {
1039     IGNORE_SCRATCHPAD_SLOT,
1040     RECORD_SCRATCHPAD_SLOT
1041   };
1042
1043   // If an object has an AllocationMemento trailing it, return it, otherwise
1044   // return NULL;
1045   inline AllocationMemento* FindAllocationMemento(HeapObject* object);
1046
1047   // An object may have an AllocationSite associated with it through a trailing
1048   // AllocationMemento. Its feedback should be updated when objects are found
1049   // in the heap.
1050   static inline void UpdateAllocationSiteFeedback(
1051       HeapObject* object, ScratchpadSlotMode mode);
1052
1053   // Support for partial snapshots.  After calling this we have a linear
1054   // space to write objects in each space.
1055   void ReserveSpace(int *sizes, Address* addresses);
1056
1057   //
1058   // Support for the API.
1059   //
1060
1061   void CreateApiObjects();
1062
1063   inline intptr_t PromotedTotalSize() {
1064     int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1065     if (total > kMaxInt) return static_cast<intptr_t>(kMaxInt);
1066     if (total < 0) return 0;
1067     return static_cast<intptr_t>(total);
1068   }
1069
1070   inline intptr_t OldGenerationSpaceAvailable() {
1071     return old_generation_allocation_limit_ - PromotedTotalSize();
1072   }
1073
1074   inline intptr_t OldGenerationCapacityAvailable() {
1075     return max_old_generation_size_ - PromotedTotalSize();
1076   }
1077
1078   static const intptr_t kMinimumOldGenerationAllocationLimit =
1079       8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1080
1081   static const int kPointerMultiplier = i::kPointerSize / 4;
1082
1083   // The new space size has to be a power of 2. Sizes are in MB.
1084   static const int kMaxSemiSpaceSizeLowMemoryDevice =
1085       1 * kPointerMultiplier;
1086   static const int kMaxSemiSpaceSizeMediumMemoryDevice =
1087       4 * kPointerMultiplier;
1088   static const int kMaxSemiSpaceSizeHighMemoryDevice =
1089       8 * kPointerMultiplier;
1090   static const int kMaxSemiSpaceSizeHugeMemoryDevice =
1091       8 * kPointerMultiplier;
1092
1093   // The old space size has to be a multiple of Page::kPageSize.
1094   // Sizes are in MB.
1095   static const int kMaxOldSpaceSizeLowMemoryDevice =
1096       128 * kPointerMultiplier;
1097   static const int kMaxOldSpaceSizeMediumMemoryDevice =
1098       256 * kPointerMultiplier;
1099   static const int kMaxOldSpaceSizeHighMemoryDevice =
1100       512 * kPointerMultiplier;
1101   static const int kMaxOldSpaceSizeHugeMemoryDevice =
1102       700 * kPointerMultiplier;
1103
1104   // The executable size has to be a multiple of Page::kPageSize.
1105   // Sizes are in MB.
1106   static const int kMaxExecutableSizeLowMemoryDevice = 96 * kPointerMultiplier;
1107   static const int kMaxExecutableSizeMediumMemoryDevice =
1108       192 * kPointerMultiplier;
1109   static const int kMaxExecutableSizeHighMemoryDevice =
1110       256 * kPointerMultiplier;
1111   static const int kMaxExecutableSizeHugeMemoryDevice =
1112       256 * kPointerMultiplier;
1113
1114   intptr_t OldGenerationAllocationLimit(intptr_t old_gen_size,
1115                                         int freed_global_handles);
1116
1117   // Indicates whether inline bump-pointer allocation has been disabled.
1118   bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1119
1120   // Switch whether inline bump-pointer allocation should be used.
1121   void EnableInlineAllocation();
1122   void DisableInlineAllocation();
1123
1124   // Implements the corresponding V8 API function.
1125   bool IdleNotification(int hint);
1126
1127   // Declare all the root indices.  This defines the root list order.
1128   enum RootListIndex {
1129 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1130     STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1131 #undef ROOT_INDEX_DECLARATION
1132
1133 #define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
1134     INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
1135 #undef STRING_DECLARATION
1136
1137     // Utility type maps
1138 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1139     STRUCT_LIST(DECLARE_STRUCT_MAP)
1140 #undef DECLARE_STRUCT_MAP
1141
1142     kStringTableRootIndex,
1143
1144 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1145     SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
1146 #undef ROOT_INDEX_DECLARATION
1147
1148     kRootListLength,
1149     kStrongRootListLength = kStringTableRootIndex,
1150     kSmiRootsStart = kStringTableRootIndex + 1
1151   };
1152
1153   STATIC_ASSERT(kUndefinedValueRootIndex ==
1154                 Internals::kUndefinedValueRootIndex);
1155   STATIC_ASSERT(kNullValueRootIndex == Internals::kNullValueRootIndex);
1156   STATIC_ASSERT(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1157   STATIC_ASSERT(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1158   STATIC_ASSERT(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
1159
1160   // Generated code can embed direct references to non-writable roots if
1161   // they are in new space.
1162   static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
1163   // Generated code can treat direct references to this root as constant.
1164   bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1165
1166   Map* MapForFixedTypedArray(ExternalArrayType array_type);
1167   RootListIndex RootIndexForFixedTypedArray(
1168       ExternalArrayType array_type);
1169
1170   Map* MapForExternalArrayType(ExternalArrayType array_type);
1171   RootListIndex RootIndexForExternalArrayType(
1172       ExternalArrayType array_type);
1173
1174   RootListIndex RootIndexForEmptyExternalArray(ElementsKind kind);
1175   RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1176   ExternalArray* EmptyExternalArrayForMap(Map* map);
1177   FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1178
1179   void RecordStats(HeapStats* stats, bool take_snapshot = false);
1180
1181   // Copy block of memory from src to dst. Size of block should be aligned
1182   // by pointer size.
1183   static inline void CopyBlock(Address dst, Address src, int byte_size);
1184
1185   // Optimized version of memmove for blocks with pointer size aligned sizes and
1186   // pointer size aligned addresses.
1187   static inline void MoveBlock(Address dst, Address src, int byte_size);
1188
1189   // Check new space expansion criteria and expand semispaces if it was hit.
1190   void CheckNewSpaceExpansionCriteria();
1191
1192   inline void IncrementPromotedObjectsSize(int object_size) {
1193     ASSERT(object_size > 0);
1194     promoted_objects_size_ += object_size;
1195   }
1196
1197   inline void IncrementSemiSpaceCopiedObjectSize(int object_size) {
1198     ASSERT(object_size > 0);
1199     semi_space_copied_object_size_ += object_size;
1200   }
1201
1202   inline void IncrementYoungSurvivorsCounter(int survived) {
1203     ASSERT(survived >= 0);
1204     survived_since_last_expansion_ += survived;
1205   }
1206
1207   inline bool NextGCIsLikelyToBeFull() {
1208     if (FLAG_gc_global) return true;
1209
1210     if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1211
1212     intptr_t adjusted_allocation_limit =
1213         old_generation_allocation_limit_ - new_space_.Capacity();
1214
1215     if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
1216
1217     return false;
1218   }
1219
1220   void UpdateNewSpaceReferencesInExternalStringTable(
1221       ExternalStringTableUpdaterCallback updater_func);
1222
1223   void UpdateReferencesInExternalStringTable(
1224       ExternalStringTableUpdaterCallback updater_func);
1225
1226   void ProcessWeakReferences(WeakObjectRetainer* retainer);
1227
1228   void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1229
1230   // Helper function that governs the promotion policy from new space to
1231   // old.  If the object's old address lies below the new space's age
1232   // mark or if we've already filled the bottom 1/16th of the to space,
1233   // we try to promote this object.
1234   inline bool ShouldBePromoted(Address old_address, int object_size);
1235
1236   void ClearJSFunctionResultCaches();
1237
1238   void ClearNormalizedMapCaches();
1239
1240   GCTracer* tracer() { return tracer_; }
1241
1242   // Returns the size of objects residing in non new spaces.
1243   intptr_t PromotedSpaceSizeOfObjects();
1244
1245   double total_regexp_code_generated() { return total_regexp_code_generated_; }
1246   void IncreaseTotalRegexpCodeGenerated(int size) {
1247     total_regexp_code_generated_ += size;
1248   }
1249
1250   void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1251     if (is_crankshafted) {
1252       crankshaft_codegen_bytes_generated_ += size;
1253     } else {
1254       full_codegen_bytes_generated_ += size;
1255     }
1256   }
1257
1258   // Returns maximum GC pause.
1259   double get_max_gc_pause() { return max_gc_pause_; }
1260
1261   // Returns maximum size of objects alive after GC.
1262   intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1263
1264   // Returns minimal interval between two subsequent collections.
1265   double get_min_in_mutator() { return min_in_mutator_; }
1266
1267   // TODO(hpayer): remove, should be handled by GCTracer
1268   void AddMarkingTime(double marking_time) {
1269     marking_time_ += marking_time;
1270   }
1271
1272   double marking_time() const {
1273     return marking_time_;
1274   }
1275
1276   // TODO(hpayer): remove, should be handled by GCTracer
1277   void AddSweepingTime(double sweeping_time) {
1278     sweeping_time_ += sweeping_time;
1279   }
1280
1281   double sweeping_time() const {
1282     return sweeping_time_;
1283   }
1284
1285   MarkCompactCollector* mark_compact_collector() {
1286     return &mark_compact_collector_;
1287   }
1288
1289   StoreBuffer* store_buffer() {
1290     return &store_buffer_;
1291   }
1292
1293   Marking* marking() {
1294     return &marking_;
1295   }
1296
1297   IncrementalMarking* incremental_marking() {
1298     return &incremental_marking_;
1299   }
1300
1301   ExternalStringTable* external_string_table() {
1302     return &external_string_table_;
1303   }
1304
1305   // Returns the current sweep generation.
1306   int sweep_generation() {
1307     return sweep_generation_;
1308   }
1309
1310   inline Isolate* isolate();
1311
1312   void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1313   void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1314
1315   inline bool OldGenerationAllocationLimitReached();
1316
1317   inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1318     scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1319   }
1320
1321   void QueueMemoryChunkForFree(MemoryChunk* chunk);
1322   void FreeQueuedChunks();
1323
1324   int gc_count() const { return gc_count_; }
1325
1326   // Completely clear the Instanceof cache (to stop it keeping objects alive
1327   // around a GC).
1328   inline void CompletelyClearInstanceofCache();
1329
1330   // The roots that have an index less than this are always in old space.
1331   static const int kOldSpaceRoots = 0x20;
1332
1333   uint32_t HashSeed() {
1334     uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1335     ASSERT(FLAG_randomize_hashes || seed == 0);
1336     return seed;
1337   }
1338
1339   void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1340     ASSERT(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1341     set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1342   }
1343
1344   void SetConstructStubDeoptPCOffset(int pc_offset) {
1345     ASSERT(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1346     set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1347   }
1348
1349   void SetGetterStubDeoptPCOffset(int pc_offset) {
1350     ASSERT(getter_stub_deopt_pc_offset() == Smi::FromInt(0));
1351     set_getter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1352   }
1353
1354   void SetSetterStubDeoptPCOffset(int pc_offset) {
1355     ASSERT(setter_stub_deopt_pc_offset() == Smi::FromInt(0));
1356     set_setter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1357   }
1358
1359   // For post mortem debugging.
1360   void RememberUnmappedPage(Address page, bool compacted);
1361
1362   // Global inline caching age: it is incremented on some GCs after context
1363   // disposal. We use it to flush inline caches.
1364   int global_ic_age() {
1365     return global_ic_age_;
1366   }
1367
1368   void AgeInlineCaches() {
1369     global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
1370   }
1371
1372   bool flush_monomorphic_ics() { return flush_monomorphic_ics_; }
1373
1374   int64_t amount_of_external_allocated_memory() {
1375     return amount_of_external_allocated_memory_;
1376   }
1377
1378   void DeoptMarkedAllocationSites();
1379
1380   bool MaximumSizeScavenge() {
1381     return maximum_size_scavenges_ > 0;
1382   }
1383
1384   bool DeoptMaybeTenuredAllocationSites() {
1385     return new_space_.IsAtMaximumCapacity() && maximum_size_scavenges_ == 0;
1386   }
1387
1388   // ObjectStats are kept in two arrays, counts and sizes. Related stats are
1389   // stored in a contiguous linear buffer. Stats groups are stored one after
1390   // another.
1391   enum {
1392     FIRST_CODE_KIND_SUB_TYPE = LAST_TYPE + 1,
1393     FIRST_FIXED_ARRAY_SUB_TYPE =
1394         FIRST_CODE_KIND_SUB_TYPE + Code::NUMBER_OF_KINDS,
1395     FIRST_CODE_AGE_SUB_TYPE =
1396         FIRST_FIXED_ARRAY_SUB_TYPE + LAST_FIXED_ARRAY_SUB_TYPE + 1,
1397     OBJECT_STATS_COUNT = FIRST_CODE_AGE_SUB_TYPE + Code::kCodeAgeCount + 1
1398   };
1399
1400   void RecordObjectStats(InstanceType type, size_t size) {
1401     ASSERT(type <= LAST_TYPE);
1402     object_counts_[type]++;
1403     object_sizes_[type] += size;
1404   }
1405
1406   void RecordCodeSubTypeStats(int code_sub_type, int code_age, size_t size) {
1407     int code_sub_type_index = FIRST_CODE_KIND_SUB_TYPE + code_sub_type;
1408     int code_age_index =
1409         FIRST_CODE_AGE_SUB_TYPE + code_age - Code::kFirstCodeAge;
1410     ASSERT(code_sub_type_index >= FIRST_CODE_KIND_SUB_TYPE &&
1411            code_sub_type_index < FIRST_CODE_AGE_SUB_TYPE);
1412     ASSERT(code_age_index >= FIRST_CODE_AGE_SUB_TYPE &&
1413            code_age_index < OBJECT_STATS_COUNT);
1414     object_counts_[code_sub_type_index]++;
1415     object_sizes_[code_sub_type_index] += size;
1416     object_counts_[code_age_index]++;
1417     object_sizes_[code_age_index] += size;
1418   }
1419
1420   void RecordFixedArraySubTypeStats(int array_sub_type, size_t size) {
1421     ASSERT(array_sub_type <= LAST_FIXED_ARRAY_SUB_TYPE);
1422     object_counts_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type]++;
1423     object_sizes_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type] += size;
1424   }
1425
1426   void CheckpointObjectStats();
1427
1428   // We don't use a LockGuard here since we want to lock the heap
1429   // only when FLAG_concurrent_recompilation is true.
1430   class RelocationLock {
1431    public:
1432     explicit RelocationLock(Heap* heap) : heap_(heap) {
1433       heap_->relocation_mutex_.Lock();
1434     }
1435
1436
1437     ~RelocationLock() {
1438       heap_->relocation_mutex_.Unlock();
1439     }
1440
1441    private:
1442     Heap* heap_;
1443   };
1444
1445   void AddWeakObjectToCodeDependency(Handle<Object> obj,
1446                                      Handle<DependentCode> dep);
1447
1448   DependentCode* LookupWeakObjectToCodeDependency(Handle<Object> obj);
1449
1450   void InitializeWeakObjectToCodeTable() {
1451     set_weak_object_to_code_table(undefined_value());
1452   }
1453
1454   void EnsureWeakObjectToCodeTable();
1455
1456   static void FatalProcessOutOfMemory(const char* location,
1457                                       bool take_snapshot = false);
1458
1459  protected:
1460   // Methods made available to tests.
1461
1462   // Allocates a JS Map in the heap.
1463   MUST_USE_RESULT AllocationResult AllocateMap(
1464       InstanceType instance_type,
1465       int instance_size,
1466       ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
1467
1468   // Allocates and initializes a new JavaScript object based on a
1469   // constructor.
1470   // If allocation_site is non-null, then a memento is emitted after the object
1471   // that points to the site.
1472   MUST_USE_RESULT AllocationResult AllocateJSObject(
1473       JSFunction* constructor,
1474       PretenureFlag pretenure = NOT_TENURED,
1475       AllocationSite* allocation_site = NULL);
1476
1477   // Allocates and initializes a new JavaScript object based on a map.
1478   // Passing an allocation site means that a memento will be created that
1479   // points to the site.
1480   MUST_USE_RESULT AllocationResult AllocateJSObjectFromMap(
1481       Map* map,
1482       PretenureFlag pretenure = NOT_TENURED,
1483       bool alloc_props = true,
1484       AllocationSite* allocation_site = NULL);
1485
1486   // Allocated a HeapNumber from value.
1487   MUST_USE_RESULT AllocationResult AllocateHeapNumber(
1488       double value, PretenureFlag pretenure = NOT_TENURED);
1489
1490   // Allocated a Float32x4 from value.
1491   MUST_USE_RESULT AllocationResult AllocateFloat32x4(
1492       float32x4_value_t value,
1493       PretenureFlag pretenure = NOT_TENURED);
1494
1495   // Allocated a Float64x2 from value.
1496   MUST_USE_RESULT AllocationResult AllocateFloat64x2(
1497       float64x2_value_t value,
1498       PretenureFlag pretenure = NOT_TENURED);
1499
1500   // Allocated a Int32x4 from value.
1501   MUST_USE_RESULT AllocationResult AllocateInt32x4(
1502       int32x4_value_t value,
1503       PretenureFlag pretenure = NOT_TENURED);
1504
1505   // Allocate a byte array of the specified length
1506   MUST_USE_RESULT AllocationResult AllocateByteArray(
1507       int length,
1508       PretenureFlag pretenure = NOT_TENURED);
1509
1510   // Allocates an arguments object - optionally with an elements array.
1511   MUST_USE_RESULT AllocationResult AllocateArgumentsObject(
1512       Object* callee, int length);
1513
1514   // Copy the code and scope info part of the code object, but insert
1515   // the provided data as the relocation information.
1516   MUST_USE_RESULT AllocationResult CopyCode(Code* code,
1517                                             Vector<byte> reloc_info);
1518
1519   MUST_USE_RESULT AllocationResult CopyCode(Code* code);
1520
1521   // Allocates a fixed array initialized with undefined values
1522   MUST_USE_RESULT AllocationResult AllocateFixedArray(
1523       int length,
1524       PretenureFlag pretenure = NOT_TENURED);
1525
1526  private:
1527   Heap();
1528
1529   // The amount of external memory registered through the API kept alive
1530   // by global handles
1531   int64_t amount_of_external_allocated_memory_;
1532
1533   // Caches the amount of external memory registered at the last global gc.
1534   int64_t amount_of_external_allocated_memory_at_last_global_gc_;
1535
1536   // This can be calculated directly from a pointer to the heap; however, it is
1537   // more expedient to get at the isolate directly from within Heap methods.
1538   Isolate* isolate_;
1539
1540   Object* roots_[kRootListLength];
1541
1542   size_t code_range_size_;
1543   int reserved_semispace_size_;
1544   int max_semi_space_size_;
1545   int initial_semispace_size_;
1546   intptr_t max_old_generation_size_;
1547   intptr_t max_executable_size_;
1548   intptr_t maximum_committed_;
1549
1550   // For keeping track of how much data has survived
1551   // scavenge since last new space expansion.
1552   int survived_since_last_expansion_;
1553
1554   // For keeping track on when to flush RegExp code.
1555   int sweep_generation_;
1556
1557   int always_allocate_scope_depth_;
1558   int linear_allocation_scope_depth_;
1559
1560   // For keeping track of context disposals.
1561   int contexts_disposed_;
1562
1563   int global_ic_age_;
1564
1565   bool flush_monomorphic_ics_;
1566
1567   int scan_on_scavenge_pages_;
1568
1569   NewSpace new_space_;
1570   OldSpace* old_pointer_space_;
1571   OldSpace* old_data_space_;
1572   OldSpace* code_space_;
1573   MapSpace* map_space_;
1574   CellSpace* cell_space_;
1575   PropertyCellSpace* property_cell_space_;
1576   LargeObjectSpace* lo_space_;
1577   HeapState gc_state_;
1578   int gc_post_processing_depth_;
1579   Address new_space_top_after_last_gc_;
1580
1581   // Returns the amount of external memory registered since last global gc.
1582   int64_t PromotedExternalMemorySize();
1583
1584   unsigned int ms_count_;  // how many mark-sweep collections happened
1585   unsigned int gc_count_;  // how many gc happened
1586
1587   // For post mortem debugging.
1588   static const int kRememberedUnmappedPages = 128;
1589   int remembered_unmapped_pages_index_;
1590   Address remembered_unmapped_pages_[kRememberedUnmappedPages];
1591
1592   // Total length of the strings we failed to flatten since the last GC.
1593   int unflattened_strings_length_;
1594
1595 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
1596   inline void set_##name(type* value) {                                        \
1597     /* The deserializer makes use of the fact that these common roots are */   \
1598     /* never in new space and never on a page that is being compacted.    */   \
1599     ASSERT(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value));  \
1600     roots_[k##camel_name##RootIndex] = value;                                  \
1601   }
1602   ROOT_LIST(ROOT_ACCESSOR)
1603 #undef ROOT_ACCESSOR
1604
1605 #ifdef DEBUG
1606   // If the --gc-interval flag is set to a positive value, this
1607   // variable holds the value indicating the number of allocations
1608   // remain until the next failure and garbage collection.
1609   int allocation_timeout_;
1610 #endif  // DEBUG
1611
1612   // Limit that triggers a global GC on the next (normally caused) GC.  This
1613   // is checked when we have already decided to do a GC to help determine
1614   // which collector to invoke, before expanding a paged space in the old
1615   // generation and on every allocation in large object space.
1616   intptr_t old_generation_allocation_limit_;
1617
1618   // Indicates that an allocation has failed in the old generation since the
1619   // last GC.
1620   bool old_gen_exhausted_;
1621
1622   // Indicates that inline bump-pointer allocation has been globally disabled
1623   // for all spaces. This is used to disable allocations in generated code.
1624   bool inline_allocation_disabled_;
1625
1626   // Weak list heads, threaded through the objects.
1627   // List heads are initilized lazily and contain the undefined_value at start.
1628   Object* native_contexts_list_;
1629   Object* array_buffers_list_;
1630   Object* allocation_sites_list_;
1631
1632   // WeakHashTable that maps objects embedded in optimized code to dependent
1633   // code list. It is initilized lazily and contains the undefined_value at
1634   // start.
1635   Object* weak_object_to_code_table_;
1636
1637   // List of encountered weak collections (JSWeakMap and JSWeakSet) during
1638   // marking. It is initialized during marking, destroyed after marking and
1639   // contains Smi(0) while marking is not active.
1640   Object* encountered_weak_collections_;
1641
1642   StoreBufferRebuilder store_buffer_rebuilder_;
1643
1644   struct StringTypeTable {
1645     InstanceType type;
1646     int size;
1647     RootListIndex index;
1648   };
1649
1650   struct ConstantStringTable {
1651     const char* contents;
1652     RootListIndex index;
1653   };
1654
1655   struct StructTable {
1656     InstanceType type;
1657     int size;
1658     RootListIndex index;
1659   };
1660
1661   static const StringTypeTable string_type_table[];
1662   static const ConstantStringTable constant_string_table[];
1663   static const StructTable struct_table[];
1664
1665   // The special hidden string which is an empty string, but does not match
1666   // any string when looked up in properties.
1667   String* hidden_string_;
1668
1669   // GC callback function, called before and after mark-compact GC.
1670   // Allocations in the callback function are disallowed.
1671   struct GCPrologueCallbackPair {
1672     GCPrologueCallbackPair(v8::Isolate::GCPrologueCallback callback,
1673                            GCType gc_type,
1674                            bool pass_isolate)
1675         : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
1676     }
1677     bool operator==(const GCPrologueCallbackPair& pair) const {
1678       return pair.callback == callback;
1679     }
1680     v8::Isolate::GCPrologueCallback callback;
1681     GCType gc_type;
1682     // TODO(dcarney): remove variable
1683     bool pass_isolate_;
1684   };
1685   List<GCPrologueCallbackPair> gc_prologue_callbacks_;
1686
1687   struct GCEpilogueCallbackPair {
1688     GCEpilogueCallbackPair(v8::Isolate::GCPrologueCallback callback,
1689                            GCType gc_type,
1690                            bool pass_isolate)
1691         : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
1692     }
1693     bool operator==(const GCEpilogueCallbackPair& pair) const {
1694       return pair.callback == callback;
1695     }
1696     v8::Isolate::GCPrologueCallback callback;
1697     GCType gc_type;
1698     // TODO(dcarney): remove variable
1699     bool pass_isolate_;
1700   };
1701   List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
1702
1703   // Support for computing object sizes during GC.
1704   HeapObjectCallback gc_safe_size_of_old_object_;
1705   static int GcSafeSizeOfOldObject(HeapObject* object);
1706
1707   // Update the GC state. Called from the mark-compact collector.
1708   void MarkMapPointersAsEncoded(bool encoded) {
1709     ASSERT(!encoded);
1710     gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
1711   }
1712
1713   // Code that should be run before and after each GC.  Includes some
1714   // reporting/verification activities when compiled with DEBUG set.
1715   void GarbageCollectionPrologue();
1716   void GarbageCollectionEpilogue();
1717
1718   // Pretenuring decisions are made based on feedback collected during new
1719   // space evacuation. Note that between feedback collection and calling this
1720   // method object in old space must not move.
1721   // Right now we only process pretenuring feedback in high promotion mode.
1722   void ProcessPretenuringFeedback();
1723
1724   // Checks whether a global GC is necessary
1725   GarbageCollector SelectGarbageCollector(AllocationSpace space,
1726                                           const char** reason);
1727
1728   // Make sure there is a filler value behind the top of the new space
1729   // so that the GC does not confuse some unintialized/stale memory
1730   // with the allocation memento of the object at the top
1731   void EnsureFillerObjectAtTop();
1732
1733   // Ensure that we have swept all spaces in such a way that we can iterate
1734   // over all objects.  May cause a GC.
1735   void MakeHeapIterable();
1736
1737   // Performs garbage collection operation.
1738   // Returns whether there is a chance that another major GC could
1739   // collect more garbage.
1740   bool CollectGarbage(
1741       GarbageCollector collector,
1742       const char* gc_reason,
1743       const char* collector_reason,
1744       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1745
1746   // Performs garbage collection
1747   // Returns whether there is a chance another major GC could
1748   // collect more garbage.
1749   bool PerformGarbageCollection(
1750       GarbageCollector collector,
1751       GCTracer* tracer,
1752       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1753
1754   inline void UpdateOldSpaceLimits();
1755
1756   // Selects the proper allocation space depending on the given object
1757   // size, pretenuring decision, and preferred old-space.
1758   static AllocationSpace SelectSpace(int object_size,
1759                                      AllocationSpace preferred_old_space,
1760                                      PretenureFlag pretenure) {
1761     ASSERT(preferred_old_space == OLD_POINTER_SPACE ||
1762            preferred_old_space == OLD_DATA_SPACE);
1763     if (object_size > Page::kMaxRegularHeapObjectSize) return LO_SPACE;
1764     return (pretenure == TENURED) ? preferred_old_space : NEW_SPACE;
1765   }
1766
1767   // Allocate an uninitialized object.  The memory is non-executable if the
1768   // hardware and OS allow.  This is the single choke-point for allocations
1769   // performed by the runtime and should not be bypassed (to extend this to
1770   // inlined allocations, use the Heap::DisableInlineAllocation() support).
1771   MUST_USE_RESULT inline AllocationResult AllocateRaw(
1772       int size_in_bytes,
1773       AllocationSpace space,
1774       AllocationSpace retry_space);
1775
1776   // Allocates a heap object based on the map.
1777   MUST_USE_RESULT AllocationResult Allocate(
1778       Map* map,
1779       AllocationSpace space,
1780       AllocationSite* allocation_site = NULL);
1781
1782   // Allocates a partial map for bootstrapping.
1783   MUST_USE_RESULT AllocationResult AllocatePartialMap(
1784       InstanceType instance_type,
1785       int instance_size);
1786
1787   // Initializes a JSObject based on its map.
1788   void InitializeJSObjectFromMap(JSObject* obj,
1789                                  FixedArray* properties,
1790                                  Map* map);
1791   void InitializeAllocationMemento(AllocationMemento* memento,
1792                                    AllocationSite* allocation_site);
1793
1794   // Allocate a block of memory in the given space (filled with a filler).
1795   // Used as a fall-back for generated code when the space is full.
1796   MUST_USE_RESULT AllocationResult AllocateFillerObject(int size,
1797                                                     bool double_align,
1798                                                     AllocationSpace space);
1799
1800   // Allocate an uninitialized fixed array.
1801   MUST_USE_RESULT AllocationResult AllocateRawFixedArray(
1802       int length, PretenureFlag pretenure);
1803
1804   // Allocate an uninitialized fixed double array.
1805   MUST_USE_RESULT AllocationResult AllocateRawFixedDoubleArray(
1806       int length, PretenureFlag pretenure);
1807
1808   // Allocate an initialized fixed array with the given filler value.
1809   MUST_USE_RESULT AllocationResult AllocateFixedArrayWithFiller(
1810       int length, PretenureFlag pretenure, Object* filler);
1811
1812   // Allocate and partially initializes a String.  There are two String
1813   // encodings: ASCII and two byte.  These functions allocate a string of the
1814   // given length and set its map and length fields.  The characters of the
1815   // string are uninitialized.
1816   MUST_USE_RESULT AllocationResult AllocateRawOneByteString(
1817       int length, PretenureFlag pretenure);
1818   MUST_USE_RESULT AllocationResult AllocateRawTwoByteString(
1819       int length, PretenureFlag pretenure);
1820
1821   bool CreateInitialMaps();
1822   void CreateInitialObjects();
1823
1824   // Allocates an internalized string in old space based on the character
1825   // stream.
1826   MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringFromUtf8(
1827       Vector<const char> str,
1828       int chars,
1829       uint32_t hash_field);
1830
1831   MUST_USE_RESULT inline AllocationResult AllocateOneByteInternalizedString(
1832         Vector<const uint8_t> str,
1833         uint32_t hash_field);
1834
1835   MUST_USE_RESULT inline AllocationResult AllocateTwoByteInternalizedString(
1836         Vector<const uc16> str,
1837         uint32_t hash_field);
1838
1839   template<bool is_one_byte, typename T>
1840   MUST_USE_RESULT AllocationResult AllocateInternalizedStringImpl(
1841       T t, int chars, uint32_t hash_field);
1842
1843   template<typename T>
1844   MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringImpl(
1845       T t, int chars, uint32_t hash_field);
1846
1847   // Allocates an uninitialized fixed array. It must be filled by the caller.
1848   MUST_USE_RESULT AllocationResult AllocateUninitializedFixedArray(int length);
1849
1850   // Make a copy of src and return it. Returns
1851   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1852   MUST_USE_RESULT inline AllocationResult CopyFixedArray(FixedArray* src);
1853
1854   // Make a copy of src, set the map, and return the copy. Returns
1855   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1856   MUST_USE_RESULT AllocationResult CopyFixedArrayWithMap(FixedArray* src,
1857                                                          Map* map);
1858
1859   // Make a copy of src and return it. Returns
1860   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1861   MUST_USE_RESULT inline AllocationResult CopyFixedDoubleArray(
1862       FixedDoubleArray* src);
1863
1864   // Make a copy of src and return it. Returns
1865   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1866   MUST_USE_RESULT inline AllocationResult CopyConstantPoolArray(
1867       ConstantPoolArray* src);
1868
1869
1870   // Computes a single character string where the character has code.
1871   // A cache is used for ASCII codes.
1872   MUST_USE_RESULT AllocationResult LookupSingleCharacterStringFromCode(
1873       uint16_t code);
1874
1875   // Allocate a symbol in old space.
1876   MUST_USE_RESULT AllocationResult AllocateSymbol();
1877
1878   // Make a copy of src, set the map, and return the copy.
1879   MUST_USE_RESULT AllocationResult CopyConstantPoolArrayWithMap(
1880       ConstantPoolArray* src, Map* map);
1881
1882   MUST_USE_RESULT AllocationResult AllocateConstantPoolArray(
1883       const ConstantPoolArray::NumberOfEntries& small);
1884
1885   MUST_USE_RESULT AllocationResult AllocateExtendedConstantPoolArray(
1886       const ConstantPoolArray::NumberOfEntries& small,
1887       const ConstantPoolArray::NumberOfEntries& extended);
1888
1889   // Allocates an external array of the specified length and type.
1890   MUST_USE_RESULT AllocationResult AllocateExternalArray(
1891       int length,
1892       ExternalArrayType array_type,
1893       void* external_pointer,
1894       PretenureFlag pretenure);
1895
1896   // Allocates a fixed typed array of the specified length and type.
1897   MUST_USE_RESULT AllocationResult AllocateFixedTypedArray(
1898       int length,
1899       ExternalArrayType array_type,
1900       PretenureFlag pretenure);
1901
1902   // Make a copy of src and return it.
1903   MUST_USE_RESULT AllocationResult CopyAndTenureFixedCOWArray(FixedArray* src);
1904
1905   // Make a copy of src, set the map, and return the copy.
1906   MUST_USE_RESULT AllocationResult CopyFixedDoubleArrayWithMap(
1907       FixedDoubleArray* src, Map* map);
1908
1909   // Allocates a fixed double array with uninitialized values. Returns
1910   MUST_USE_RESULT AllocationResult AllocateUninitializedFixedDoubleArray(
1911       int length,
1912       PretenureFlag pretenure = NOT_TENURED);
1913
1914   // These five Create*EntryStub functions are here and forced to not be inlined
1915   // because of a gcc-4.4 bug that assigns wrong vtable entries.
1916   NO_INLINE(void CreateJSEntryStub());
1917   NO_INLINE(void CreateJSConstructEntryStub());
1918
1919   void CreateFixedStubs();
1920
1921   // Allocate empty fixed array.
1922   MUST_USE_RESULT AllocationResult AllocateEmptyFixedArray();
1923
1924   // Allocate empty external array of given type.
1925   MUST_USE_RESULT AllocationResult AllocateEmptyExternalArray(
1926       ExternalArrayType array_type);
1927
1928   // Allocate empty fixed typed array of given type.
1929   MUST_USE_RESULT AllocationResult AllocateEmptyFixedTypedArray(
1930       ExternalArrayType array_type);
1931
1932   // Allocate empty constant pool array.
1933   MUST_USE_RESULT AllocationResult AllocateEmptyConstantPoolArray();
1934
1935   // Allocate a tenured simple cell.
1936   MUST_USE_RESULT AllocationResult AllocateCell(Object* value);
1937
1938   // Allocate a tenured JS global property cell initialized with the hole.
1939   MUST_USE_RESULT AllocationResult AllocatePropertyCell();
1940
1941   // Allocates a new utility object in the old generation.
1942   MUST_USE_RESULT AllocationResult AllocateStruct(InstanceType type);
1943
1944   // Allocates a new foreign object.
1945   MUST_USE_RESULT AllocationResult AllocateForeign(
1946       Address address, PretenureFlag pretenure = NOT_TENURED);
1947
1948   MUST_USE_RESULT AllocationResult AllocateCode(int object_size,
1949                                                 bool immovable);
1950
1951   MUST_USE_RESULT AllocationResult InternalizeStringWithKey(HashTableKey* key);
1952
1953   MUST_USE_RESULT AllocationResult InternalizeString(String* str);
1954
1955   // Performs a minor collection in new generation.
1956   void Scavenge();
1957
1958   // Commits from space if it is uncommitted.
1959   void EnsureFromSpaceIsCommitted();
1960
1961   // Uncommit unused semi space.
1962   bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
1963
1964   // Fill in bogus values in from space
1965   void ZapFromSpace();
1966
1967   static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
1968       Heap* heap,
1969       Object** pointer);
1970
1971   Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
1972   static void ScavengeStoreBufferCallback(Heap* heap,
1973                                           MemoryChunk* page,
1974                                           StoreBufferEvent event);
1975
1976   // Performs a major collection in the whole heap.
1977   void MarkCompact(GCTracer* tracer);
1978
1979   // Code to be run before and after mark-compact.
1980   void MarkCompactPrologue();
1981
1982   void ProcessNativeContexts(WeakObjectRetainer* retainer);
1983   void ProcessArrayBuffers(WeakObjectRetainer* retainer);
1984   void ProcessAllocationSites(WeakObjectRetainer* retainer);
1985
1986   // Deopts all code that contains allocation instruction which are tenured or
1987   // not tenured. Moreover it clears the pretenuring allocation site statistics.
1988   void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
1989
1990   // Evaluates local pretenuring for the old space and calls
1991   // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
1992   // the old space.
1993   void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
1994
1995   // Called on heap tear-down.
1996   void TearDownArrayBuffers();
1997
1998   // Record statistics before and after garbage collection.
1999   void ReportStatisticsBeforeGC();
2000   void ReportStatisticsAfterGC();
2001
2002   // Slow part of scavenge object.
2003   static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
2004
2005   // Total RegExp code ever generated
2006   double total_regexp_code_generated_;
2007
2008   GCTracer* tracer_;
2009
2010   // Creates and installs the full-sized number string cache.
2011   int FullSizeNumberStringCacheLength();
2012   // Flush the number to string cache.
2013   void FlushNumberStringCache();
2014
2015   // Sets used allocation sites entries to undefined.
2016   void FlushAllocationSitesScratchpad();
2017
2018   // Initializes the allocation sites scratchpad with undefined values.
2019   void InitializeAllocationSitesScratchpad();
2020
2021   // Adds an allocation site to the scratchpad if there is space left.
2022   void AddAllocationSiteToScratchpad(AllocationSite* site,
2023                                      ScratchpadSlotMode mode);
2024
2025   void UpdateSurvivalStatistics(int start_new_space_size);
2026
2027   static const int kYoungSurvivalRateHighThreshold = 90;
2028   static const int kYoungSurvivalRateAllowedDeviation = 15;
2029
2030   static const int kOldSurvivalRateLowThreshold = 10;
2031
2032   int high_survival_rate_period_length_;
2033   intptr_t promoted_objects_size_;
2034   double promotion_rate_;
2035   intptr_t semi_space_copied_object_size_;
2036   double semi_space_copied_rate_;
2037
2038   // This is the pretenuring trigger for allocation sites that are in maybe
2039   // tenure state. When we switched to the maximum new space size we deoptimize
2040   // the code that belongs to the allocation site and derive the lifetime
2041   // of the allocation site.
2042   unsigned int maximum_size_scavenges_;
2043
2044   // TODO(hpayer): Allocation site pretenuring may make this method obsolete.
2045   // Re-visit incremental marking heuristics.
2046   bool IsHighSurvivalRate() {
2047     return high_survival_rate_period_length_ > 0;
2048   }
2049
2050   void SelectScavengingVisitorsTable();
2051
2052   void StartIdleRound() {
2053     mark_sweeps_since_idle_round_started_ = 0;
2054   }
2055
2056   void FinishIdleRound() {
2057     mark_sweeps_since_idle_round_started_ = kMaxMarkSweepsInIdleRound;
2058     scavenges_since_last_idle_round_ = 0;
2059   }
2060
2061   bool EnoughGarbageSinceLastIdleRound() {
2062     return (scavenges_since_last_idle_round_ >= kIdleScavengeThreshold);
2063   }
2064
2065   // Estimates how many milliseconds a Mark-Sweep would take to complete.
2066   // In idle notification handler we assume that this function will return:
2067   // - a number less than 10 for small heaps, which are less than 8Mb.
2068   // - a number greater than 10 for large heaps, which are greater than 32Mb.
2069   int TimeMarkSweepWouldTakeInMs() {
2070     // Rough estimate of how many megabytes of heap can be processed in 1 ms.
2071     static const int kMbPerMs = 2;
2072
2073     int heap_size_mb = static_cast<int>(SizeOfObjects() / MB);
2074     return heap_size_mb / kMbPerMs;
2075   }
2076
2077   // Returns true if no more GC work is left.
2078   bool IdleGlobalGC();
2079
2080   void AdvanceIdleIncrementalMarking(intptr_t step_size);
2081
2082   void ClearObjectStats(bool clear_last_time_stats = false);
2083
2084   void set_weak_object_to_code_table(Object* value) {
2085     ASSERT(!InNewSpace(value));
2086     weak_object_to_code_table_ = value;
2087   }
2088
2089   Object** weak_object_to_code_table_address() {
2090     return &weak_object_to_code_table_;
2091   }
2092
2093   static const int kInitialStringTableSize = 2048;
2094   static const int kInitialEvalCacheSize = 64;
2095   static const int kInitialNumberStringCacheSize = 256;
2096
2097   // Object counts and used memory by InstanceType
2098   size_t object_counts_[OBJECT_STATS_COUNT];
2099   size_t object_counts_last_time_[OBJECT_STATS_COUNT];
2100   size_t object_sizes_[OBJECT_STATS_COUNT];
2101   size_t object_sizes_last_time_[OBJECT_STATS_COUNT];
2102
2103   // Maximum GC pause.
2104   double max_gc_pause_;
2105
2106   // Total time spent in GC.
2107   double total_gc_time_ms_;
2108
2109   // Maximum size of objects alive after GC.
2110   intptr_t max_alive_after_gc_;
2111
2112   // Minimal interval between two subsequent collections.
2113   double min_in_mutator_;
2114
2115   // Size of objects alive after last GC.
2116   intptr_t alive_after_last_gc_;
2117
2118   double last_gc_end_timestamp_;
2119
2120   // Cumulative GC time spent in marking
2121   double marking_time_;
2122
2123   // Cumulative GC time spent in sweeping
2124   double sweeping_time_;
2125
2126   MarkCompactCollector mark_compact_collector_;
2127
2128   StoreBuffer store_buffer_;
2129
2130   Marking marking_;
2131
2132   IncrementalMarking incremental_marking_;
2133
2134   int number_idle_notifications_;
2135   unsigned int last_idle_notification_gc_count_;
2136   bool last_idle_notification_gc_count_init_;
2137
2138   int mark_sweeps_since_idle_round_started_;
2139   unsigned int gc_count_at_last_idle_gc_;
2140   int scavenges_since_last_idle_round_;
2141
2142   // These two counters are monotomically increasing and never reset.
2143   size_t full_codegen_bytes_generated_;
2144   size_t crankshaft_codegen_bytes_generated_;
2145
2146   // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2147   // this variable holds the number of garbage collections since the last
2148   // deoptimization triggered by garbage collection.
2149   int gcs_since_last_deopt_;
2150
2151 #ifdef VERIFY_HEAP
2152   int no_weak_object_verification_scope_depth_;
2153 #endif
2154
2155   static const int kAllocationSiteScratchpadSize = 256;
2156   int allocation_sites_scratchpad_length_;
2157
2158   static const int kMaxMarkSweepsInIdleRound = 7;
2159   static const int kIdleScavengeThreshold = 5;
2160
2161   // Shared state read by the scavenge collector and set by ScavengeObject.
2162   PromotionQueue promotion_queue_;
2163
2164   // Flag is set when the heap has been configured.  The heap can be repeatedly
2165   // configured through the API until it is set up.
2166   bool configured_;
2167
2168   ExternalStringTable external_string_table_;
2169
2170   VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2171
2172   MemoryChunk* chunks_queued_for_free_;
2173
2174   Mutex relocation_mutex_;
2175
2176   int gc_callbacks_depth_;
2177
2178   friend class AlwaysAllocateScope;
2179   friend class Factory;
2180   friend class GCCallbacksScope;
2181   friend class GCTracer;
2182   friend class HeapIterator;
2183   friend class Isolate;
2184   friend class MarkCompactCollector;
2185   friend class MarkCompactMarkingVisitor;
2186   friend class MapCompact;
2187 #ifdef VERIFY_HEAP
2188   friend class NoWeakObjectVerificationScope;
2189 #endif
2190   friend class Page;
2191
2192   DISALLOW_COPY_AND_ASSIGN(Heap);
2193 };
2194
2195
2196 class HeapStats {
2197  public:
2198   static const int kStartMarker = 0xDECADE00;
2199   static const int kEndMarker = 0xDECADE01;
2200
2201   int* start_marker;                    //  0
2202   int* new_space_size;                  //  1
2203   int* new_space_capacity;              //  2
2204   intptr_t* old_pointer_space_size;          //  3
2205   intptr_t* old_pointer_space_capacity;      //  4
2206   intptr_t* old_data_space_size;             //  5
2207   intptr_t* old_data_space_capacity;         //  6
2208   intptr_t* code_space_size;                 //  7
2209   intptr_t* code_space_capacity;             //  8
2210   intptr_t* map_space_size;                  //  9
2211   intptr_t* map_space_capacity;              // 10
2212   intptr_t* cell_space_size;                 // 11
2213   intptr_t* cell_space_capacity;             // 12
2214   intptr_t* lo_space_size;                   // 13
2215   int* global_handle_count;             // 14
2216   int* weak_global_handle_count;        // 15
2217   int* pending_global_handle_count;     // 16
2218   int* near_death_global_handle_count;  // 17
2219   int* free_global_handle_count;        // 18
2220   intptr_t* memory_allocator_size;           // 19
2221   intptr_t* memory_allocator_capacity;       // 20
2222   int* objects_per_type;                // 21
2223   int* size_per_type;                   // 22
2224   int* os_error;                        // 23
2225   int* end_marker;                      // 24
2226   intptr_t* property_cell_space_size;   // 25
2227   intptr_t* property_cell_space_capacity;    // 26
2228 };
2229
2230
2231 class AlwaysAllocateScope {
2232  public:
2233   explicit inline AlwaysAllocateScope(Isolate* isolate);
2234   inline ~AlwaysAllocateScope();
2235
2236  private:
2237   // Implicitly disable artificial allocation failures.
2238   Heap* heap_;
2239   DisallowAllocationFailure daf_;
2240 };
2241
2242
2243 #ifdef VERIFY_HEAP
2244 class NoWeakObjectVerificationScope {
2245  public:
2246   inline NoWeakObjectVerificationScope();
2247   inline ~NoWeakObjectVerificationScope();
2248 };
2249 #endif
2250
2251
2252 class GCCallbacksScope {
2253  public:
2254   explicit inline GCCallbacksScope(Heap* heap);
2255   inline ~GCCallbacksScope();
2256
2257   inline bool CheckReenter();
2258
2259  private:
2260   Heap* heap_;
2261 };
2262
2263
2264 // Visitor class to verify interior pointers in spaces that do not contain
2265 // or care about intergenerational references. All heap object pointers have to
2266 // point into the heap to a location that has a map pointer at its first word.
2267 // Caveat: Heap::Contains is an approximation because it can return true for
2268 // objects in a heap space but above the allocation pointer.
2269 class VerifyPointersVisitor: public ObjectVisitor {
2270  public:
2271   inline void VisitPointers(Object** start, Object** end);
2272 };
2273
2274
2275 // Verify that all objects are Smis.
2276 class VerifySmisVisitor: public ObjectVisitor {
2277  public:
2278   inline void VisitPointers(Object** start, Object** end);
2279 };
2280
2281
2282 // Space iterator for iterating over all spaces of the heap.  Returns each space
2283 // in turn, and null when it is done.
2284 class AllSpaces BASE_EMBEDDED {
2285  public:
2286   explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2287   Space* next();
2288  private:
2289   Heap* heap_;
2290   int counter_;
2291 };
2292
2293
2294 // Space iterator for iterating over all old spaces of the heap: Old pointer
2295 // space, old data space and code space.  Returns each space in turn, and null
2296 // when it is done.
2297 class OldSpaces BASE_EMBEDDED {
2298  public:
2299   explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2300   OldSpace* next();
2301  private:
2302   Heap* heap_;
2303   int counter_;
2304 };
2305
2306
2307 // Space iterator for iterating over all the paged spaces of the heap: Map
2308 // space, old pointer space, old data space, code space and cell space.  Returns
2309 // each space in turn, and null when it is done.
2310 class PagedSpaces BASE_EMBEDDED {
2311  public:
2312   explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2313   PagedSpace* next();
2314  private:
2315   Heap* heap_;
2316   int counter_;
2317 };
2318
2319
2320 // Space iterator for iterating over all spaces of the heap.
2321 // For each space an object iterator is provided. The deallocation of the
2322 // returned object iterators is handled by the space iterator.
2323 class SpaceIterator : public Malloced {
2324  public:
2325   explicit SpaceIterator(Heap* heap);
2326   SpaceIterator(Heap* heap, HeapObjectCallback size_func);
2327   virtual ~SpaceIterator();
2328
2329   bool has_next();
2330   ObjectIterator* next();
2331
2332  private:
2333   ObjectIterator* CreateIterator();
2334
2335   Heap* heap_;
2336   int current_space_;  // from enum AllocationSpace.
2337   ObjectIterator* iterator_;  // object iterator for the current space.
2338   HeapObjectCallback size_func_;
2339 };
2340
2341
2342 // A HeapIterator provides iteration over the whole heap. It
2343 // aggregates the specific iterators for the different spaces as
2344 // these can only iterate over one space only.
2345 //
2346 // HeapIterator ensures there is no allocation during its lifetime
2347 // (using an embedded DisallowHeapAllocation instance).
2348 //
2349 // HeapIterator can skip free list nodes (that is, de-allocated heap
2350 // objects that still remain in the heap). As implementation of free
2351 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2352 // phases. Also, it is forbidden to interrupt iteration in this mode,
2353 // as this will leave heap objects marked (and thus, unusable).
2354 class HeapObjectsFilter;
2355
2356 class HeapIterator BASE_EMBEDDED {
2357  public:
2358   enum HeapObjectsFiltering {
2359     kNoFiltering,
2360     kFilterUnreachable
2361   };
2362
2363   explicit HeapIterator(Heap* heap);
2364   HeapIterator(Heap* heap, HeapObjectsFiltering filtering);
2365   ~HeapIterator();
2366
2367   HeapObject* next();
2368   void reset();
2369
2370  private:
2371   struct MakeHeapIterableHelper {
2372     explicit MakeHeapIterableHelper(Heap* heap) { heap->MakeHeapIterable(); }
2373   };
2374
2375   // Perform the initialization.
2376   void Init();
2377   // Perform all necessary shutdown (destruction) work.
2378   void Shutdown();
2379   HeapObject* NextObject();
2380
2381   MakeHeapIterableHelper make_heap_iterable_helper_;
2382   DisallowHeapAllocation no_heap_allocation_;
2383   Heap* heap_;
2384   HeapObjectsFiltering filtering_;
2385   HeapObjectsFilter* filter_;
2386   // Space iterator for iterating all the spaces.
2387   SpaceIterator* space_iterator_;
2388   // Object iterator for the space currently being iterated.
2389   ObjectIterator* object_iterator_;
2390 };
2391
2392
2393 // Cache for mapping (map, property name) into field offset.
2394 // Cleared at startup and prior to mark sweep collection.
2395 class KeyedLookupCache {
2396  public:
2397   // Lookup field offset for (map, name). If absent, -1 is returned.
2398   int Lookup(Handle<Map> map, Handle<Name> name);
2399
2400   // Update an element in the cache.
2401   void Update(Handle<Map> map, Handle<Name> name, int field_offset);
2402
2403   // Clear the cache.
2404   void Clear();
2405
2406   static const int kLength = 256;
2407   static const int kCapacityMask = kLength - 1;
2408   static const int kMapHashShift = 5;
2409   static const int kHashMask = -4;  // Zero the last two bits.
2410   static const int kEntriesPerBucket = 4;
2411   static const int kEntryLength = 2;
2412   static const int kMapIndex = 0;
2413   static const int kKeyIndex = 1;
2414   static const int kNotFound = -1;
2415
2416   // kEntriesPerBucket should be a power of 2.
2417   STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2418   STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2419
2420  private:
2421   KeyedLookupCache() {
2422     for (int i = 0; i < kLength; ++i) {
2423       keys_[i].map = NULL;
2424       keys_[i].name = NULL;
2425       field_offsets_[i] = kNotFound;
2426     }
2427   }
2428
2429   static inline int Hash(Handle<Map> map, Handle<Name> name);
2430
2431   // Get the address of the keys and field_offsets arrays.  Used in
2432   // generated code to perform cache lookups.
2433   Address keys_address() {
2434     return reinterpret_cast<Address>(&keys_);
2435   }
2436
2437   Address field_offsets_address() {
2438     return reinterpret_cast<Address>(&field_offsets_);
2439   }
2440
2441   struct Key {
2442     Map* map;
2443     Name* name;
2444   };
2445
2446   Key keys_[kLength];
2447   int field_offsets_[kLength];
2448
2449   friend class ExternalReference;
2450   friend class Isolate;
2451   DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2452 };
2453
2454
2455 // Cache for mapping (map, property name) into descriptor index.
2456 // The cache contains both positive and negative results.
2457 // Descriptor index equals kNotFound means the property is absent.
2458 // Cleared at startup and prior to any gc.
2459 class DescriptorLookupCache {
2460  public:
2461   // Lookup descriptor index for (map, name).
2462   // If absent, kAbsent is returned.
2463   int Lookup(Map* source, Name* name) {
2464     if (!name->IsUniqueName()) return kAbsent;
2465     int index = Hash(source, name);
2466     Key& key = keys_[index];
2467     if ((key.source == source) && (key.name == name)) return results_[index];
2468     return kAbsent;
2469   }
2470
2471   // Update an element in the cache.
2472   void Update(Map* source, Name* name, int result) {
2473     ASSERT(result != kAbsent);
2474     if (name->IsUniqueName()) {
2475       int index = Hash(source, name);
2476       Key& key = keys_[index];
2477       key.source = source;
2478       key.name = name;
2479       results_[index] = result;
2480     }
2481   }
2482
2483   // Clear the cache.
2484   void Clear();
2485
2486   static const int kAbsent = -2;
2487
2488  private:
2489   DescriptorLookupCache() {
2490     for (int i = 0; i < kLength; ++i) {
2491       keys_[i].source = NULL;
2492       keys_[i].name = NULL;
2493       results_[i] = kAbsent;
2494     }
2495   }
2496
2497   static int Hash(Object* source, Name* name) {
2498     // Uses only lower 32 bits if pointers are larger.
2499     uint32_t source_hash =
2500         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(source))
2501             >> kPointerSizeLog2;
2502     uint32_t name_hash =
2503         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name))
2504             >> kPointerSizeLog2;
2505     return (source_hash ^ name_hash) % kLength;
2506   }
2507
2508   static const int kLength = 64;
2509   struct Key {
2510     Map* source;
2511     Name* name;
2512   };
2513
2514   Key keys_[kLength];
2515   int results_[kLength];
2516
2517   friend class Isolate;
2518   DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2519 };
2520
2521
2522 // GCTracer collects and prints ONE line after each garbage collector
2523 // invocation IFF --trace_gc is used.
2524
2525 class GCTracer BASE_EMBEDDED {
2526  public:
2527   class Scope BASE_EMBEDDED {
2528    public:
2529     enum ScopeId {
2530       EXTERNAL,
2531       MC_MARK,
2532       MC_SWEEP,
2533       MC_SWEEP_NEWSPACE,
2534       MC_SWEEP_OLDSPACE,
2535       MC_EVACUATE_PAGES,
2536       MC_UPDATE_NEW_TO_NEW_POINTERS,
2537       MC_UPDATE_ROOT_TO_NEW_POINTERS,
2538       MC_UPDATE_OLD_TO_NEW_POINTERS,
2539       MC_UPDATE_POINTERS_TO_EVACUATED,
2540       MC_UPDATE_POINTERS_BETWEEN_EVACUATED,
2541       MC_UPDATE_MISC_POINTERS,
2542       MC_WEAKCOLLECTION_PROCESS,
2543       MC_WEAKCOLLECTION_CLEAR,
2544       MC_FLUSH_CODE,
2545       kNumberOfScopes
2546     };
2547
2548     Scope(GCTracer* tracer, ScopeId scope)
2549         : tracer_(tracer),
2550         scope_(scope) {
2551       start_time_ = OS::TimeCurrentMillis();
2552     }
2553
2554     ~Scope() {
2555       ASSERT(scope_ < kNumberOfScopes);  // scope_ is unsigned.
2556       tracer_->scopes_[scope_] += OS::TimeCurrentMillis() - start_time_;
2557     }
2558
2559    private:
2560     GCTracer* tracer_;
2561     ScopeId scope_;
2562     double start_time_;
2563   };
2564
2565   explicit GCTracer(Heap* heap,
2566                     const char* gc_reason,
2567                     const char* collector_reason);
2568   ~GCTracer();
2569
2570   // Sets the collector.
2571   void set_collector(GarbageCollector collector) { collector_ = collector; }
2572
2573   // Sets the GC count.
2574   void set_gc_count(unsigned int count) { gc_count_ = count; }
2575
2576   // Sets the full GC count.
2577   void set_full_gc_count(int count) { full_gc_count_ = count; }
2578
2579   void increment_nodes_died_in_new_space() {
2580     nodes_died_in_new_space_++;
2581   }
2582
2583   void increment_nodes_copied_in_new_space() {
2584     nodes_copied_in_new_space_++;
2585   }
2586
2587   void increment_nodes_promoted() {
2588     nodes_promoted_++;
2589   }
2590
2591  private:
2592   // Returns a string matching the collector.
2593   const char* CollectorString();
2594
2595   // Returns size of object in heap (in MB).
2596   inline double SizeOfHeapObjects();
2597
2598   // Timestamp set in the constructor.
2599   double start_time_;
2600
2601   // Size of objects in heap set in constructor.
2602   intptr_t start_object_size_;
2603
2604   // Size of memory allocated from OS set in constructor.
2605   intptr_t start_memory_size_;
2606
2607   // Type of collector.
2608   GarbageCollector collector_;
2609
2610   // A count (including this one, e.g. the first collection is 1) of the
2611   // number of garbage collections.
2612   unsigned int gc_count_;
2613
2614   // A count (including this one) of the number of full garbage collections.
2615   int full_gc_count_;
2616
2617   // Amounts of time spent in different scopes during GC.
2618   double scopes_[Scope::kNumberOfScopes];
2619
2620   // Total amount of space either wasted or contained in one of free lists
2621   // before the current GC.
2622   intptr_t in_free_list_or_wasted_before_gc_;
2623
2624   // Difference between space used in the heap at the beginning of the current
2625   // collection and the end of the previous collection.
2626   intptr_t allocated_since_last_gc_;
2627
2628   // Amount of time spent in mutator that is time elapsed between end of the
2629   // previous collection and the beginning of the current one.
2630   double spent_in_mutator_;
2631
2632   // Number of died nodes in the new space.
2633   int nodes_died_in_new_space_;
2634
2635   // Number of copied nodes to the new space.
2636   int nodes_copied_in_new_space_;
2637
2638   // Number of promoted nodes to the old space.
2639   int nodes_promoted_;
2640
2641   // Incremental marking steps counters.
2642   int steps_count_;
2643   double steps_took_;
2644   double longest_step_;
2645   int steps_count_since_last_gc_;
2646   double steps_took_since_last_gc_;
2647
2648   Heap* heap_;
2649
2650   const char* gc_reason_;
2651   const char* collector_reason_;
2652 };
2653
2654
2655 class RegExpResultsCache {
2656  public:
2657   enum ResultsCacheType { REGEXP_MULTIPLE_INDICES, STRING_SPLIT_SUBSTRINGS };
2658
2659   // Attempt to retrieve a cached result.  On failure, 0 is returned as a Smi.
2660   // On success, the returned result is guaranteed to be a COW-array.
2661   static Object* Lookup(Heap* heap,
2662                         String* key_string,
2663                         Object* key_pattern,
2664                         ResultsCacheType type);
2665   // Attempt to add value_array to the cache specified by type.  On success,
2666   // value_array is turned into a COW-array.
2667   static void Enter(Isolate* isolate,
2668                     Handle<String> key_string,
2669                     Handle<Object> key_pattern,
2670                     Handle<FixedArray> value_array,
2671                     ResultsCacheType type);
2672   static void Clear(FixedArray* cache);
2673   static const int kRegExpResultsCacheSize = 0x100;
2674
2675  private:
2676   static const int kArrayEntriesPerCacheEntry = 4;
2677   static const int kStringOffset = 0;
2678   static const int kPatternOffset = 1;
2679   static const int kArrayOffset = 2;
2680 };
2681
2682
2683 // Abstract base class for checking whether a weak object should be retained.
2684 class WeakObjectRetainer {
2685  public:
2686   virtual ~WeakObjectRetainer() {}
2687
2688   // Return whether this object should be retained. If NULL is returned the
2689   // object has no references. Otherwise the address of the retained object
2690   // should be returned as in some GC situations the object has been moved.
2691   virtual Object* RetainAs(Object* object) = 0;
2692 };
2693
2694
2695 // Intrusive object marking uses least significant bit of
2696 // heap object's map word to mark objects.
2697 // Normally all map words have least significant bit set
2698 // because they contain tagged map pointer.
2699 // If the bit is not set object is marked.
2700 // All objects should be unmarked before resuming
2701 // JavaScript execution.
2702 class IntrusiveMarking {
2703  public:
2704   static bool IsMarked(HeapObject* object) {
2705     return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
2706   }
2707
2708   static void ClearMark(HeapObject* object) {
2709     uintptr_t map_word = object->map_word().ToRawValue();
2710     object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
2711     ASSERT(!IsMarked(object));
2712   }
2713
2714   static void SetMark(HeapObject* object) {
2715     uintptr_t map_word = object->map_word().ToRawValue();
2716     object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
2717     ASSERT(IsMarked(object));
2718   }
2719
2720   static Map* MapOfMarkedObject(HeapObject* object) {
2721     uintptr_t map_word = object->map_word().ToRawValue();
2722     return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
2723   }
2724
2725   static int SizeOfMarkedObject(HeapObject* object) {
2726     return object->SizeFromMap(MapOfMarkedObject(object));
2727   }
2728
2729  private:
2730   static const uintptr_t kNotMarkedBit = 0x1;
2731   STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0);  // NOLINT
2732 };
2733
2734
2735 #ifdef DEBUG
2736 // Helper class for tracing paths to a search target Object from all roots.
2737 // The TracePathFrom() method can be used to trace paths from a specific
2738 // object to the search target object.
2739 class PathTracer : public ObjectVisitor {
2740  public:
2741   enum WhatToFind {
2742     FIND_ALL,   // Will find all matches.
2743     FIND_FIRST  // Will stop the search after first match.
2744   };
2745
2746   // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2747   static const int kMarkTag = 2;
2748
2749   // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2750   // after the first match.  If FIND_ALL is specified, then tracing will be
2751   // done for all matches.
2752   PathTracer(Object* search_target,
2753              WhatToFind what_to_find,
2754              VisitMode visit_mode)
2755       : search_target_(search_target),
2756         found_target_(false),
2757         found_target_in_trace_(false),
2758         what_to_find_(what_to_find),
2759         visit_mode_(visit_mode),
2760         object_stack_(20),
2761         no_allocation() {}
2762
2763   virtual void VisitPointers(Object** start, Object** end);
2764
2765   void Reset();
2766   void TracePathFrom(Object** root);
2767
2768   bool found() const { return found_target_; }
2769
2770   static Object* const kAnyGlobalObject;
2771
2772  protected:
2773   class MarkVisitor;
2774   class UnmarkVisitor;
2775
2776   void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2777   void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2778   virtual void ProcessResults();
2779
2780   Object* search_target_;
2781   bool found_target_;
2782   bool found_target_in_trace_;
2783   WhatToFind what_to_find_;
2784   VisitMode visit_mode_;
2785   List<Object*> object_stack_;
2786
2787   DisallowHeapAllocation no_allocation;  // i.e. no gc allowed.
2788
2789  private:
2790   DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2791 };
2792 #endif  // DEBUG
2793
2794 } }  // namespace v8::internal
2795
2796 #endif  // V8_HEAP_H_