[V8] Introduce a QML compilation mode
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / heap.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #ifndef V8_HEAP_H_
29 #define V8_HEAP_H_
30
31 #include <math.h>
32
33 #include "allocation.h"
34 #include "globals.h"
35 #include "incremental-marking.h"
36 #include "list.h"
37 #include "mark-compact.h"
38 #include "objects-visiting.h"
39 #include "spaces.h"
40 #include "splay-tree-inl.h"
41 #include "store-buffer.h"
42 #include "v8-counters.h"
43 #include "v8globals.h"
44
45 namespace v8 {
46 namespace internal {
47
48 // Defines all the roots in Heap.
49 #define STRONG_ROOT_LIST(V)                                                    \
50   V(Map, byte_array_map, ByteArrayMap)                                         \
51   V(Map, free_space_map, FreeSpaceMap)                                         \
52   V(Map, one_pointer_filler_map, OnePointerFillerMap)                          \
53   V(Map, two_pointer_filler_map, TwoPointerFillerMap)                          \
54   /* Cluster the most popular ones in a few cache lines here at the top.    */ \
55   V(Smi, store_buffer_top, StoreBufferTop)                                     \
56   V(Oddball, undefined_value, UndefinedValue)                                  \
57   V(Oddball, the_hole_value, TheHoleValue)                                     \
58   V(Oddball, null_value, NullValue)                                            \
59   V(Oddball, true_value, TrueValue)                                            \
60   V(Oddball, false_value, FalseValue)                                          \
61   V(Map, global_property_cell_map, GlobalPropertyCellMap)                      \
62   V(Map, shared_function_info_map, SharedFunctionInfoMap)                      \
63   V(Map, meta_map, MetaMap)                                                    \
64   V(Map, ascii_symbol_map, AsciiSymbolMap)                                     \
65   V(Map, ascii_string_map, AsciiStringMap)                                     \
66   V(Map, heap_number_map, HeapNumberMap)                                       \
67   V(Map, global_context_map, GlobalContextMap)                                 \
68   V(Map, fixed_array_map, FixedArrayMap)                                       \
69   V(Map, code_map, CodeMap)                                                    \
70   V(Map, scope_info_map, ScopeInfoMap)                                         \
71   V(Map, fixed_cow_array_map, FixedCOWArrayMap)                                \
72   V(Map, fixed_double_array_map, FixedDoubleArrayMap)                          \
73   V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel)       \
74   V(Map, hash_table_map, HashTableMap)                                         \
75   V(FixedArray, empty_fixed_array, EmptyFixedArray)                            \
76   V(ByteArray, empty_byte_array, EmptyByteArray)                               \
77   V(String, empty_string, EmptyString)                                         \
78   V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray)             \
79   V(Smi, stack_limit, StackLimit)                                              \
80   V(Oddball, arguments_marker, ArgumentsMarker)                                \
81   /* The first 32 roots above this line should be boring from a GC point of */ \
82   /* view.  This means they are never in new space and never on a page that */ \
83   /* is being compacted.                                                    */ \
84   V(FixedArray, number_string_cache, NumberStringCache)                        \
85   V(Object, instanceof_cache_function, InstanceofCacheFunction)                \
86   V(Object, instanceof_cache_map, InstanceofCacheMap)                          \
87   V(Object, instanceof_cache_answer, InstanceofCacheAnswer)                    \
88   V(FixedArray, single_character_string_cache, SingleCharacterStringCache)     \
89   V(FixedArray, string_split_cache, StringSplitCache)                          \
90   V(Object, termination_exception, TerminationException)                       \
91   V(Smi, hash_seed, HashSeed)                                                  \
92   V(Map, string_map, StringMap)                                                \
93   V(Map, symbol_map, SymbolMap)                                                \
94   V(Map, cons_string_map, ConsStringMap)                                       \
95   V(Map, cons_ascii_string_map, ConsAsciiStringMap)                            \
96   V(Map, sliced_string_map, SlicedStringMap)                                   \
97   V(Map, sliced_ascii_string_map, SlicedAsciiStringMap)                        \
98   V(Map, cons_symbol_map, ConsSymbolMap)                                       \
99   V(Map, cons_ascii_symbol_map, ConsAsciiSymbolMap)                            \
100   V(Map, external_symbol_map, ExternalSymbolMap)                               \
101   V(Map, external_symbol_with_ascii_data_map, ExternalSymbolWithAsciiDataMap)  \
102   V(Map, external_ascii_symbol_map, ExternalAsciiSymbolMap)                    \
103   V(Map, external_string_map, ExternalStringMap)                               \
104   V(Map, external_string_with_ascii_data_map, ExternalStringWithAsciiDataMap)  \
105   V(Map, external_ascii_string_map, ExternalAsciiStringMap)                    \
106   V(Map, short_external_symbol_map, ShortExternalSymbolMap)                    \
107   V(Map,                                                                       \
108     short_external_symbol_with_ascii_data_map,                                 \
109     ShortExternalSymbolWithAsciiDataMap)                                       \
110   V(Map, short_external_ascii_symbol_map, ShortExternalAsciiSymbolMap)         \
111   V(Map, short_external_string_map, ShortExternalStringMap)                    \
112   V(Map,                                                                       \
113     short_external_string_with_ascii_data_map,                                 \
114     ShortExternalStringWithAsciiDataMap)                                       \
115   V(Map, short_external_ascii_string_map, ShortExternalAsciiStringMap)         \
116   V(Map, undetectable_string_map, UndetectableStringMap)                       \
117   V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap)            \
118   V(Map, external_pixel_array_map, ExternalPixelArrayMap)                      \
119   V(Map, external_byte_array_map, ExternalByteArrayMap)                        \
120   V(Map, external_unsigned_byte_array_map, ExternalUnsignedByteArrayMap)       \
121   V(Map, external_short_array_map, ExternalShortArrayMap)                      \
122   V(Map, external_unsigned_short_array_map, ExternalUnsignedShortArrayMap)     \
123   V(Map, external_int_array_map, ExternalIntArrayMap)                          \
124   V(Map, external_unsigned_int_array_map, ExternalUnsignedIntArrayMap)         \
125   V(Map, external_float_array_map, ExternalFloatArrayMap)                      \
126   V(Map, external_double_array_map, ExternalDoubleArrayMap)                    \
127   V(Map, non_strict_arguments_elements_map, NonStrictArgumentsElementsMap)     \
128   V(Map, function_context_map, FunctionContextMap)                             \
129   V(Map, catch_context_map, CatchContextMap)                                   \
130   V(Map, with_context_map, WithContextMap)                                     \
131   V(Map, block_context_map, BlockContextMap)                                   \
132   V(Map, module_context_map, ModuleContextMap)                                 \
133   V(Map, oddball_map, OddballMap)                                              \
134   V(Map, message_object_map, JSMessageObjectMap)                               \
135   V(Map, foreign_map, ForeignMap)                                              \
136   V(HeapNumber, nan_value, NanValue)                                           \
137   V(HeapNumber, infinity_value, InfinityValue)                                 \
138   V(HeapNumber, minus_zero_value, MinusZeroValue)                              \
139   V(Map, neander_map, NeanderMap)                                              \
140   V(JSObject, message_listeners, MessageListeners)                             \
141   V(Foreign, prototype_accessors, PrototypeAccessors)                          \
142   V(UnseededNumberDictionary, code_stubs, CodeStubs)                           \
143   V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache)      \
144   V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache)        \
145   V(Code, js_entry_code, JsEntryCode)                                          \
146   V(Code, js_construct_entry_code, JsConstructEntryCode)                       \
147   V(FixedArray, natives_source_cache, NativesSourceCache)                      \
148   V(Object, last_script_id, LastScriptId)                                      \
149   V(Script, empty_script, EmptyScript)                                         \
150   V(Smi, real_stack_limit, RealStackLimit)                                     \
151   V(StringDictionary, intrinsic_function_names, IntrinsicFunctionNames)        \
152   V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset)     \
153   V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset)
154
155 #define ROOT_LIST(V)                                  \
156   STRONG_ROOT_LIST(V)                                 \
157   V(SymbolTable, symbol_table, SymbolTable)
158
159 #define SYMBOL_LIST(V)                                                   \
160   V(Array_symbol, "Array")                                               \
161   V(Object_symbol, "Object")                                             \
162   V(Proto_symbol, "__proto__")                                           \
163   V(StringImpl_symbol, "StringImpl")                                     \
164   V(arguments_symbol, "arguments")                                       \
165   V(Arguments_symbol, "Arguments")                                       \
166   V(call_symbol, "call")                                                 \
167   V(apply_symbol, "apply")                                               \
168   V(caller_symbol, "caller")                                             \
169   V(boolean_symbol, "boolean")                                           \
170   V(Boolean_symbol, "Boolean")                                           \
171   V(callee_symbol, "callee")                                             \
172   V(constructor_symbol, "constructor")                                   \
173   V(code_symbol, ".code")                                                \
174   V(result_symbol, ".result")                                            \
175   V(catch_var_symbol, ".catch-var")                                      \
176   V(empty_symbol, "")                                                    \
177   V(eval_symbol, "eval")                                                 \
178   V(function_symbol, "function")                                         \
179   V(length_symbol, "length")                                             \
180   V(module_symbol, "module")                                             \
181   V(name_symbol, "name")                                                 \
182   V(native_symbol, "native")                                             \
183   V(null_symbol, "null")                                                 \
184   V(number_symbol, "number")                                             \
185   V(Number_symbol, "Number")                                             \
186   V(nan_symbol, "NaN")                                                   \
187   V(RegExp_symbol, "RegExp")                                             \
188   V(source_symbol, "source")                                             \
189   V(global_symbol, "global")                                             \
190   V(ignore_case_symbol, "ignoreCase")                                    \
191   V(multiline_symbol, "multiline")                                       \
192   V(input_symbol, "input")                                               \
193   V(index_symbol, "index")                                               \
194   V(last_index_symbol, "lastIndex")                                      \
195   V(object_symbol, "object")                                             \
196   V(prototype_symbol, "prototype")                                       \
197   V(string_symbol, "string")                                             \
198   V(String_symbol, "String")                                             \
199   V(Date_symbol, "Date")                                                 \
200   V(this_symbol, "this")                                                 \
201   V(to_string_symbol, "toString")                                        \
202   V(char_at_symbol, "CharAt")                                            \
203   V(undefined_symbol, "undefined")                                       \
204   V(value_of_symbol, "valueOf")                                          \
205   V(InitializeVarGlobal_symbol, "InitializeVarGlobal")                   \
206   V(InitializeConstGlobal_symbol, "InitializeConstGlobal")               \
207   V(KeyedLoadElementMonomorphic_symbol,                                  \
208     "KeyedLoadElementMonomorphic")                                       \
209   V(KeyedStoreElementMonomorphic_symbol,                                 \
210     "KeyedStoreElementMonomorphic")                                      \
211   V(KeyedStoreAndGrowElementMonomorphic_symbol,                          \
212     "KeyedStoreAndGrowElementMonomorphic")                               \
213   V(stack_overflow_symbol, "kStackOverflowBoilerplate")                  \
214   V(illegal_access_symbol, "illegal access")                             \
215   V(out_of_memory_symbol, "out-of-memory")                               \
216   V(illegal_execution_state_symbol, "illegal execution state")           \
217   V(get_symbol, "get")                                                   \
218   V(set_symbol, "set")                                                   \
219   V(function_class_symbol, "Function")                                   \
220   V(illegal_argument_symbol, "illegal argument")                         \
221   V(MakeReferenceError_symbol, "MakeReferenceError")                     \
222   V(MakeSyntaxError_symbol, "MakeSyntaxError")                           \
223   V(MakeTypeError_symbol, "MakeTypeError")                               \
224   V(invalid_lhs_in_assignment_symbol, "invalid_lhs_in_assignment")       \
225   V(invalid_lhs_in_for_in_symbol, "invalid_lhs_in_for_in")               \
226   V(invalid_lhs_in_postfix_op_symbol, "invalid_lhs_in_postfix_op")       \
227   V(invalid_lhs_in_prefix_op_symbol, "invalid_lhs_in_prefix_op")         \
228   V(illegal_return_symbol, "illegal_return")                             \
229   V(illegal_break_symbol, "illegal_break")                               \
230   V(illegal_continue_symbol, "illegal_continue")                         \
231   V(unknown_label_symbol, "unknown_label")                               \
232   V(redeclaration_symbol, "redeclaration")                               \
233   V(failure_symbol, "<failure>")                                         \
234   V(space_symbol, " ")                                                   \
235   V(exec_symbol, "exec")                                                 \
236   V(zero_symbol, "0")                                                    \
237   V(global_eval_symbol, "GlobalEval")                                    \
238   V(identity_hash_symbol, "v8::IdentityHash")                            \
239   V(closure_symbol, "(closure)")                                         \
240   V(use_strict, "use strict")                                            \
241   V(dot_symbol, ".")                                                     \
242   V(anonymous_function_symbol, "(anonymous function)")                   \
243   V(compare_ic_symbol, ".compare_ic")                                    \
244   V(infinity_symbol, "Infinity")                                         \
245   V(minus_infinity_symbol, "-Infinity")                                  \
246   V(hidden_stack_trace_symbol, "v8::hidden_stack_trace")                 \
247   V(query_colon_symbol, "(?:)")
248
249 // Forward declarations.
250 class GCTracer;
251 class HeapStats;
252 class Isolate;
253 class WeakObjectRetainer;
254
255
256 typedef HeapObject* (*ExternalStringTableUpdaterCallback)(Heap* heap,
257                                                           Object** pointer);
258
259 class StoreBufferRebuilder {
260  public:
261   explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
262       : store_buffer_(store_buffer) {
263   }
264
265   void Callback(MemoryChunk* page, StoreBufferEvent event);
266
267  private:
268   StoreBuffer* store_buffer_;
269
270   // We record in this variable how full the store buffer was when we started
271   // iterating over the current page, finding pointers to new space.  If the
272   // store buffer overflows again we can exempt the page from the store buffer
273   // by rewinding to this point instead of having to search the store buffer.
274   Object*** start_of_current_page_;
275   // The current page we are scanning in the store buffer iterator.
276   MemoryChunk* current_page_;
277 };
278
279
280
281 // The all static Heap captures the interface to the global object heap.
282 // All JavaScript contexts by this process share the same object heap.
283
284 #ifdef DEBUG
285 class HeapDebugUtils;
286 #endif
287
288
289 // A queue of objects promoted during scavenge. Each object is accompanied
290 // by it's size to avoid dereferencing a map pointer for scanning.
291 class PromotionQueue {
292  public:
293   explicit PromotionQueue(Heap* heap)
294       : front_(NULL),
295         rear_(NULL),
296         limit_(NULL),
297         emergency_stack_(0),
298         heap_(heap) { }
299
300   void Initialize();
301
302   void Destroy() {
303     ASSERT(is_empty());
304     delete emergency_stack_;
305     emergency_stack_ = NULL;
306   }
307
308   inline void ActivateGuardIfOnTheSamePage();
309
310   Page* GetHeadPage() {
311     return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
312   }
313
314   void SetNewLimit(Address limit) {
315     if (!guard_) {
316       return;
317     }
318
319     ASSERT(GetHeadPage() == Page::FromAllocationTop(limit));
320     limit_ = reinterpret_cast<intptr_t*>(limit);
321
322     if (limit_ <= rear_) {
323       return;
324     }
325
326     RelocateQueueHead();
327   }
328
329   bool is_empty() {
330     return (front_ == rear_) &&
331         (emergency_stack_ == NULL || emergency_stack_->length() == 0);
332   }
333
334   inline void insert(HeapObject* target, int size);
335
336   void remove(HeapObject** target, int* size) {
337     ASSERT(!is_empty());
338     if (front_ == rear_) {
339       Entry e = emergency_stack_->RemoveLast();
340       *target = e.obj_;
341       *size = e.size_;
342       return;
343     }
344
345     if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(front_))) {
346       NewSpacePage* front_page =
347           NewSpacePage::FromAddress(reinterpret_cast<Address>(front_));
348       ASSERT(!front_page->prev_page()->is_anchor());
349       front_ =
350           reinterpret_cast<intptr_t*>(front_page->prev_page()->area_end());
351     }
352     *target = reinterpret_cast<HeapObject*>(*(--front_));
353     *size = static_cast<int>(*(--front_));
354     // Assert no underflow.
355     SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
356                                 reinterpret_cast<Address>(front_));
357   }
358
359  private:
360   // The front of the queue is higher in the memory page chain than the rear.
361   intptr_t* front_;
362   intptr_t* rear_;
363   intptr_t* limit_;
364
365   bool guard_;
366
367   static const int kEntrySizeInWords = 2;
368
369   struct Entry {
370     Entry(HeapObject* obj, int size) : obj_(obj), size_(size) { }
371
372     HeapObject* obj_;
373     int size_;
374   };
375   List<Entry>* emergency_stack_;
376
377   Heap* heap_;
378
379   void RelocateQueueHead();
380
381   DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
382 };
383
384
385 typedef void (*ScavengingCallback)(Map* map,
386                                    HeapObject** slot,
387                                    HeapObject* object);
388
389
390 // External strings table is a place where all external strings are
391 // registered.  We need to keep track of such strings to properly
392 // finalize them.
393 // The ExternalStringTable can contain both strings and objects with
394 // external resources.  It was not renamed to make the patch simpler.
395 class ExternalStringTable {
396  public:
397   // Registers an external string.
398   inline void AddString(String* string);
399   // Registers an external object.
400   inline void AddObject(HeapObject* string);
401
402   inline void Iterate(ObjectVisitor* v);
403
404   // Restores internal invariant and gets rid of collected strings.
405   // Must be called after each Iterate() that modified the strings.
406   void CleanUp();
407
408   // Destroys all allocated memory.
409   void TearDown();
410
411  private:
412   ExternalStringTable() { }
413
414   friend class Heap;
415
416   inline void Verify();
417
418   inline void AddOldObject(HeapObject* string);
419
420   // Notifies the table that only a prefix of the new list is valid.
421   inline void ShrinkNewObjects(int position);
422
423   // To speed up scavenge collections new space string are kept
424   // separate from old space strings.
425   List<Object*> new_space_strings_;
426   List<Object*> old_space_strings_;
427
428   Heap* heap_;
429
430   DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
431 };
432
433
434 enum ArrayStorageAllocationMode {
435   DONT_INITIALIZE_ARRAY_ELEMENTS,
436   INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
437 };
438
439 class Heap {
440  public:
441   // Configure heap size before setup. Return false if the heap has been
442   // set up already.
443   bool ConfigureHeap(int max_semispace_size,
444                      intptr_t max_old_gen_size,
445                      intptr_t max_executable_size);
446   bool ConfigureHeapDefault();
447
448   // Initializes the global object heap. If create_heap_objects is true,
449   // also creates the basic non-mutable objects.
450   // Returns whether it succeeded.
451   bool SetUp(bool create_heap_objects);
452
453   // Destroys all memory allocated by the heap.
454   void TearDown();
455
456   // Set the stack limit in the roots_ array.  Some architectures generate
457   // code that looks here, because it is faster than loading from the static
458   // jslimit_/real_jslimit_ variable in the StackGuard.
459   void SetStackLimits();
460
461   // Returns whether SetUp has been called.
462   bool HasBeenSetUp();
463
464   // Returns the maximum amount of memory reserved for the heap.  For
465   // the young generation, we reserve 4 times the amount needed for a
466   // semi space.  The young generation consists of two semi spaces and
467   // we reserve twice the amount needed for those in order to ensure
468   // that new space can be aligned to its size.
469   intptr_t MaxReserved() {
470     return 4 * reserved_semispace_size_ + max_old_generation_size_;
471   }
472   int MaxSemiSpaceSize() { return max_semispace_size_; }
473   int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
474   int InitialSemiSpaceSize() { return initial_semispace_size_; }
475   intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
476   intptr_t MaxExecutableSize() { return max_executable_size_; }
477
478   // Returns the capacity of the heap in bytes w/o growing. Heap grows when
479   // more spaces are needed until it reaches the limit.
480   intptr_t Capacity();
481
482   // Returns the amount of memory currently committed for the heap.
483   intptr_t CommittedMemory();
484
485   // Returns the amount of executable memory currently committed for the heap.
486   intptr_t CommittedMemoryExecutable();
487
488   // Returns the available bytes in space w/o growing.
489   // Heap doesn't guarantee that it can allocate an object that requires
490   // all available bytes. Check MaxHeapObjectSize() instead.
491   intptr_t Available();
492
493   // Returns of size of all objects residing in the heap.
494   intptr_t SizeOfObjects();
495
496   // Return the starting address and a mask for the new space.  And-masking an
497   // address with the mask will result in the start address of the new space
498   // for all addresses in either semispace.
499   Address NewSpaceStart() { return new_space_.start(); }
500   uintptr_t NewSpaceMask() { return new_space_.mask(); }
501   Address NewSpaceTop() { return new_space_.top(); }
502
503   NewSpace* new_space() { return &new_space_; }
504   OldSpace* old_pointer_space() { return old_pointer_space_; }
505   OldSpace* old_data_space() { return old_data_space_; }
506   OldSpace* code_space() { return code_space_; }
507   MapSpace* map_space() { return map_space_; }
508   CellSpace* cell_space() { return cell_space_; }
509   LargeObjectSpace* lo_space() { return lo_space_; }
510
511   bool always_allocate() { return always_allocate_scope_depth_ != 0; }
512   Address always_allocate_scope_depth_address() {
513     return reinterpret_cast<Address>(&always_allocate_scope_depth_);
514   }
515   bool linear_allocation() {
516     return linear_allocation_scope_depth_ != 0;
517   }
518
519   Address* NewSpaceAllocationTopAddress() {
520     return new_space_.allocation_top_address();
521   }
522   Address* NewSpaceAllocationLimitAddress() {
523     return new_space_.allocation_limit_address();
524   }
525
526   // Uncommit unused semi space.
527   bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
528
529   // Allocates and initializes a new JavaScript object based on a
530   // constructor.
531   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
532   // failed.
533   // Please note this does not perform a garbage collection.
534   MUST_USE_RESULT MaybeObject* AllocateJSObject(
535       JSFunction* constructor, PretenureFlag pretenure = NOT_TENURED);
536
537   MUST_USE_RESULT MaybeObject* AllocateJSModule();
538
539   // Allocate a JSArray with no elements
540   MUST_USE_RESULT MaybeObject* AllocateEmptyJSArray(
541       ElementsKind elements_kind,
542       PretenureFlag pretenure = NOT_TENURED) {
543     return AllocateJSArrayAndStorage(elements_kind, 0, 0,
544                                      DONT_INITIALIZE_ARRAY_ELEMENTS,
545                                      pretenure);
546   }
547
548   // Allocate a JSArray with a specified length but elements that are left
549   // uninitialized.
550   MUST_USE_RESULT MaybeObject* AllocateJSArrayAndStorage(
551       ElementsKind elements_kind,
552       int length,
553       int capacity,
554       ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS,
555       PretenureFlag pretenure = NOT_TENURED);
556
557   // Allocate a JSArray with no elements
558   MUST_USE_RESULT MaybeObject* AllocateJSArrayWithElements(
559       FixedArrayBase* array_base,
560       ElementsKind elements_kind,
561       PretenureFlag pretenure = NOT_TENURED);
562
563   // Allocates and initializes a new global object based on a constructor.
564   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
565   // failed.
566   // Please note this does not perform a garbage collection.
567   MUST_USE_RESULT MaybeObject* AllocateGlobalObject(JSFunction* constructor);
568
569   // Returns a deep copy of the JavaScript object.
570   // Properties and elements are copied too.
571   // Returns failure if allocation failed.
572   MUST_USE_RESULT MaybeObject* CopyJSObject(JSObject* source);
573
574   // Allocates the function prototype.
575   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
576   // failed.
577   // Please note this does not perform a garbage collection.
578   MUST_USE_RESULT MaybeObject* AllocateFunctionPrototype(JSFunction* function);
579
580   // Allocates a Harmony proxy or function proxy.
581   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
582   // failed.
583   // Please note this does not perform a garbage collection.
584   MUST_USE_RESULT MaybeObject* AllocateJSProxy(Object* handler,
585                                                Object* prototype);
586
587   MUST_USE_RESULT MaybeObject* AllocateJSFunctionProxy(Object* handler,
588                                                        Object* call_trap,
589                                                        Object* construct_trap,
590                                                        Object* prototype);
591
592   // Reinitialize a JSReceiver into an (empty) JS object of respective type and
593   // size, but keeping the original prototype.  The receiver must have at least
594   // the size of the new object.  The object is reinitialized and behaves as an
595   // object that has been freshly allocated.
596   // Returns failure if an error occured, otherwise object.
597   MUST_USE_RESULT MaybeObject* ReinitializeJSReceiver(JSReceiver* object,
598                                                       InstanceType type,
599                                                       int size);
600
601   // Reinitialize an JSGlobalProxy based on a constructor.  The object
602   // must have the same size as objects allocated using the
603   // constructor.  The object is reinitialized and behaves as an
604   // object that has been freshly allocated using the constructor.
605   MUST_USE_RESULT MaybeObject* ReinitializeJSGlobalProxy(
606       JSFunction* constructor, JSGlobalProxy* global);
607
608   // Allocates and initializes a new JavaScript object based on a map.
609   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
610   // failed.
611   // Please note this does not perform a garbage collection.
612   MUST_USE_RESULT MaybeObject* AllocateJSObjectFromMap(
613       Map* map, PretenureFlag pretenure = NOT_TENURED);
614
615   // Allocates a heap object based on the map.
616   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
617   // failed.
618   // Please note this function does not perform a garbage collection.
619   MUST_USE_RESULT MaybeObject* Allocate(Map* map, AllocationSpace space);
620
621   // Allocates a JS Map in the heap.
622   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
623   // failed.
624   // Please note this function does not perform a garbage collection.
625   MUST_USE_RESULT MaybeObject* AllocateMap(
626       InstanceType instance_type,
627       int instance_size,
628       ElementsKind elements_kind = FAST_ELEMENTS);
629
630   // Allocates a partial map for bootstrapping.
631   MUST_USE_RESULT MaybeObject* AllocatePartialMap(InstanceType instance_type,
632                                                   int instance_size);
633
634   // Allocate a map for the specified function
635   MUST_USE_RESULT MaybeObject* AllocateInitialMap(JSFunction* fun);
636
637   // Allocates an empty code cache.
638   MUST_USE_RESULT MaybeObject* AllocateCodeCache();
639
640   // Allocates a serialized scope info.
641   MUST_USE_RESULT MaybeObject* AllocateScopeInfo(int length);
642
643   // Allocates an empty PolymorphicCodeCache.
644   MUST_USE_RESULT MaybeObject* AllocatePolymorphicCodeCache();
645
646   // Allocates a pre-tenured empty AccessorPair.
647   MUST_USE_RESULT MaybeObject* AllocateAccessorPair();
648
649   // Allocates an empty TypeFeedbackInfo.
650   MUST_USE_RESULT MaybeObject* AllocateTypeFeedbackInfo();
651
652   // Allocates an AliasedArgumentsEntry.
653   MUST_USE_RESULT MaybeObject* AllocateAliasedArgumentsEntry(int slot);
654
655   // Clear the Instanceof cache (used when a prototype changes).
656   inline void ClearInstanceofCache();
657
658   // Allocates and fully initializes a String.  There are two String
659   // encodings: ASCII and two byte. One should choose between the three string
660   // allocation functions based on the encoding of the string buffer used to
661   // initialized the string.
662   //   - ...FromAscii initializes the string from a buffer that is ASCII
663   //     encoded (it does not check that the buffer is ASCII encoded) and the
664   //     result will be ASCII encoded.
665   //   - ...FromUTF8 initializes the string from a buffer that is UTF-8
666   //     encoded.  If the characters are all single-byte characters, the
667   //     result will be ASCII encoded, otherwise it will converted to two
668   //     byte.
669   //   - ...FromTwoByte initializes the string from a buffer that is two-byte
670   //     encoded.  If the characters are all single-byte characters, the
671   //     result will be converted to ASCII, otherwise it will be left as
672   //     two-byte.
673   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
674   // failed.
675   // Please note this does not perform a garbage collection.
676   MUST_USE_RESULT MaybeObject* AllocateStringFromAscii(
677       Vector<const char> str,
678       PretenureFlag pretenure = NOT_TENURED);
679   MUST_USE_RESULT inline MaybeObject* AllocateStringFromUtf8(
680       Vector<const char> str,
681       PretenureFlag pretenure = NOT_TENURED);
682   MUST_USE_RESULT MaybeObject* AllocateStringFromUtf8Slow(
683       Vector<const char> str,
684       PretenureFlag pretenure = NOT_TENURED);
685   MUST_USE_RESULT MaybeObject* AllocateStringFromTwoByte(
686       Vector<const uc16> str,
687       PretenureFlag pretenure = NOT_TENURED);
688
689   // Allocates a symbol in old space based on the character stream.
690   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
691   // failed.
692   // Please note this function does not perform a garbage collection.
693   MUST_USE_RESULT inline MaybeObject* AllocateSymbol(Vector<const char> str,
694                                                      int chars,
695                                                      uint32_t hash_field);
696
697   MUST_USE_RESULT inline MaybeObject* AllocateAsciiSymbol(
698         Vector<const char> str,
699         uint32_t hash_field);
700
701   MUST_USE_RESULT inline MaybeObject* AllocateTwoByteSymbol(
702         Vector<const uc16> str,
703         uint32_t hash_field);
704
705   MUST_USE_RESULT MaybeObject* AllocateInternalSymbol(
706       unibrow::CharacterStream* buffer, int chars, uint32_t hash_field);
707
708   MUST_USE_RESULT MaybeObject* AllocateExternalSymbol(
709       Vector<const char> str,
710       int chars);
711
712   // Allocates and partially initializes a String.  There are two String
713   // encodings: ASCII and two byte.  These functions allocate a string of the
714   // given length and set its map and length fields.  The characters of the
715   // string are uninitialized.
716   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
717   // failed.
718   // Please note this does not perform a garbage collection.
719   MUST_USE_RESULT MaybeObject* AllocateRawAsciiString(
720       int length,
721       PretenureFlag pretenure = NOT_TENURED);
722   MUST_USE_RESULT MaybeObject* AllocateRawTwoByteString(
723       int length,
724       PretenureFlag pretenure = NOT_TENURED);
725
726   // Computes a single character string where the character has code.
727   // A cache is used for ASCII codes.
728   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
729   // failed. Please note this does not perform a garbage collection.
730   MUST_USE_RESULT MaybeObject* LookupSingleCharacterStringFromCode(
731       uint16_t code);
732
733   // Allocate a byte array of the specified length
734   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
735   // failed.
736   // Please note this does not perform a garbage collection.
737   MUST_USE_RESULT MaybeObject* AllocateByteArray(int length,
738                                                  PretenureFlag pretenure);
739
740   // Allocate a non-tenured byte array of the specified length
741   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
742   // failed.
743   // Please note this does not perform a garbage collection.
744   MUST_USE_RESULT MaybeObject* AllocateByteArray(int length);
745
746   // Allocates an external array of the specified length and type.
747   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
748   // failed.
749   // Please note this does not perform a garbage collection.
750   MUST_USE_RESULT MaybeObject* AllocateExternalArray(
751       int length,
752       ExternalArrayType array_type,
753       void* external_pointer,
754       PretenureFlag pretenure);
755
756   // Allocate a tenured JS global property cell.
757   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
758   // failed.
759   // Please note this does not perform a garbage collection.
760   MUST_USE_RESULT MaybeObject* AllocateJSGlobalPropertyCell(Object* value);
761
762   // Allocates a fixed array initialized with undefined values
763   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
764   // failed.
765   // Please note this does not perform a garbage collection.
766   MUST_USE_RESULT MaybeObject* AllocateFixedArray(int length,
767                                                   PretenureFlag pretenure);
768   // Allocates a fixed array initialized with undefined values
769   MUST_USE_RESULT MaybeObject* AllocateFixedArray(int length);
770
771   // Allocates an uninitialized fixed array. It must be filled by the caller.
772   //
773   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
774   // failed.
775   // Please note this does not perform a garbage collection.
776   MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedArray(int length);
777
778   // Make a copy of src and return it. Returns
779   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
780   MUST_USE_RESULT inline MaybeObject* CopyFixedArray(FixedArray* src);
781
782   // Make a copy of src, set the map, and return the copy. Returns
783   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
784   MUST_USE_RESULT MaybeObject* CopyFixedArrayWithMap(FixedArray* src, Map* map);
785
786   // Make a copy of src and return it. Returns
787   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
788   MUST_USE_RESULT inline MaybeObject* CopyFixedDoubleArray(
789       FixedDoubleArray* src);
790
791   // Make a copy of src, set the map, and return the copy. Returns
792   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
793   MUST_USE_RESULT MaybeObject* CopyFixedDoubleArrayWithMap(
794       FixedDoubleArray* src, Map* map);
795
796   // Allocates a fixed array initialized with the hole values.
797   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
798   // failed.
799   // Please note this does not perform a garbage collection.
800   MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithHoles(
801       int length,
802       PretenureFlag pretenure = NOT_TENURED);
803
804   MUST_USE_RESULT MaybeObject* AllocateRawFixedDoubleArray(
805       int length,
806       PretenureFlag pretenure);
807
808   // Allocates a fixed double array with uninitialized values. Returns
809   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
810   // Please note this does not perform a garbage collection.
811   MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedDoubleArray(
812       int length,
813       PretenureFlag pretenure = NOT_TENURED);
814
815   // Allocates a fixed double array with hole values. Returns
816   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
817   // Please note this does not perform a garbage collection.
818   MUST_USE_RESULT MaybeObject* AllocateFixedDoubleArrayWithHoles(
819       int length,
820       PretenureFlag pretenure = NOT_TENURED);
821
822   // AllocateHashTable is identical to AllocateFixedArray except
823   // that the resulting object has hash_table_map as map.
824   MUST_USE_RESULT MaybeObject* AllocateHashTable(
825       int length, PretenureFlag pretenure = NOT_TENURED);
826
827   // Allocate a global (but otherwise uninitialized) context.
828   MUST_USE_RESULT MaybeObject* AllocateGlobalContext();
829
830   // Allocate a module context.
831   MUST_USE_RESULT MaybeObject* AllocateModuleContext(Context* previous,
832                                                      ScopeInfo* scope_info);
833
834   // Allocate a function context.
835   MUST_USE_RESULT MaybeObject* AllocateFunctionContext(int length,
836                                                        JSFunction* function);
837
838   // Allocate a catch context.
839   MUST_USE_RESULT MaybeObject* AllocateCatchContext(JSFunction* function,
840                                                     Context* previous,
841                                                     String* name,
842                                                     Object* thrown_object);
843   // Allocate a 'with' context.
844   MUST_USE_RESULT MaybeObject* AllocateWithContext(JSFunction* function,
845                                                    Context* previous,
846                                                    JSObject* extension);
847
848   // Allocate a block context.
849   MUST_USE_RESULT MaybeObject* AllocateBlockContext(JSFunction* function,
850                                                     Context* previous,
851                                                     ScopeInfo* info);
852
853   // Allocates a new utility object in the old generation.
854   MUST_USE_RESULT MaybeObject* AllocateStruct(InstanceType type);
855
856   // Allocates a function initialized with a shared part.
857   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
858   // failed.
859   // Please note this does not perform a garbage collection.
860   MUST_USE_RESULT MaybeObject* AllocateFunction(
861       Map* function_map,
862       SharedFunctionInfo* shared,
863       Object* prototype,
864       PretenureFlag pretenure = TENURED);
865
866   // Arguments object size.
867   static const int kArgumentsObjectSize =
868       JSObject::kHeaderSize + 2 * kPointerSize;
869   // Strict mode arguments has no callee so it is smaller.
870   static const int kArgumentsObjectSizeStrict =
871       JSObject::kHeaderSize + 1 * kPointerSize;
872   // Indicies for direct access into argument objects.
873   static const int kArgumentsLengthIndex = 0;
874   // callee is only valid in non-strict mode.
875   static const int kArgumentsCalleeIndex = 1;
876
877   // Allocates an arguments object - optionally with an elements array.
878   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
879   // failed.
880   // Please note this does not perform a garbage collection.
881   MUST_USE_RESULT MaybeObject* AllocateArgumentsObject(
882       Object* callee, int length);
883
884   // Same as NewNumberFromDouble, but may return a preallocated/immutable
885   // number object (e.g., minus_zero_value_, nan_value_)
886   MUST_USE_RESULT MaybeObject* NumberFromDouble(
887       double value, PretenureFlag pretenure = NOT_TENURED);
888
889   // Allocated a HeapNumber from value.
890   MUST_USE_RESULT MaybeObject* AllocateHeapNumber(
891       double value,
892       PretenureFlag pretenure);
893   // pretenure = NOT_TENURED
894   MUST_USE_RESULT MaybeObject* AllocateHeapNumber(double value);
895
896   // Converts an int into either a Smi or a HeapNumber object.
897   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
898   // failed.
899   // Please note this does not perform a garbage collection.
900   MUST_USE_RESULT inline MaybeObject* NumberFromInt32(
901       int32_t value, PretenureFlag pretenure = NOT_TENURED);
902
903   // Converts an int into either a Smi or a HeapNumber object.
904   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
905   // failed.
906   // Please note this does not perform a garbage collection.
907   MUST_USE_RESULT inline MaybeObject* NumberFromUint32(
908       uint32_t value, PretenureFlag pretenure = NOT_TENURED);
909
910   // Allocates a new foreign object.
911   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
912   // failed.
913   // Please note this does not perform a garbage collection.
914   MUST_USE_RESULT MaybeObject* AllocateForeign(
915       Address address, PretenureFlag pretenure = NOT_TENURED);
916
917   // Allocates a new SharedFunctionInfo object.
918   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
919   // failed.
920   // Please note this does not perform a garbage collection.
921   MUST_USE_RESULT MaybeObject* AllocateSharedFunctionInfo(Object* name);
922
923   // Allocates a new JSMessageObject object.
924   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
925   // failed.
926   // Please note that this does not perform a garbage collection.
927   MUST_USE_RESULT MaybeObject* AllocateJSMessageObject(
928       String* type,
929       JSArray* arguments,
930       int start_position,
931       int end_position,
932       Object* script,
933       Object* stack_trace,
934       Object* stack_frames);
935
936   // Allocates a new cons string object.
937   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
938   // failed.
939   // Please note this does not perform a garbage collection.
940   MUST_USE_RESULT MaybeObject* AllocateConsString(String* first,
941                                                   String* second);
942
943   // Allocates a new sub string object which is a substring of an underlying
944   // string buffer stretching from the index start (inclusive) to the index
945   // end (exclusive).
946   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
947   // failed.
948   // Please note this does not perform a garbage collection.
949   MUST_USE_RESULT MaybeObject* AllocateSubString(
950       String* buffer,
951       int start,
952       int end,
953       PretenureFlag pretenure = NOT_TENURED);
954
955   // Allocate a new external string object, which is backed by a string
956   // resource that resides outside the V8 heap.
957   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
958   // failed.
959   // Please note this does not perform a garbage collection.
960   MUST_USE_RESULT MaybeObject* AllocateExternalStringFromAscii(
961       const ExternalAsciiString::Resource* resource);
962   MUST_USE_RESULT MaybeObject* AllocateExternalStringFromTwoByte(
963       const ExternalTwoByteString::Resource* resource);
964
965   // Finalizes an external string by deleting the associated external
966   // data and clearing the resource pointer.
967   inline void FinalizeExternalString(HeapObject* string);
968
969   // Allocates an uninitialized object.  The memory is non-executable if the
970   // hardware and OS allow.
971   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
972   // failed.
973   // Please note this function does not perform a garbage collection.
974   MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes,
975                                                   AllocationSpace space,
976                                                   AllocationSpace retry_space);
977
978   // Initialize a filler object to keep the ability to iterate over the heap
979   // when shortening objects.
980   void CreateFillerObjectAt(Address addr, int size);
981
982   // Makes a new native code object
983   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
984   // failed. On success, the pointer to the Code object is stored in the
985   // self_reference. This allows generated code to reference its own Code
986   // object by containing this pointer.
987   // Please note this function does not perform a garbage collection.
988   MUST_USE_RESULT MaybeObject* CreateCode(const CodeDesc& desc,
989                                           Code::Flags flags,
990                                           Handle<Object> self_reference,
991                                           bool immovable = false);
992
993   MUST_USE_RESULT MaybeObject* CopyCode(Code* code);
994
995   // Copy the code and scope info part of the code object, but insert
996   // the provided data as the relocation information.
997   MUST_USE_RESULT MaybeObject* CopyCode(Code* code, Vector<byte> reloc_info);
998
999   // Finds the symbol for string in the symbol table.
1000   // If not found, a new symbol is added to the table and returned.
1001   // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
1002   // failed.
1003   // Please note this function does not perform a garbage collection.
1004   MUST_USE_RESULT MaybeObject* LookupSymbol(Vector<const char> str);
1005   MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Vector<const char> str);
1006   MUST_USE_RESULT MaybeObject* LookupTwoByteSymbol(Vector<const uc16> str);
1007   MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(const char* str) {
1008     return LookupSymbol(CStrVector(str));
1009   }
1010   MUST_USE_RESULT MaybeObject* LookupSymbol(String* str);
1011   MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Handle<SeqAsciiString> string,
1012                                                  int from,
1013                                                  int length);
1014
1015   bool LookupSymbolIfExists(String* str, String** symbol);
1016   bool LookupTwoCharsSymbolIfExists(String* str, String** symbol);
1017
1018   // Compute the matching symbol map for a string if possible.
1019   // NULL is returned if string is in new space or not flattened.
1020   Map* SymbolMapForString(String* str);
1021
1022   // Tries to flatten a string before compare operation.
1023   //
1024   // Returns a failure in case it was decided that flattening was
1025   // necessary and failed.  Note, if flattening is not necessary the
1026   // string might stay non-flat even when not a failure is returned.
1027   //
1028   // Please note this function does not perform a garbage collection.
1029   MUST_USE_RESULT inline MaybeObject* PrepareForCompare(String* str);
1030
1031   // Converts the given boolean condition to JavaScript boolean value.
1032   inline Object* ToBoolean(bool condition);
1033
1034   // Code that should be run before and after each GC.  Includes some
1035   // reporting/verification activities when compiled with DEBUG set.
1036   void GarbageCollectionPrologue();
1037   void GarbageCollectionEpilogue();
1038
1039   // Performs garbage collection operation.
1040   // Returns whether there is a chance that another major GC could
1041   // collect more garbage.
1042   bool CollectGarbage(AllocationSpace space,
1043                       GarbageCollector collector,
1044                       const char* gc_reason,
1045                       const char* collector_reason);
1046
1047   // Performs garbage collection operation.
1048   // Returns whether there is a chance that another major GC could
1049   // collect more garbage.
1050   inline bool CollectGarbage(AllocationSpace space,
1051                              const char* gc_reason = NULL);
1052
1053   static const int kNoGCFlags = 0;
1054   static const int kSweepPreciselyMask = 1;
1055   static const int kReduceMemoryFootprintMask = 2;
1056   static const int kAbortIncrementalMarkingMask = 4;
1057
1058   // Making the heap iterable requires us to sweep precisely and abort any
1059   // incremental marking as well.
1060   static const int kMakeHeapIterableMask =
1061       kSweepPreciselyMask | kAbortIncrementalMarkingMask;
1062
1063   // Performs a full garbage collection.  If (flags & kMakeHeapIterableMask) is
1064   // non-zero, then the slower precise sweeper is used, which leaves the heap
1065   // in a state where we can iterate over the heap visiting all objects.
1066   void CollectAllGarbage(int flags, const char* gc_reason = NULL);
1067
1068   // Last hope GC, should try to squeeze as much as possible.
1069   void CollectAllAvailableGarbage(const char* gc_reason = NULL);
1070
1071   // Check whether the heap is currently iterable.
1072   bool IsHeapIterable();
1073
1074   // Ensure that we have swept all spaces in such a way that we can iterate
1075   // over all objects.  May cause a GC.
1076   void EnsureHeapIsIterable();
1077
1078   // Notify the heap that a context has been disposed.
1079   int NotifyContextDisposed() { return ++contexts_disposed_; }
1080
1081   // Utility to invoke the scavenger. This is needed in test code to
1082   // ensure correct callback for weak global handles.
1083   void PerformScavenge();
1084
1085   inline void increment_scan_on_scavenge_pages() {
1086     scan_on_scavenge_pages_++;
1087     if (FLAG_gc_verbose) {
1088       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1089     }
1090   }
1091
1092   inline void decrement_scan_on_scavenge_pages() {
1093     scan_on_scavenge_pages_--;
1094     if (FLAG_gc_verbose) {
1095       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1096     }
1097   }
1098
1099   PromotionQueue* promotion_queue() { return &promotion_queue_; }
1100
1101 #ifdef DEBUG
1102   // Utility used with flag gc-greedy.
1103   void GarbageCollectionGreedyCheck();
1104 #endif
1105
1106   void AddGCPrologueCallback(
1107       GCEpilogueCallback callback, GCType gc_type_filter);
1108   void RemoveGCPrologueCallback(GCEpilogueCallback callback);
1109
1110   void AddGCEpilogueCallback(
1111       GCEpilogueCallback callback, GCType gc_type_filter);
1112   void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
1113
1114   void SetGlobalGCPrologueCallback(GCCallback callback) {
1115     ASSERT((callback == NULL) ^ (global_gc_prologue_callback_ == NULL));
1116     global_gc_prologue_callback_ = callback;
1117   }
1118   void SetGlobalGCEpilogueCallback(GCCallback callback) {
1119     ASSERT((callback == NULL) ^ (global_gc_epilogue_callback_ == NULL));
1120     global_gc_epilogue_callback_ = callback;
1121   }
1122
1123   // Heap root getters.  We have versions with and without type::cast() here.
1124   // You can't use type::cast during GC because the assert fails.
1125   // TODO(1490): Try removing the unchecked accessors, now that GC marking does
1126   // not corrupt the map.
1127 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
1128   type* name() {                                                               \
1129     return type::cast(roots_[k##camel_name##RootIndex]);                       \
1130   }                                                                            \
1131   type* raw_unchecked_##name() {                                               \
1132     return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]);          \
1133   }
1134   ROOT_LIST(ROOT_ACCESSOR)
1135 #undef ROOT_ACCESSOR
1136
1137 // Utility type maps
1138 #define STRUCT_MAP_ACCESSOR(NAME, Name, name)                                  \
1139     Map* name##_map() {                                                        \
1140       return Map::cast(roots_[k##Name##MapRootIndex]);                         \
1141     }
1142   STRUCT_LIST(STRUCT_MAP_ACCESSOR)
1143 #undef STRUCT_MAP_ACCESSOR
1144
1145 #define SYMBOL_ACCESSOR(name, str) String* name() {                            \
1146     return String::cast(roots_[k##name##RootIndex]);                           \
1147   }
1148   SYMBOL_LIST(SYMBOL_ACCESSOR)
1149 #undef SYMBOL_ACCESSOR
1150
1151   // The hidden_symbol is special because it is the empty string, but does
1152   // not match the empty string.
1153   String* hidden_symbol() { return hidden_symbol_; }
1154
1155   void set_global_contexts_list(Object* object) {
1156     global_contexts_list_ = object;
1157   }
1158   Object* global_contexts_list() { return global_contexts_list_; }
1159
1160   // Number of mark-sweeps.
1161   int ms_count() { return ms_count_; }
1162
1163   // Iterates over all roots in the heap.
1164   void IterateRoots(ObjectVisitor* v, VisitMode mode);
1165   // Iterates over all strong roots in the heap.
1166   void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
1167   // Iterates over all the other roots in the heap.
1168   void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
1169
1170   // Iterate pointers to from semispace of new space found in memory interval
1171   // from start to end.
1172   void IterateAndMarkPointersToFromSpace(Address start,
1173                                          Address end,
1174                                          ObjectSlotCallback callback);
1175
1176   // Returns whether the object resides in new space.
1177   inline bool InNewSpace(Object* object);
1178   inline bool InNewSpace(Address addr);
1179   inline bool InNewSpacePage(Address addr);
1180   inline bool InFromSpace(Object* object);
1181   inline bool InToSpace(Object* object);
1182
1183   // Checks whether an address/object in the heap (including auxiliary
1184   // area and unused area).
1185   bool Contains(Address addr);
1186   bool Contains(HeapObject* value);
1187
1188   // Checks whether an address/object in a space.
1189   // Currently used by tests, serialization and heap verification only.
1190   bool InSpace(Address addr, AllocationSpace space);
1191   bool InSpace(HeapObject* value, AllocationSpace space);
1192
1193   // Finds out which space an object should get promoted to based on its type.
1194   inline OldSpace* TargetSpace(HeapObject* object);
1195   inline AllocationSpace TargetSpaceId(InstanceType type);
1196
1197   // Sets the stub_cache_ (only used when expanding the dictionary).
1198   void public_set_code_stubs(UnseededNumberDictionary* value) {
1199     roots_[kCodeStubsRootIndex] = value;
1200   }
1201
1202   // Support for computing object sizes for old objects during GCs. Returns
1203   // a function that is guaranteed to be safe for computing object sizes in
1204   // the current GC phase.
1205   HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
1206     return gc_safe_size_of_old_object_;
1207   }
1208
1209   // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
1210   void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
1211     roots_[kNonMonomorphicCacheRootIndex] = value;
1212   }
1213
1214   void public_set_empty_script(Script* script) {
1215     roots_[kEmptyScriptRootIndex] = script;
1216   }
1217
1218   void public_set_store_buffer_top(Address* top) {
1219     roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1220   }
1221
1222   // Update the next script id.
1223   inline void SetLastScriptId(Object* last_script_id);
1224
1225   // Generated code can embed this address to get access to the roots.
1226   Object** roots_array_start() { return roots_; }
1227
1228   Address* store_buffer_top_address() {
1229     return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1230   }
1231
1232   // Get address of global contexts list for serialization support.
1233   Object** global_contexts_list_address() {
1234     return &global_contexts_list_;
1235   }
1236
1237 #ifdef DEBUG
1238   void Print();
1239   void PrintHandles();
1240
1241   // Verify the heap is in its normal state before or after a GC.
1242   void Verify();
1243
1244   // Verify that AccessorPairs are not shared, i.e. make sure that they have
1245   // exactly one pointer to them.
1246   void VerifyNoAccessorPairSharing();
1247
1248   void OldPointerSpaceCheckStoreBuffer();
1249   void MapSpaceCheckStoreBuffer();
1250   void LargeObjectSpaceCheckStoreBuffer();
1251
1252   // Report heap statistics.
1253   void ReportHeapStatistics(const char* title);
1254   void ReportCodeStatistics(const char* title);
1255
1256   // Fill in bogus values in from space
1257   void ZapFromSpace();
1258 #endif
1259
1260   // Print short heap statistics.
1261   void PrintShortHeapStatistics();
1262
1263   // Makes a new symbol object
1264   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1265   // failed.
1266   // Please note this function does not perform a garbage collection.
1267   MUST_USE_RESULT MaybeObject* CreateSymbol(
1268       const char* str, int length, int hash);
1269   MUST_USE_RESULT MaybeObject* CreateSymbol(String* str);
1270
1271   // Write barrier support for address[offset] = o.
1272   inline void RecordWrite(Address address, int offset);
1273
1274   // Write barrier support for address[start : start + len[ = o.
1275   inline void RecordWrites(Address address, int start, int len);
1276
1277   // Given an address occupied by a live code object, return that object.
1278   Object* FindCodeObject(Address a);
1279
1280   // Invoke Shrink on shrinkable spaces.
1281   void Shrink();
1282
1283   enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1284   inline HeapState gc_state() { return gc_state_; }
1285
1286   inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1287
1288 #ifdef DEBUG
1289   bool IsAllocationAllowed() { return allocation_allowed_; }
1290   inline bool allow_allocation(bool enable);
1291
1292   bool disallow_allocation_failure() {
1293     return disallow_allocation_failure_;
1294   }
1295
1296   void TracePathToObject(Object* target);
1297   void TracePathToGlobal();
1298 #endif
1299
1300   // Callback function passed to Heap::Iterate etc.  Copies an object if
1301   // necessary, the object might be promoted to an old space.  The caller must
1302   // ensure the precondition that the object is (a) a heap object and (b) in
1303   // the heap's from space.
1304   static inline void ScavengePointer(HeapObject** p);
1305   static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1306
1307   // Commits from space if it is uncommitted.
1308   void EnsureFromSpaceIsCommitted();
1309
1310   // Support for partial snapshots.  After calling this we can allocate a
1311   // certain number of bytes using only linear allocation (with a
1312   // LinearAllocationScope and an AlwaysAllocateScope) without using freelists
1313   // or causing a GC.  It returns true of space was reserved or false if a GC is
1314   // needed.  For paged spaces the space requested must include the space wasted
1315   // at the end of each page when allocating linearly.
1316   void ReserveSpace(
1317     int new_space_size,
1318     int pointer_space_size,
1319     int data_space_size,
1320     int code_space_size,
1321     int map_space_size,
1322     int cell_space_size,
1323     int large_object_size);
1324
1325   //
1326   // Support for the API.
1327   //
1328
1329   bool CreateApiObjects();
1330
1331   // Attempt to find the number in a small cache.  If we finds it, return
1332   // the string representation of the number.  Otherwise return undefined.
1333   Object* GetNumberStringCache(Object* number);
1334
1335   // Update the cache with a new number-string pair.
1336   void SetNumberStringCache(Object* number, String* str);
1337
1338   // Adjusts the amount of registered external memory.
1339   // Returns the adjusted value.
1340   inline intptr_t AdjustAmountOfExternalAllocatedMemory(
1341       intptr_t change_in_bytes);
1342
1343   // Allocate uninitialized fixed array.
1344   MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(int length);
1345   MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(int length,
1346                                                      PretenureFlag pretenure);
1347
1348   inline intptr_t PromotedTotalSize() {
1349     return PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1350   }
1351
1352   // True if we have reached the allocation limit in the old generation that
1353   // should force the next GC (caused normally) to be a full one.
1354   inline bool OldGenerationPromotionLimitReached() {
1355     return PromotedTotalSize() > old_gen_promotion_limit_;
1356   }
1357
1358   inline intptr_t OldGenerationSpaceAvailable() {
1359     return old_gen_allocation_limit_ - PromotedTotalSize();
1360   }
1361
1362   inline intptr_t OldGenerationCapacityAvailable() {
1363     return max_old_generation_size_ - PromotedTotalSize();
1364   }
1365
1366   static const intptr_t kMinimumPromotionLimit = 5 * Page::kPageSize;
1367   static const intptr_t kMinimumAllocationLimit =
1368       8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1369
1370   intptr_t OldGenPromotionLimit(intptr_t old_gen_size) {
1371     const int divisor = FLAG_stress_compaction ? 10 : 3;
1372     intptr_t limit =
1373         Max(old_gen_size + old_gen_size / divisor, kMinimumPromotionLimit);
1374     limit += new_space_.Capacity();
1375     limit *= old_gen_limit_factor_;
1376     intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1377     return Min(limit, halfway_to_the_max);
1378   }
1379
1380   intptr_t OldGenAllocationLimit(intptr_t old_gen_size) {
1381     const int divisor = FLAG_stress_compaction ? 8 : 2;
1382     intptr_t limit =
1383         Max(old_gen_size + old_gen_size / divisor, kMinimumAllocationLimit);
1384     limit += new_space_.Capacity();
1385     limit *= old_gen_limit_factor_;
1386     intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1387     return Min(limit, halfway_to_the_max);
1388   }
1389
1390   // Implements the corresponding V8 API function.
1391   bool IdleNotification(int hint);
1392
1393   // Declare all the root indices.
1394   enum RootListIndex {
1395 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1396     STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1397 #undef ROOT_INDEX_DECLARATION
1398
1399 // Utility type maps
1400 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1401   STRUCT_LIST(DECLARE_STRUCT_MAP)
1402 #undef DECLARE_STRUCT_MAP
1403
1404 #define SYMBOL_INDEX_DECLARATION(name, str) k##name##RootIndex,
1405     SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1406 #undef SYMBOL_DECLARATION
1407
1408     kSymbolTableRootIndex,
1409     kStrongRootListLength = kSymbolTableRootIndex,
1410     kRootListLength
1411   };
1412
1413   STATIC_CHECK(kUndefinedValueRootIndex == Internals::kUndefinedValueRootIndex);
1414   STATIC_CHECK(kNullValueRootIndex == Internals::kNullValueRootIndex);
1415   STATIC_CHECK(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1416   STATIC_CHECK(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1417   STATIC_CHECK(kempty_symbolRootIndex == Internals::kEmptySymbolRootIndex);
1418
1419   MUST_USE_RESULT MaybeObject* NumberToString(
1420       Object* number, bool check_number_string_cache = true);
1421   MUST_USE_RESULT MaybeObject* Uint32ToString(
1422       uint32_t value, bool check_number_string_cache = true);
1423
1424   Map* MapForExternalArrayType(ExternalArrayType array_type);
1425   RootListIndex RootIndexForExternalArrayType(
1426       ExternalArrayType array_type);
1427
1428   void RecordStats(HeapStats* stats, bool take_snapshot = false);
1429
1430   // Copy block of memory from src to dst. Size of block should be aligned
1431   // by pointer size.
1432   static inline void CopyBlock(Address dst, Address src, int byte_size);
1433
1434   // Optimized version of memmove for blocks with pointer size aligned sizes and
1435   // pointer size aligned addresses.
1436   static inline void MoveBlock(Address dst, Address src, int byte_size);
1437
1438   // Check new space expansion criteria and expand semispaces if it was hit.
1439   void CheckNewSpaceExpansionCriteria();
1440
1441   inline void IncrementYoungSurvivorsCounter(int survived) {
1442     ASSERT(survived >= 0);
1443     young_survivors_after_last_gc_ = survived;
1444     survived_since_last_expansion_ += survived;
1445   }
1446
1447   inline bool NextGCIsLikelyToBeFull() {
1448     if (FLAG_gc_global) return true;
1449
1450     if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1451
1452     intptr_t total_promoted = PromotedTotalSize();
1453
1454     intptr_t adjusted_promotion_limit =
1455         old_gen_promotion_limit_ - new_space_.Capacity();
1456
1457     if (total_promoted >= adjusted_promotion_limit) return true;
1458
1459     intptr_t adjusted_allocation_limit =
1460         old_gen_allocation_limit_ - new_space_.Capacity() / 5;
1461
1462     if (PromotedSpaceSizeOfObjects() >= adjusted_allocation_limit) return true;
1463
1464     return false;
1465   }
1466
1467
1468   void UpdateNewSpaceReferencesInExternalStringTable(
1469       ExternalStringTableUpdaterCallback updater_func);
1470
1471   void UpdateReferencesInExternalStringTable(
1472       ExternalStringTableUpdaterCallback updater_func);
1473
1474   void ProcessWeakReferences(WeakObjectRetainer* retainer);
1475
1476   void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1477
1478   // Helper function that governs the promotion policy from new space to
1479   // old.  If the object's old address lies below the new space's age
1480   // mark or if we've already filled the bottom 1/16th of the to space,
1481   // we try to promote this object.
1482   inline bool ShouldBePromoted(Address old_address, int object_size);
1483
1484   int MaxObjectSizeInNewSpace() { return kMaxObjectSizeInNewSpace; }
1485
1486   void ClearJSFunctionResultCaches();
1487
1488   void ClearNormalizedMapCaches();
1489
1490   // Clears the cache of ICs related to this map.
1491   void ClearCacheOnMap(Map* map) {
1492     if (FLAG_cleanup_code_caches_at_gc) {
1493       map->ClearCodeCache(this);
1494     }
1495   }
1496
1497   GCTracer* tracer() { return tracer_; }
1498
1499   // Returns the size of objects residing in non new spaces.
1500   intptr_t PromotedSpaceSizeOfObjects();
1501
1502   double total_regexp_code_generated() { return total_regexp_code_generated_; }
1503   void IncreaseTotalRegexpCodeGenerated(int size) {
1504     total_regexp_code_generated_ += size;
1505   }
1506
1507   // Returns maximum GC pause.
1508   int get_max_gc_pause() { return max_gc_pause_; }
1509
1510   // Returns maximum size of objects alive after GC.
1511   intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1512
1513   // Returns minimal interval between two subsequent collections.
1514   int get_min_in_mutator() { return min_in_mutator_; }
1515
1516   MarkCompactCollector* mark_compact_collector() {
1517     return &mark_compact_collector_;
1518   }
1519
1520   StoreBuffer* store_buffer() {
1521     return &store_buffer_;
1522   }
1523
1524   Marking* marking() {
1525     return &marking_;
1526   }
1527
1528   IncrementalMarking* incremental_marking() {
1529     return &incremental_marking_;
1530   }
1531
1532   bool IsSweepingComplete() {
1533     return old_data_space()->IsSweepingComplete() &&
1534            old_pointer_space()->IsSweepingComplete();
1535   }
1536
1537   bool AdvanceSweepers(int step_size) {
1538     bool sweeping_complete = old_data_space()->AdvanceSweeper(step_size);
1539     sweeping_complete &= old_pointer_space()->AdvanceSweeper(step_size);
1540     return sweeping_complete;
1541   }
1542
1543   ExternalStringTable* external_string_table() {
1544     return &external_string_table_;
1545   }
1546
1547   // Returns the current sweep generation.
1548   int sweep_generation() {
1549     return sweep_generation_;
1550   }
1551
1552   inline Isolate* isolate();
1553
1554   inline void CallGlobalGCPrologueCallback() {
1555     if (global_gc_prologue_callback_ != NULL) global_gc_prologue_callback_();
1556   }
1557
1558   inline void CallGlobalGCEpilogueCallback() {
1559     if (global_gc_epilogue_callback_ != NULL) global_gc_epilogue_callback_();
1560   }
1561
1562   inline bool OldGenerationAllocationLimitReached();
1563
1564   inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1565     scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1566   }
1567
1568   void QueueMemoryChunkForFree(MemoryChunk* chunk);
1569   void FreeQueuedChunks();
1570
1571   // Completely clear the Instanceof cache (to stop it keeping objects alive
1572   // around a GC).
1573   inline void CompletelyClearInstanceofCache();
1574
1575   // The roots that have an index less than this are always in old space.
1576   static const int kOldSpaceRoots = 0x20;
1577
1578   uint32_t HashSeed() {
1579     uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1580     ASSERT(FLAG_randomize_hashes || seed == 0);
1581     return seed;
1582   }
1583
1584   void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1585     ASSERT(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1586     set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1587   }
1588
1589   void SetConstructStubDeoptPCOffset(int pc_offset) {
1590     ASSERT(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1591     set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1592   }
1593
1594   // For post mortem debugging.
1595   void RememberUnmappedPage(Address page, bool compacted);
1596
1597   // Global inline caching age: it is incremented on some GCs after context
1598   // disposal. We use it to flush inline caches.
1599   int global_ic_age() {
1600     return global_ic_age_;
1601   }
1602
1603   void AgeInlineCaches() {
1604     ++global_ic_age_;
1605   }
1606
1607  private:
1608   Heap();
1609
1610   // This can be calculated directly from a pointer to the heap; however, it is
1611   // more expedient to get at the isolate directly from within Heap methods.
1612   Isolate* isolate_;
1613
1614   Object* roots_[kRootListLength];
1615
1616   intptr_t code_range_size_;
1617   int reserved_semispace_size_;
1618   int max_semispace_size_;
1619   int initial_semispace_size_;
1620   intptr_t max_old_generation_size_;
1621   intptr_t max_executable_size_;
1622
1623   // For keeping track of how much data has survived
1624   // scavenge since last new space expansion.
1625   int survived_since_last_expansion_;
1626
1627   // For keeping track on when to flush RegExp code.
1628   int sweep_generation_;
1629
1630   int always_allocate_scope_depth_;
1631   int linear_allocation_scope_depth_;
1632
1633   // For keeping track of context disposals.
1634   int contexts_disposed_;
1635
1636   int global_ic_age_;
1637
1638   int scan_on_scavenge_pages_;
1639
1640 #if defined(V8_TARGET_ARCH_X64)
1641   static const int kMaxObjectSizeInNewSpace = 1024*KB;
1642 #else
1643   static const int kMaxObjectSizeInNewSpace = 512*KB;
1644 #endif
1645
1646   NewSpace new_space_;
1647   OldSpace* old_pointer_space_;
1648   OldSpace* old_data_space_;
1649   OldSpace* code_space_;
1650   MapSpace* map_space_;
1651   CellSpace* cell_space_;
1652   LargeObjectSpace* lo_space_;
1653   HeapState gc_state_;
1654   int gc_post_processing_depth_;
1655
1656   // Returns the amount of external memory registered since last global gc.
1657   intptr_t PromotedExternalMemorySize();
1658
1659   int ms_count_;  // how many mark-sweep collections happened
1660   unsigned int gc_count_;  // how many gc happened
1661
1662   // For post mortem debugging.
1663   static const int kRememberedUnmappedPages = 128;
1664   int remembered_unmapped_pages_index_;
1665   Address remembered_unmapped_pages_[kRememberedUnmappedPages];
1666
1667   // Total length of the strings we failed to flatten since the last GC.
1668   int unflattened_strings_length_;
1669
1670 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
1671   inline void set_##name(type* value) {                                        \
1672     /* The deserializer makes use of the fact that these common roots are */   \
1673     /* never in new space and never on a page that is being compacted.    */   \
1674     ASSERT(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value));  \
1675     roots_[k##camel_name##RootIndex] = value;                                  \
1676   }
1677   ROOT_LIST(ROOT_ACCESSOR)
1678 #undef ROOT_ACCESSOR
1679
1680 #ifdef DEBUG
1681   bool allocation_allowed_;
1682
1683   // If the --gc-interval flag is set to a positive value, this
1684   // variable holds the value indicating the number of allocations
1685   // remain until the next failure and garbage collection.
1686   int allocation_timeout_;
1687
1688   // Do we expect to be able to handle allocation failure at this
1689   // time?
1690   bool disallow_allocation_failure_;
1691
1692   HeapDebugUtils* debug_utils_;
1693 #endif  // DEBUG
1694
1695   // Indicates that the new space should be kept small due to high promotion
1696   // rates caused by the mutator allocating a lot of long-lived objects.
1697   bool new_space_high_promotion_mode_active_;
1698
1699   // Limit that triggers a global GC on the next (normally caused) GC.  This
1700   // is checked when we have already decided to do a GC to help determine
1701   // which collector to invoke.
1702   intptr_t old_gen_promotion_limit_;
1703
1704   // Limit that triggers a global GC as soon as is reasonable.  This is
1705   // checked before expanding a paged space in the old generation and on
1706   // every allocation in large object space.
1707   intptr_t old_gen_allocation_limit_;
1708
1709   // Sometimes the heuristics dictate that those limits are increased.  This
1710   // variable records that fact.
1711   int old_gen_limit_factor_;
1712
1713   // Used to adjust the limits that control the timing of the next GC.
1714   intptr_t size_of_old_gen_at_last_old_space_gc_;
1715
1716   // Limit on the amount of externally allocated memory allowed
1717   // between global GCs. If reached a global GC is forced.
1718   intptr_t external_allocation_limit_;
1719
1720   // The amount of external memory registered through the API kept alive
1721   // by global handles
1722   intptr_t amount_of_external_allocated_memory_;
1723
1724   // Caches the amount of external memory registered at the last global gc.
1725   intptr_t amount_of_external_allocated_memory_at_last_global_gc_;
1726
1727   // Indicates that an allocation has failed in the old generation since the
1728   // last GC.
1729   int old_gen_exhausted_;
1730
1731   Object* global_contexts_list_;
1732
1733   StoreBufferRebuilder store_buffer_rebuilder_;
1734
1735   struct StringTypeTable {
1736     InstanceType type;
1737     int size;
1738     RootListIndex index;
1739   };
1740
1741   struct ConstantSymbolTable {
1742     const char* contents;
1743     RootListIndex index;
1744   };
1745
1746   struct StructTable {
1747     InstanceType type;
1748     int size;
1749     RootListIndex index;
1750   };
1751
1752   static const StringTypeTable string_type_table[];
1753   static const ConstantSymbolTable constant_symbol_table[];
1754   static const StructTable struct_table[];
1755
1756   // The special hidden symbol which is an empty string, but does not match
1757   // any string when looked up in properties.
1758   String* hidden_symbol_;
1759
1760   // GC callback function, called before and after mark-compact GC.
1761   // Allocations in the callback function are disallowed.
1762   struct GCPrologueCallbackPair {
1763     GCPrologueCallbackPair(GCPrologueCallback callback, GCType gc_type)
1764         : callback(callback), gc_type(gc_type) {
1765     }
1766     bool operator==(const GCPrologueCallbackPair& pair) const {
1767       return pair.callback == callback;
1768     }
1769     GCPrologueCallback callback;
1770     GCType gc_type;
1771   };
1772   List<GCPrologueCallbackPair> gc_prologue_callbacks_;
1773
1774   struct GCEpilogueCallbackPair {
1775     GCEpilogueCallbackPair(GCEpilogueCallback callback, GCType gc_type)
1776         : callback(callback), gc_type(gc_type) {
1777     }
1778     bool operator==(const GCEpilogueCallbackPair& pair) const {
1779       return pair.callback == callback;
1780     }
1781     GCEpilogueCallback callback;
1782     GCType gc_type;
1783   };
1784   List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
1785
1786   GCCallback global_gc_prologue_callback_;
1787   GCCallback global_gc_epilogue_callback_;
1788
1789   // Support for computing object sizes during GC.
1790   HeapObjectCallback gc_safe_size_of_old_object_;
1791   static int GcSafeSizeOfOldObject(HeapObject* object);
1792
1793   // Update the GC state. Called from the mark-compact collector.
1794   void MarkMapPointersAsEncoded(bool encoded) {
1795     ASSERT(!encoded);
1796     gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
1797   }
1798
1799   // Checks whether a global GC is necessary
1800   GarbageCollector SelectGarbageCollector(AllocationSpace space,
1801                                           const char** reason);
1802
1803   // Performs garbage collection
1804   // Returns whether there is a chance another major GC could
1805   // collect more garbage.
1806   bool PerformGarbageCollection(GarbageCollector collector,
1807                                 GCTracer* tracer);
1808
1809
1810   inline void UpdateOldSpaceLimits();
1811
1812   // Allocate an uninitialized object in map space.  The behavior is identical
1813   // to Heap::AllocateRaw(size_in_bytes, MAP_SPACE), except that (a) it doesn't
1814   // have to test the allocation space argument and (b) can reduce code size
1815   // (since both AllocateRaw and AllocateRawMap are inlined).
1816   MUST_USE_RESULT inline MaybeObject* AllocateRawMap();
1817
1818   // Allocate an uninitialized object in the global property cell space.
1819   MUST_USE_RESULT inline MaybeObject* AllocateRawCell();
1820
1821   // Initializes a JSObject based on its map.
1822   void InitializeJSObjectFromMap(JSObject* obj,
1823                                  FixedArray* properties,
1824                                  Map* map);
1825
1826   bool CreateInitialMaps();
1827   bool CreateInitialObjects();
1828
1829   // These five Create*EntryStub functions are here and forced to not be inlined
1830   // because of a gcc-4.4 bug that assigns wrong vtable entries.
1831   NO_INLINE(void CreateJSEntryStub());
1832   NO_INLINE(void CreateJSConstructEntryStub());
1833
1834   void CreateFixedStubs();
1835
1836   MaybeObject* CreateOddball(const char* to_string,
1837                              Object* to_number,
1838                              byte kind);
1839
1840   // Allocate a JSArray with no elements
1841   MUST_USE_RESULT MaybeObject* AllocateJSArray(
1842       ElementsKind elements_kind,
1843       PretenureFlag pretenure = NOT_TENURED);
1844
1845   // Allocate empty fixed array.
1846   MUST_USE_RESULT MaybeObject* AllocateEmptyFixedArray();
1847
1848   // Allocate empty fixed double array.
1849   MUST_USE_RESULT MaybeObject* AllocateEmptyFixedDoubleArray();
1850
1851   // Performs a minor collection in new generation.
1852   void Scavenge();
1853
1854   static HeapObject* UpdateNewSpaceReferenceInExternalStringTableEntry(
1855       Heap* heap,
1856       Object** pointer);
1857
1858   Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
1859   static void ScavengeStoreBufferCallback(Heap* heap,
1860                                           MemoryChunk* page,
1861                                           StoreBufferEvent event);
1862
1863   // Performs a major collection in the whole heap.
1864   void MarkCompact(GCTracer* tracer);
1865
1866   // Code to be run before and after mark-compact.
1867   void MarkCompactPrologue();
1868
1869   // Record statistics before and after garbage collection.
1870   void ReportStatisticsBeforeGC();
1871   void ReportStatisticsAfterGC();
1872
1873   // Slow part of scavenge object.
1874   static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
1875
1876   // Initializes a function with a shared part and prototype.
1877   // Note: this code was factored out of AllocateFunction such that
1878   // other parts of the VM could use it. Specifically, a function that creates
1879   // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
1880   // Please note this does not perform a garbage collection.
1881   inline void InitializeFunction(
1882       JSFunction* function,
1883       SharedFunctionInfo* shared,
1884       Object* prototype);
1885
1886   // Total RegExp code ever generated
1887   double total_regexp_code_generated_;
1888
1889   GCTracer* tracer_;
1890
1891
1892   // Allocates a small number to string cache.
1893   MUST_USE_RESULT MaybeObject* AllocateInitialNumberStringCache();
1894   // Creates and installs the full-sized number string cache.
1895   void AllocateFullSizeNumberStringCache();
1896   // Get the length of the number to string cache based on the max semispace
1897   // size.
1898   int FullSizeNumberStringCacheLength();
1899   // Flush the number to string cache.
1900   void FlushNumberStringCache();
1901
1902   void UpdateSurvivalRateTrend(int start_new_space_size);
1903
1904   enum SurvivalRateTrend { INCREASING, STABLE, DECREASING, FLUCTUATING };
1905
1906   static const int kYoungSurvivalRateHighThreshold = 90;
1907   static const int kYoungSurvivalRateLowThreshold = 10;
1908   static const int kYoungSurvivalRateAllowedDeviation = 15;
1909
1910   int young_survivors_after_last_gc_;
1911   int high_survival_rate_period_length_;
1912   int low_survival_rate_period_length_;
1913   double survival_rate_;
1914   SurvivalRateTrend previous_survival_rate_trend_;
1915   SurvivalRateTrend survival_rate_trend_;
1916
1917   void set_survival_rate_trend(SurvivalRateTrend survival_rate_trend) {
1918     ASSERT(survival_rate_trend != FLUCTUATING);
1919     previous_survival_rate_trend_ = survival_rate_trend_;
1920     survival_rate_trend_ = survival_rate_trend;
1921   }
1922
1923   SurvivalRateTrend survival_rate_trend() {
1924     if (survival_rate_trend_ == STABLE) {
1925       return STABLE;
1926     } else if (previous_survival_rate_trend_ == STABLE) {
1927       return survival_rate_trend_;
1928     } else if (survival_rate_trend_ != previous_survival_rate_trend_) {
1929       return FLUCTUATING;
1930     } else {
1931       return survival_rate_trend_;
1932     }
1933   }
1934
1935   bool IsStableOrIncreasingSurvivalTrend() {
1936     switch (survival_rate_trend()) {
1937       case STABLE:
1938       case INCREASING:
1939         return true;
1940       default:
1941         return false;
1942     }
1943   }
1944
1945   bool IsStableOrDecreasingSurvivalTrend() {
1946     switch (survival_rate_trend()) {
1947       case STABLE:
1948       case DECREASING:
1949         return true;
1950       default:
1951         return false;
1952     }
1953   }
1954
1955   bool IsIncreasingSurvivalTrend() {
1956     return survival_rate_trend() == INCREASING;
1957   }
1958
1959   bool IsHighSurvivalRate() {
1960     return high_survival_rate_period_length_ > 0;
1961   }
1962
1963   bool IsLowSurvivalRate() {
1964     return low_survival_rate_period_length_ > 0;
1965   }
1966
1967   void SelectScavengingVisitorsTable();
1968
1969   void StartIdleRound() {
1970     mark_sweeps_since_idle_round_started_ = 0;
1971     ms_count_at_last_idle_notification_ = ms_count_;
1972   }
1973
1974   void FinishIdleRound() {
1975     mark_sweeps_since_idle_round_started_ = kMaxMarkSweepsInIdleRound;
1976     scavenges_since_last_idle_round_ = 0;
1977   }
1978
1979   bool EnoughGarbageSinceLastIdleRound() {
1980     return (scavenges_since_last_idle_round_ >= kIdleScavengeThreshold);
1981   }
1982
1983   // Estimates how many milliseconds a Mark-Sweep would take to complete.
1984   // In idle notification handler we assume that this function will return:
1985   // - a number less than 10 for small heaps, which are less than 8Mb.
1986   // - a number greater than 10 for large heaps, which are greater than 32Mb.
1987   int TimeMarkSweepWouldTakeInMs() {
1988     // Rough estimate of how many megabytes of heap can be processed in 1 ms.
1989     static const int kMbPerMs = 2;
1990
1991     int heap_size_mb = static_cast<int>(SizeOfObjects() / MB);
1992     return heap_size_mb / kMbPerMs;
1993   }
1994
1995   // Returns true if no more GC work is left.
1996   bool IdleGlobalGC();
1997
1998   void AdvanceIdleIncrementalMarking(intptr_t step_size);
1999
2000
2001   static const int kInitialSymbolTableSize = 2048;
2002   static const int kInitialEvalCacheSize = 64;
2003   static const int kInitialNumberStringCacheSize = 256;
2004
2005   // Maximum GC pause.
2006   int max_gc_pause_;
2007
2008   // Maximum size of objects alive after GC.
2009   intptr_t max_alive_after_gc_;
2010
2011   // Minimal interval between two subsequent collections.
2012   int min_in_mutator_;
2013
2014   // Size of objects alive after last GC.
2015   intptr_t alive_after_last_gc_;
2016
2017   double last_gc_end_timestamp_;
2018
2019   MarkCompactCollector mark_compact_collector_;
2020
2021   StoreBuffer store_buffer_;
2022
2023   Marking marking_;
2024
2025   IncrementalMarking incremental_marking_;
2026
2027   int number_idle_notifications_;
2028   unsigned int last_idle_notification_gc_count_;
2029   bool last_idle_notification_gc_count_init_;
2030
2031   int mark_sweeps_since_idle_round_started_;
2032   int ms_count_at_last_idle_notification_;
2033   unsigned int gc_count_at_last_idle_gc_;
2034   int scavenges_since_last_idle_round_;
2035
2036   static const int kMaxMarkSweepsInIdleRound = 7;
2037   static const int kIdleScavengeThreshold = 5;
2038
2039   // Shared state read by the scavenge collector and set by ScavengeObject.
2040   PromotionQueue promotion_queue_;
2041
2042   // Flag is set when the heap has been configured.  The heap can be repeatedly
2043   // configured through the API until it is set up.
2044   bool configured_;
2045
2046   ExternalStringTable external_string_table_;
2047
2048   VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2049
2050   MemoryChunk* chunks_queued_for_free_;
2051
2052   friend class Factory;
2053   friend class GCTracer;
2054   friend class DisallowAllocationFailure;
2055   friend class AlwaysAllocateScope;
2056   friend class LinearAllocationScope;
2057   friend class Page;
2058   friend class Isolate;
2059   friend class MarkCompactCollector;
2060   friend class StaticMarkingVisitor;
2061   friend class MapCompact;
2062
2063   DISALLOW_COPY_AND_ASSIGN(Heap);
2064 };
2065
2066
2067 class HeapStats {
2068  public:
2069   static const int kStartMarker = 0xDECADE00;
2070   static const int kEndMarker = 0xDECADE01;
2071
2072   int* start_marker;                    //  0
2073   int* new_space_size;                  //  1
2074   int* new_space_capacity;              //  2
2075   intptr_t* old_pointer_space_size;          //  3
2076   intptr_t* old_pointer_space_capacity;      //  4
2077   intptr_t* old_data_space_size;             //  5
2078   intptr_t* old_data_space_capacity;         //  6
2079   intptr_t* code_space_size;                 //  7
2080   intptr_t* code_space_capacity;             //  8
2081   intptr_t* map_space_size;                  //  9
2082   intptr_t* map_space_capacity;              // 10
2083   intptr_t* cell_space_size;                 // 11
2084   intptr_t* cell_space_capacity;             // 12
2085   intptr_t* lo_space_size;                   // 13
2086   int* global_handle_count;             // 14
2087   int* weak_global_handle_count;        // 15
2088   int* pending_global_handle_count;     // 16
2089   int* near_death_global_handle_count;  // 17
2090   int* free_global_handle_count;        // 18
2091   intptr_t* memory_allocator_size;           // 19
2092   intptr_t* memory_allocator_capacity;       // 20
2093   int* objects_per_type;                // 21
2094   int* size_per_type;                   // 22
2095   int* os_error;                        // 23
2096   int* end_marker;                      // 24
2097 };
2098
2099
2100 class AlwaysAllocateScope {
2101  public:
2102   inline AlwaysAllocateScope();
2103   inline ~AlwaysAllocateScope();
2104 };
2105
2106
2107 class LinearAllocationScope {
2108  public:
2109   inline LinearAllocationScope();
2110   inline ~LinearAllocationScope();
2111 };
2112
2113
2114 #ifdef DEBUG
2115 // Visitor class to verify interior pointers in spaces that do not contain
2116 // or care about intergenerational references. All heap object pointers have to
2117 // point into the heap to a location that has a map pointer at its first word.
2118 // Caveat: Heap::Contains is an approximation because it can return true for
2119 // objects in a heap space but above the allocation pointer.
2120 class VerifyPointersVisitor: public ObjectVisitor {
2121  public:
2122   inline void VisitPointers(Object** start, Object** end);
2123 };
2124 #endif
2125
2126
2127 // Space iterator for iterating over all spaces of the heap.
2128 // Returns each space in turn, and null when it is done.
2129 class AllSpaces BASE_EMBEDDED {
2130  public:
2131   Space* next();
2132   AllSpaces() { counter_ = FIRST_SPACE; }
2133  private:
2134   int counter_;
2135 };
2136
2137
2138 // Space iterator for iterating over all old spaces of the heap: Old pointer
2139 // space, old data space and code space.
2140 // Returns each space in turn, and null when it is done.
2141 class OldSpaces BASE_EMBEDDED {
2142  public:
2143   OldSpace* next();
2144   OldSpaces() { counter_ = OLD_POINTER_SPACE; }
2145  private:
2146   int counter_;
2147 };
2148
2149
2150 // Space iterator for iterating over all the paged spaces of the heap:
2151 // Map space, old pointer space, old data space, code space and cell space.
2152 // Returns each space in turn, and null when it is done.
2153 class PagedSpaces BASE_EMBEDDED {
2154  public:
2155   PagedSpace* next();
2156   PagedSpaces() { counter_ = OLD_POINTER_SPACE; }
2157  private:
2158   int counter_;
2159 };
2160
2161
2162 // Space iterator for iterating over all spaces of the heap.
2163 // For each space an object iterator is provided. The deallocation of the
2164 // returned object iterators is handled by the space iterator.
2165 class SpaceIterator : public Malloced {
2166  public:
2167   SpaceIterator();
2168   explicit SpaceIterator(HeapObjectCallback size_func);
2169   virtual ~SpaceIterator();
2170
2171   bool has_next();
2172   ObjectIterator* next();
2173
2174  private:
2175   ObjectIterator* CreateIterator();
2176
2177   int current_space_;  // from enum AllocationSpace.
2178   ObjectIterator* iterator_;  // object iterator for the current space.
2179   HeapObjectCallback size_func_;
2180 };
2181
2182
2183 // A HeapIterator provides iteration over the whole heap. It
2184 // aggregates the specific iterators for the different spaces as
2185 // these can only iterate over one space only.
2186 //
2187 // HeapIterator can skip free list nodes (that is, de-allocated heap
2188 // objects that still remain in the heap). As implementation of free
2189 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2190 // phases. Also, it is forbidden to interrupt iteration in this mode,
2191 // as this will leave heap objects marked (and thus, unusable).
2192 class HeapObjectsFilter;
2193
2194 class HeapIterator BASE_EMBEDDED {
2195  public:
2196   enum HeapObjectsFiltering {
2197     kNoFiltering,
2198     kFilterUnreachable
2199   };
2200
2201   HeapIterator();
2202   explicit HeapIterator(HeapObjectsFiltering filtering);
2203   ~HeapIterator();
2204
2205   HeapObject* next();
2206   void reset();
2207
2208  private:
2209   // Perform the initialization.
2210   void Init();
2211   // Perform all necessary shutdown (destruction) work.
2212   void Shutdown();
2213   HeapObject* NextObject();
2214
2215   HeapObjectsFiltering filtering_;
2216   HeapObjectsFilter* filter_;
2217   // Space iterator for iterating all the spaces.
2218   SpaceIterator* space_iterator_;
2219   // Object iterator for the space currently being iterated.
2220   ObjectIterator* object_iterator_;
2221 };
2222
2223
2224 // Cache for mapping (map, property name) into field offset.
2225 // Cleared at startup and prior to mark sweep collection.
2226 class KeyedLookupCache {
2227  public:
2228   // Lookup field offset for (map, name). If absent, -1 is returned.
2229   int Lookup(Map* map, String* name);
2230
2231   // Update an element in the cache.
2232   void Update(Map* map, String* name, int field_offset);
2233
2234   // Clear the cache.
2235   void Clear();
2236
2237   static const int kLength = 256;
2238   static const int kCapacityMask = kLength - 1;
2239   static const int kMapHashShift = 5;
2240   static const int kHashMask = -4;  // Zero the last two bits.
2241   static const int kEntriesPerBucket = 4;
2242   static const int kNotFound = -1;
2243
2244   // kEntriesPerBucket should be a power of 2.
2245   STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2246   STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2247
2248  private:
2249   KeyedLookupCache() {
2250     for (int i = 0; i < kLength; ++i) {
2251       keys_[i].map = NULL;
2252       keys_[i].name = NULL;
2253       field_offsets_[i] = kNotFound;
2254     }
2255   }
2256
2257   static inline int Hash(Map* map, String* name);
2258
2259   // Get the address of the keys and field_offsets arrays.  Used in
2260   // generated code to perform cache lookups.
2261   Address keys_address() {
2262     return reinterpret_cast<Address>(&keys_);
2263   }
2264
2265   Address field_offsets_address() {
2266     return reinterpret_cast<Address>(&field_offsets_);
2267   }
2268
2269   struct Key {
2270     Map* map;
2271     String* name;
2272   };
2273
2274   Key keys_[kLength];
2275   int field_offsets_[kLength];
2276
2277   friend class ExternalReference;
2278   friend class Isolate;
2279   DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2280 };
2281
2282
2283 // Cache for mapping (array, property name) into descriptor index.
2284 // The cache contains both positive and negative results.
2285 // Descriptor index equals kNotFound means the property is absent.
2286 // Cleared at startup and prior to any gc.
2287 class DescriptorLookupCache {
2288  public:
2289   // Lookup descriptor index for (map, name).
2290   // If absent, kAbsent is returned.
2291   int Lookup(DescriptorArray* array, String* name) {
2292     if (!StringShape(name).IsSymbol()) return kAbsent;
2293     int index = Hash(array, name);
2294     Key& key = keys_[index];
2295     if ((key.array == array) && (key.name == name)) return results_[index];
2296     return kAbsent;
2297   }
2298
2299   // Update an element in the cache.
2300   void Update(DescriptorArray* array, String* name, int result) {
2301     ASSERT(result != kAbsent);
2302     if (StringShape(name).IsSymbol()) {
2303       int index = Hash(array, name);
2304       Key& key = keys_[index];
2305       key.array = array;
2306       key.name = name;
2307       results_[index] = result;
2308     }
2309   }
2310
2311   // Clear the cache.
2312   void Clear();
2313
2314   static const int kAbsent = -2;
2315
2316  private:
2317   DescriptorLookupCache() {
2318     for (int i = 0; i < kLength; ++i) {
2319       keys_[i].array = NULL;
2320       keys_[i].name = NULL;
2321       results_[i] = kAbsent;
2322     }
2323   }
2324
2325   static int Hash(DescriptorArray* array, String* name) {
2326     // Uses only lower 32 bits if pointers are larger.
2327     uint32_t array_hash =
2328         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(array)) >> 2;
2329     uint32_t name_hash =
2330         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >> 2;
2331     return (array_hash ^ name_hash) % kLength;
2332   }
2333
2334   static const int kLength = 64;
2335   struct Key {
2336     DescriptorArray* array;
2337     String* name;
2338   };
2339
2340   Key keys_[kLength];
2341   int results_[kLength];
2342
2343   friend class Isolate;
2344   DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2345 };
2346
2347
2348 #ifdef DEBUG
2349 class DisallowAllocationFailure {
2350  public:
2351   inline DisallowAllocationFailure();
2352   inline ~DisallowAllocationFailure();
2353
2354  private:
2355   bool old_state_;
2356 };
2357 #endif
2358
2359
2360 // A helper class to document/test C++ scopes where we do not
2361 // expect a GC. Usage:
2362 //
2363 // /* Allocation not allowed: we cannot handle a GC in this scope. */
2364 // { AssertNoAllocation nogc;
2365 //   ...
2366 // }
2367 class AssertNoAllocation {
2368  public:
2369   inline AssertNoAllocation();
2370   inline ~AssertNoAllocation();
2371
2372 #ifdef DEBUG
2373  private:
2374   bool old_state_;
2375 #endif
2376 };
2377
2378
2379 class DisableAssertNoAllocation {
2380  public:
2381   inline DisableAssertNoAllocation();
2382   inline ~DisableAssertNoAllocation();
2383
2384 #ifdef DEBUG
2385  private:
2386   bool old_state_;
2387 #endif
2388 };
2389
2390 // GCTracer collects and prints ONE line after each garbage collector
2391 // invocation IFF --trace_gc is used.
2392
2393 class GCTracer BASE_EMBEDDED {
2394  public:
2395   class Scope BASE_EMBEDDED {
2396    public:
2397     enum ScopeId {
2398       EXTERNAL,
2399       MC_MARK,
2400       MC_SWEEP,
2401       MC_SWEEP_NEWSPACE,
2402       MC_EVACUATE_PAGES,
2403       MC_UPDATE_NEW_TO_NEW_POINTERS,
2404       MC_UPDATE_ROOT_TO_NEW_POINTERS,
2405       MC_UPDATE_OLD_TO_NEW_POINTERS,
2406       MC_UPDATE_POINTERS_TO_EVACUATED,
2407       MC_UPDATE_POINTERS_BETWEEN_EVACUATED,
2408       MC_UPDATE_MISC_POINTERS,
2409       MC_FLUSH_CODE,
2410       kNumberOfScopes
2411     };
2412
2413     Scope(GCTracer* tracer, ScopeId scope)
2414         : tracer_(tracer),
2415         scope_(scope) {
2416       start_time_ = OS::TimeCurrentMillis();
2417     }
2418
2419     ~Scope() {
2420       ASSERT(scope_ < kNumberOfScopes);  // scope_ is unsigned.
2421       tracer_->scopes_[scope_] += OS::TimeCurrentMillis() - start_time_;
2422     }
2423
2424    private:
2425     GCTracer* tracer_;
2426     ScopeId scope_;
2427     double start_time_;
2428   };
2429
2430   explicit GCTracer(Heap* heap,
2431                     const char* gc_reason,
2432                     const char* collector_reason);
2433   ~GCTracer();
2434
2435   // Sets the collector.
2436   void set_collector(GarbageCollector collector) { collector_ = collector; }
2437
2438   // Sets the GC count.
2439   void set_gc_count(unsigned int count) { gc_count_ = count; }
2440
2441   // Sets the full GC count.
2442   void set_full_gc_count(int count) { full_gc_count_ = count; }
2443
2444   void increment_promoted_objects_size(int object_size) {
2445     promoted_objects_size_ += object_size;
2446   }
2447
2448  private:
2449   // Returns a string matching the collector.
2450   const char* CollectorString();
2451
2452   // Returns size of object in heap (in MB).
2453   inline double SizeOfHeapObjects();
2454
2455   // Timestamp set in the constructor.
2456   double start_time_;
2457
2458   // Size of objects in heap set in constructor.
2459   intptr_t start_object_size_;
2460
2461   // Size of memory allocated from OS set in constructor.
2462   intptr_t start_memory_size_;
2463
2464   // Type of collector.
2465   GarbageCollector collector_;
2466
2467   // A count (including this one, e.g. the first collection is 1) of the
2468   // number of garbage collections.
2469   unsigned int gc_count_;
2470
2471   // A count (including this one) of the number of full garbage collections.
2472   int full_gc_count_;
2473
2474   // Amounts of time spent in different scopes during GC.
2475   double scopes_[Scope::kNumberOfScopes];
2476
2477   // Total amount of space either wasted or contained in one of free lists
2478   // before the current GC.
2479   intptr_t in_free_list_or_wasted_before_gc_;
2480
2481   // Difference between space used in the heap at the beginning of the current
2482   // collection and the end of the previous collection.
2483   intptr_t allocated_since_last_gc_;
2484
2485   // Amount of time spent in mutator that is time elapsed between end of the
2486   // previous collection and the beginning of the current one.
2487   double spent_in_mutator_;
2488
2489   // Size of objects promoted during the current collection.
2490   intptr_t promoted_objects_size_;
2491
2492   // Incremental marking steps counters.
2493   int steps_count_;
2494   double steps_took_;
2495   double longest_step_;
2496   int steps_count_since_last_gc_;
2497   double steps_took_since_last_gc_;
2498
2499   Heap* heap_;
2500
2501   const char* gc_reason_;
2502   const char* collector_reason_;
2503 };
2504
2505
2506 class StringSplitCache {
2507  public:
2508   static Object* Lookup(FixedArray* cache, String* string, String* pattern);
2509   static void Enter(Heap* heap,
2510                     FixedArray* cache,
2511                     String* string,
2512                     String* pattern,
2513                     FixedArray* array);
2514   static void Clear(FixedArray* cache);
2515   static const int kStringSplitCacheSize = 0x100;
2516
2517  private:
2518   static const int kArrayEntriesPerCacheEntry = 4;
2519   static const int kStringOffset = 0;
2520   static const int kPatternOffset = 1;
2521   static const int kArrayOffset = 2;
2522
2523   static MaybeObject* WrapFixedArrayInJSArray(Object* fixed_array);
2524 };
2525
2526
2527 class TranscendentalCache {
2528  public:
2529   enum Type {ACOS, ASIN, ATAN, COS, EXP, LOG, SIN, TAN, kNumberOfCaches};
2530   static const int kTranscendentalTypeBits = 3;
2531   STATIC_ASSERT((1 << kTranscendentalTypeBits) >= kNumberOfCaches);
2532
2533   // Returns a heap number with f(input), where f is a math function specified
2534   // by the 'type' argument.
2535   MUST_USE_RESULT inline MaybeObject* Get(Type type, double input);
2536
2537   // The cache contains raw Object pointers.  This method disposes of
2538   // them before a garbage collection.
2539   void Clear();
2540
2541  private:
2542   class SubCache {
2543     static const int kCacheSize = 512;
2544
2545     explicit SubCache(Type t);
2546
2547     MUST_USE_RESULT inline MaybeObject* Get(double input);
2548
2549     inline double Calculate(double input);
2550
2551     struct Element {
2552       uint32_t in[2];
2553       Object* output;
2554     };
2555
2556     union Converter {
2557       double dbl;
2558       uint32_t integers[2];
2559     };
2560
2561     inline static int Hash(const Converter& c) {
2562       uint32_t hash = (c.integers[0] ^ c.integers[1]);
2563       hash ^= static_cast<int32_t>(hash) >> 16;
2564       hash ^= static_cast<int32_t>(hash) >> 8;
2565       return (hash & (kCacheSize - 1));
2566     }
2567
2568     Element elements_[kCacheSize];
2569     Type type_;
2570     Isolate* isolate_;
2571
2572     // Allow access to the caches_ array as an ExternalReference.
2573     friend class ExternalReference;
2574     // Inline implementation of the cache.
2575     friend class TranscendentalCacheStub;
2576     // For evaluating value.
2577     friend class TranscendentalCache;
2578
2579     DISALLOW_COPY_AND_ASSIGN(SubCache);
2580   };
2581
2582   TranscendentalCache() {
2583     for (int i = 0; i < kNumberOfCaches; ++i) caches_[i] = NULL;
2584   }
2585
2586   // Used to create an external reference.
2587   inline Address cache_array_address();
2588
2589   // Instantiation
2590   friend class Isolate;
2591   // Inline implementation of the caching.
2592   friend class TranscendentalCacheStub;
2593   // Allow access to the caches_ array as an ExternalReference.
2594   friend class ExternalReference;
2595
2596   SubCache* caches_[kNumberOfCaches];
2597   DISALLOW_COPY_AND_ASSIGN(TranscendentalCache);
2598 };
2599
2600
2601 // Abstract base class for checking whether a weak object should be retained.
2602 class WeakObjectRetainer {
2603  public:
2604   virtual ~WeakObjectRetainer() {}
2605
2606   // Return whether this object should be retained. If NULL is returned the
2607   // object has no references. Otherwise the address of the retained object
2608   // should be returned as in some GC situations the object has been moved.
2609   virtual Object* RetainAs(Object* object) = 0;
2610 };
2611
2612
2613 // Intrusive object marking uses least significant bit of
2614 // heap object's map word to mark objects.
2615 // Normally all map words have least significant bit set
2616 // because they contain tagged map pointer.
2617 // If the bit is not set object is marked.
2618 // All objects should be unmarked before resuming
2619 // JavaScript execution.
2620 class IntrusiveMarking {
2621  public:
2622   static bool IsMarked(HeapObject* object) {
2623     return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
2624   }
2625
2626   static void ClearMark(HeapObject* object) {
2627     uintptr_t map_word = object->map_word().ToRawValue();
2628     object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
2629     ASSERT(!IsMarked(object));
2630   }
2631
2632   static void SetMark(HeapObject* object) {
2633     uintptr_t map_word = object->map_word().ToRawValue();
2634     object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
2635     ASSERT(IsMarked(object));
2636   }
2637
2638   static Map* MapOfMarkedObject(HeapObject* object) {
2639     uintptr_t map_word = object->map_word().ToRawValue();
2640     return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
2641   }
2642
2643   static int SizeOfMarkedObject(HeapObject* object) {
2644     return object->SizeFromMap(MapOfMarkedObject(object));
2645   }
2646
2647  private:
2648   static const uintptr_t kNotMarkedBit = 0x1;
2649   STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0);
2650 };
2651
2652
2653 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
2654 // Helper class for tracing paths to a search target Object from all roots.
2655 // The TracePathFrom() method can be used to trace paths from a specific
2656 // object to the search target object.
2657 class PathTracer : public ObjectVisitor {
2658  public:
2659   enum WhatToFind {
2660     FIND_ALL,   // Will find all matches.
2661     FIND_FIRST  // Will stop the search after first match.
2662   };
2663
2664   // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2665   // after the first match.  If FIND_ALL is specified, then tracing will be
2666   // done for all matches.
2667   PathTracer(Object* search_target,
2668              WhatToFind what_to_find,
2669              VisitMode visit_mode)
2670       : search_target_(search_target),
2671         found_target_(false),
2672         found_target_in_trace_(false),
2673         what_to_find_(what_to_find),
2674         visit_mode_(visit_mode),
2675         object_stack_(20),
2676         no_alloc() {}
2677
2678   virtual void VisitPointers(Object** start, Object** end);
2679
2680   void Reset();
2681   void TracePathFrom(Object** root);
2682
2683   bool found() const { return found_target_; }
2684
2685   static Object* const kAnyGlobalObject;
2686
2687  protected:
2688   class MarkVisitor;
2689   class UnmarkVisitor;
2690
2691   void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2692   void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2693   virtual void ProcessResults();
2694
2695   // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2696   static const int kMarkTag = 2;
2697
2698   Object* search_target_;
2699   bool found_target_;
2700   bool found_target_in_trace_;
2701   WhatToFind what_to_find_;
2702   VisitMode visit_mode_;
2703   List<Object*> object_stack_;
2704
2705   AssertNoAllocation no_alloc;  // i.e. no gc allowed.
2706
2707  private:
2708   DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2709 };
2710 #endif  // DEBUG || LIVE_OBJECT_LIST
2711
2712 } }  // namespace v8::internal
2713
2714 #endif  // V8_HEAP_H_