d4af4a6255c1d1d1765f8d66ea2e7c0e1436978e
[platform/upstream/nodejs.git] / deps / v8 / src / objects.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_OBJECTS_H_
6 #define V8_OBJECTS_H_
7
8 #include <iosfwd>
9
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/builtins.h"
15 #include "src/checks.h"
16 #include "src/elements-kind.h"
17 #include "src/field-index.h"
18 #include "src/flags.h"
19 #include "src/list.h"
20 #include "src/property-details.h"
21 #include "src/smart-pointers.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
24 #include "src/zone.h"
25
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h"  // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h"  // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h"  // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h"  // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h"  // NOLINT
36 #endif
37
38
39 //
40 // Most object types in the V8 JavaScript are described in this file.
41 //
42 // Inheritance hierarchy:
43 // - Object
44 //   - Smi          (immediate small integer)
45 //   - HeapObject   (superclass for everything allocated in the heap)
46 //     - JSReceiver  (suitable for property access)
47 //       - JSObject
48 //         - JSArray
49 //         - JSArrayBuffer
50 //         - JSArrayBufferView
51 //           - JSTypedArray
52 //           - JSDataView
53 //         - JSCollection
54 //           - JSSet
55 //           - JSMap
56 //         - JSSetIterator
57 //         - JSMapIterator
58 //         - JSWeakCollection
59 //           - JSWeakMap
60 //           - JSWeakSet
61 //         - JSRegExp
62 //         - JSFunction
63 //         - JSGeneratorObject
64 //         - JSModule
65 //         - GlobalObject
66 //           - JSGlobalObject
67 //           - JSBuiltinsObject
68 //         - JSGlobalProxy
69 //         - JSValue
70 //           - JSDate
71 //         - JSMessageObject
72 //       - JSProxy
73 //         - JSFunctionProxy
74 //     - FixedArrayBase
75 //       - ByteArray
76 //       - FixedArray
77 //         - DescriptorArray
78 //         - HashTable
79 //           - Dictionary
80 //           - StringTable
81 //           - CompilationCacheTable
82 //           - CodeCacheHashTable
83 //           - MapCache
84 //         - OrderedHashTable
85 //           - OrderedHashSet
86 //           - OrderedHashMap
87 //         - Context
88 //         - TypeFeedbackVector
89 //         - JSFunctionResultCache
90 //         - ScopeInfo
91 //         - TransitionArray
92 //         - ScriptContextTable
93 //         - WeakFixedArray
94 //       - FixedDoubleArray
95 //       - ExternalArray
96 //         - ExternalUint8ClampedArray
97 //         - ExternalInt8Array
98 //         - ExternalUint8Array
99 //         - ExternalInt16Array
100 //         - ExternalUint16Array
101 //         - ExternalInt32Array
102 //         - ExternalUint32Array
103 //         - ExternalFloat32Array
104 //     - Name
105 //       - String
106 //         - SeqString
107 //           - SeqOneByteString
108 //           - SeqTwoByteString
109 //         - SlicedString
110 //         - ConsString
111 //         - ExternalString
112 //           - ExternalOneByteString
113 //           - ExternalTwoByteString
114 //         - InternalizedString
115 //           - SeqInternalizedString
116 //             - SeqOneByteInternalizedString
117 //             - SeqTwoByteInternalizedString
118 //           - ConsInternalizedString
119 //           - ExternalInternalizedString
120 //             - ExternalOneByteInternalizedString
121 //             - ExternalTwoByteInternalizedString
122 //       - Symbol
123 //     - HeapNumber
124 //     - Cell
125 //       - PropertyCell
126 //     - Code
127 //     - Map
128 //     - Oddball
129 //     - Foreign
130 //     - SharedFunctionInfo
131 //     - Struct
132 //       - Box
133 //       - AccessorInfo
134 //         - ExecutableAccessorInfo
135 //       - AccessorPair
136 //       - AccessCheckInfo
137 //       - InterceptorInfo
138 //       - CallHandlerInfo
139 //       - TemplateInfo
140 //         - FunctionTemplateInfo
141 //         - ObjectTemplateInfo
142 //       - Script
143 //       - TypeSwitchInfo
144 //       - DebugInfo
145 //       - BreakPointInfo
146 //       - CodeCache
147 //     - WeakCell
148 //
149 // Formats of Object*:
150 //  Smi:        [31 bit signed int] 0
151 //  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
152
153 namespace v8 {
154 namespace internal {
155
156 enum KeyedAccessStoreMode {
157   STANDARD_STORE,
158   STORE_TRANSITION_SMI_TO_OBJECT,
159   STORE_TRANSITION_SMI_TO_DOUBLE,
160   STORE_TRANSITION_DOUBLE_TO_OBJECT,
161   STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
162   STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
163   STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
164   STORE_AND_GROW_NO_TRANSITION,
165   STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
166   STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
167   STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
168   STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
169   STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
170   STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
171   STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
172   STORE_NO_TRANSITION_HANDLE_COW
173 };
174
175
176 enum ContextualMode {
177   NOT_CONTEXTUAL,
178   CONTEXTUAL
179 };
180
181
182 enum MutableMode {
183   MUTABLE,
184   IMMUTABLE
185 };
186
187
188 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
189     STANDARD_STORE;
190 STATIC_ASSERT(STANDARD_STORE == 0);
191 STATIC_ASSERT(kGrowICDelta ==
192               STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
193               STORE_TRANSITION_SMI_TO_OBJECT);
194 STATIC_ASSERT(kGrowICDelta ==
195               STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
196               STORE_TRANSITION_SMI_TO_DOUBLE);
197 STATIC_ASSERT(kGrowICDelta ==
198               STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
199               STORE_TRANSITION_DOUBLE_TO_OBJECT);
200
201
202 static inline KeyedAccessStoreMode GetGrowStoreMode(
203     KeyedAccessStoreMode store_mode) {
204   if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
205     store_mode = static_cast<KeyedAccessStoreMode>(
206         static_cast<int>(store_mode) + kGrowICDelta);
207   }
208   return store_mode;
209 }
210
211
212 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
213   return store_mode > STANDARD_STORE &&
214       store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
215       store_mode != STORE_AND_GROW_NO_TRANSITION;
216 }
217
218
219 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
220     KeyedAccessStoreMode store_mode) {
221   if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
222     return store_mode;
223   }
224   if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
225     return STORE_AND_GROW_NO_TRANSITION;
226   }
227   return STANDARD_STORE;
228 }
229
230
231 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
232   return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
233       store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
234 }
235
236
237 enum IcCheckType { ELEMENT, PROPERTY };
238
239
240 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
241 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
242
243
244 // Indicates whether a value can be loaded as a constant.
245 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
246
247
248 // PropertyNormalizationMode is used to specify whether to keep
249 // inobject properties when normalizing properties of a JSObject.
250 enum PropertyNormalizationMode {
251   CLEAR_INOBJECT_PROPERTIES,
252   KEEP_INOBJECT_PROPERTIES
253 };
254
255
256 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
257 // will give the fastest result by tailoring the map to the prototype, but that
258 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
259 // (at least for now) when dynamically modifying the prototype chain of an
260 // object using __proto__ or Object.setPrototypeOf.
261 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
262
263
264 // Indicates whether transitions can be added to a source map or not.
265 enum TransitionFlag {
266   INSERT_TRANSITION,
267   OMIT_TRANSITION
268 };
269
270
271 enum DebugExtraICState {
272   DEBUG_BREAK,
273   DEBUG_PREPARE_STEP_IN
274 };
275
276
277 // Indicates whether the transition is simple: the target map of the transition
278 // either extends the current map with a new property, or it modifies the
279 // property that was added last to the current map.
280 enum SimpleTransitionFlag {
281   SIMPLE_PROPERTY_TRANSITION,
282   PROPERTY_TRANSITION,
283   SPECIAL_TRANSITION
284 };
285
286
287 // Indicates whether we are only interested in the descriptors of a particular
288 // map, or in all descriptors in the descriptor array.
289 enum DescriptorFlag {
290   ALL_DESCRIPTORS,
291   OWN_DESCRIPTORS
292 };
293
294 // The GC maintains a bit of information, the MarkingParity, which toggles
295 // from odd to even and back every time marking is completed. Incremental
296 // marking can visit an object twice during a marking phase, so algorithms that
297 // that piggy-back on marking can use the parity to ensure that they only
298 // perform an operation on an object once per marking phase: they record the
299 // MarkingParity when they visit an object, and only re-visit the object when it
300 // is marked again and the MarkingParity changes.
301 enum MarkingParity {
302   NO_MARKING_PARITY,
303   ODD_MARKING_PARITY,
304   EVEN_MARKING_PARITY
305 };
306
307 // ICs store extra state in a Code object. The default extra state is
308 // kNoExtraICState.
309 typedef int ExtraICState;
310 static const ExtraICState kNoExtraICState = 0;
311
312 // Instance size sentinel for objects of variable size.
313 const int kVariableSizeSentinel = 0;
314
315 // We may store the unsigned bit field as signed Smi value and do not
316 // use the sign bit.
317 const int kStubMajorKeyBits = 7;
318 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
319
320 // All Maps have a field instance_type containing a InstanceType.
321 // It describes the type of the instances.
322 //
323 // As an example, a JavaScript object is a heap object and its map
324 // instance_type is JS_OBJECT_TYPE.
325 //
326 // The names of the string instance types are intended to systematically
327 // mirror their encoding in the instance_type field of the map.  The default
328 // encoding is considered TWO_BYTE.  It is not mentioned in the name.  ONE_BYTE
329 // encoding is mentioned explicitly in the name.  Likewise, the default
330 // representation is considered sequential.  It is not mentioned in the
331 // name.  The other representations (e.g. CONS, EXTERNAL) are explicitly
332 // mentioned.  Finally, the string is either a STRING_TYPE (if it is a normal
333 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
334 //
335 // NOTE: The following things are some that depend on the string types having
336 // instance_types that are less than those of all other types:
337 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
338 // Object::IsString.
339 //
340 // NOTE: Everything following JS_VALUE_TYPE is considered a
341 // JSObject for GC purposes. The first four entries here have typeof
342 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
343 #define INSTANCE_TYPE_LIST(V)                                   \
344   V(STRING_TYPE)                                                \
345   V(ONE_BYTE_STRING_TYPE)                                       \
346   V(CONS_STRING_TYPE)                                           \
347   V(CONS_ONE_BYTE_STRING_TYPE)                                  \
348   V(SLICED_STRING_TYPE)                                         \
349   V(SLICED_ONE_BYTE_STRING_TYPE)                                \
350   V(EXTERNAL_STRING_TYPE)                                       \
351   V(EXTERNAL_ONE_BYTE_STRING_TYPE)                              \
352   V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE)                    \
353   V(SHORT_EXTERNAL_STRING_TYPE)                                 \
354   V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE)                        \
355   V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE)              \
356                                                                 \
357   V(INTERNALIZED_STRING_TYPE)                                   \
358   V(ONE_BYTE_INTERNALIZED_STRING_TYPE)                          \
359   V(EXTERNAL_INTERNALIZED_STRING_TYPE)                          \
360   V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE)                 \
361   V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE)       \
362   V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE)                    \
363   V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE)           \
364   V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
365                                                                 \
366   V(SYMBOL_TYPE)                                                \
367                                                                 \
368   V(MAP_TYPE)                                                   \
369   V(CODE_TYPE)                                                  \
370   V(ODDBALL_TYPE)                                               \
371   V(CELL_TYPE)                                                  \
372   V(PROPERTY_CELL_TYPE)                                         \
373                                                                 \
374   V(HEAP_NUMBER_TYPE)                                           \
375   V(MUTABLE_HEAP_NUMBER_TYPE)                                   \
376   V(FOREIGN_TYPE)                                               \
377   V(BYTE_ARRAY_TYPE)                                            \
378   V(FREE_SPACE_TYPE)                                            \
379   /* Note: the order of these external array */                 \
380   /* types is relied upon in */                                 \
381   /* Object::IsExternalArray(). */                              \
382   V(EXTERNAL_INT8_ARRAY_TYPE)                                   \
383   V(EXTERNAL_UINT8_ARRAY_TYPE)                                  \
384   V(EXTERNAL_INT16_ARRAY_TYPE)                                  \
385   V(EXTERNAL_UINT16_ARRAY_TYPE)                                 \
386   V(EXTERNAL_INT32_ARRAY_TYPE)                                  \
387   V(EXTERNAL_UINT32_ARRAY_TYPE)                                 \
388   V(EXTERNAL_FLOAT32_ARRAY_TYPE)                                \
389   V(EXTERNAL_FLOAT64_ARRAY_TYPE)                                \
390   V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE)                          \
391                                                                 \
392   V(FIXED_INT8_ARRAY_TYPE)                                      \
393   V(FIXED_UINT8_ARRAY_TYPE)                                     \
394   V(FIXED_INT16_ARRAY_TYPE)                                     \
395   V(FIXED_UINT16_ARRAY_TYPE)                                    \
396   V(FIXED_INT32_ARRAY_TYPE)                                     \
397   V(FIXED_UINT32_ARRAY_TYPE)                                    \
398   V(FIXED_FLOAT32_ARRAY_TYPE)                                   \
399   V(FIXED_FLOAT64_ARRAY_TYPE)                                   \
400   V(FIXED_UINT8_CLAMPED_ARRAY_TYPE)                             \
401                                                                 \
402   V(FILLER_TYPE)                                                \
403                                                                 \
404   V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE)                          \
405   V(DECLARED_ACCESSOR_INFO_TYPE)                                \
406   V(EXECUTABLE_ACCESSOR_INFO_TYPE)                              \
407   V(ACCESSOR_PAIR_TYPE)                                         \
408   V(ACCESS_CHECK_INFO_TYPE)                                     \
409   V(INTERCEPTOR_INFO_TYPE)                                      \
410   V(CALL_HANDLER_INFO_TYPE)                                     \
411   V(FUNCTION_TEMPLATE_INFO_TYPE)                                \
412   V(OBJECT_TEMPLATE_INFO_TYPE)                                  \
413   V(SIGNATURE_INFO_TYPE)                                        \
414   V(TYPE_SWITCH_INFO_TYPE)                                      \
415   V(ALLOCATION_MEMENTO_TYPE)                                    \
416   V(ALLOCATION_SITE_TYPE)                                       \
417   V(SCRIPT_TYPE)                                                \
418   V(CODE_CACHE_TYPE)                                            \
419   V(POLYMORPHIC_CODE_CACHE_TYPE)                                \
420   V(TYPE_FEEDBACK_INFO_TYPE)                                    \
421   V(ALIASED_ARGUMENTS_ENTRY_TYPE)                               \
422   V(BOX_TYPE)                                                   \
423                                                                 \
424   V(FIXED_ARRAY_TYPE)                                           \
425   V(FIXED_DOUBLE_ARRAY_TYPE)                                    \
426   V(CONSTANT_POOL_ARRAY_TYPE)                                   \
427   V(SHARED_FUNCTION_INFO_TYPE)                                  \
428   V(WEAK_CELL_TYPE)                                             \
429                                                                 \
430   V(JS_MESSAGE_OBJECT_TYPE)                                     \
431                                                                 \
432   V(JS_VALUE_TYPE)                                              \
433   V(JS_DATE_TYPE)                                               \
434   V(JS_OBJECT_TYPE)                                             \
435   V(JS_CONTEXT_EXTENSION_OBJECT_TYPE)                           \
436   V(JS_GENERATOR_OBJECT_TYPE)                                   \
437   V(JS_MODULE_TYPE)                                             \
438   V(JS_GLOBAL_OBJECT_TYPE)                                      \
439   V(JS_BUILTINS_OBJECT_TYPE)                                    \
440   V(JS_GLOBAL_PROXY_TYPE)                                       \
441   V(JS_ARRAY_TYPE)                                              \
442   V(JS_ARRAY_BUFFER_TYPE)                                       \
443   V(JS_TYPED_ARRAY_TYPE)                                        \
444   V(JS_DATA_VIEW_TYPE)                                          \
445   V(JS_PROXY_TYPE)                                              \
446   V(JS_SET_TYPE)                                                \
447   V(JS_MAP_TYPE)                                                \
448   V(JS_SET_ITERATOR_TYPE)                                       \
449   V(JS_MAP_ITERATOR_TYPE)                                       \
450   V(JS_WEAK_MAP_TYPE)                                           \
451   V(JS_WEAK_SET_TYPE)                                           \
452   V(JS_REGEXP_TYPE)                                             \
453                                                                 \
454   V(JS_FUNCTION_TYPE)                                           \
455   V(JS_FUNCTION_PROXY_TYPE)                                     \
456   V(DEBUG_INFO_TYPE)                                            \
457   V(BREAK_POINT_INFO_TYPE)
458
459
460 // Since string types are not consecutive, this macro is used to
461 // iterate over them.
462 #define STRING_TYPE_LIST(V)                                                   \
463   V(STRING_TYPE, kVariableSizeSentinel, string, String)                       \
464   V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string,             \
465     OneByteString)                                                            \
466   V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString)             \
467   V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string,       \
468     ConsOneByteString)                                                        \
469   V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString)     \
470   V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
471     SlicedOneByteString)                                                      \
472   V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string,      \
473     ExternalString)                                                           \
474   V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize,              \
475     external_one_byte_string, ExternalOneByteString)                          \
476   V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize,    \
477     external_string_with_one_byte_data, ExternalStringWithOneByteData)        \
478   V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize,            \
479     short_external_string, ShortExternalString)                               \
480   V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize,   \
481     short_external_one_byte_string, ShortExternalOneByteString)               \
482   V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE,                            \
483     ExternalTwoByteString::kShortSize,                                        \
484     short_external_string_with_one_byte_data,                                 \
485     ShortExternalStringWithOneByteData)                                       \
486                                                                               \
487   V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string,     \
488     InternalizedString)                                                       \
489   V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel,                 \
490     one_byte_internalized_string, OneByteInternalizedString)                  \
491   V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize,          \
492     external_internalized_string, ExternalInternalizedString)                 \
493   V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
494     external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
495   V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE,                     \
496     ExternalTwoByteString::kSize,                                             \
497     external_internalized_string_with_one_byte_data,                          \
498     ExternalInternalizedStringWithOneByteData)                                \
499   V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE,                                  \
500     ExternalTwoByteString::kShortSize, short_external_internalized_string,    \
501     ShortExternalInternalizedString)                                          \
502   V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE,                         \
503     ExternalOneByteString::kShortSize,                                        \
504     short_external_one_byte_internalized_string,                              \
505     ShortExternalOneByteInternalizedString)                                   \
506   V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE,               \
507     ExternalTwoByteString::kShortSize,                                        \
508     short_external_internalized_string_with_one_byte_data,                    \
509     ShortExternalInternalizedStringWithOneByteData)
510
511 // A struct is a simple object a set of object-valued fields.  Including an
512 // object type in this causes the compiler to generate most of the boilerplate
513 // code for the class including allocation and garbage collection routines,
514 // casts and predicates.  All you need to define is the class, methods and
515 // object verification routines.  Easy, no?
516 //
517 // Note that for subtle reasons related to the ordering or numerical values of
518 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
519 // manually.
520 #define STRUCT_LIST(V)                                                         \
521   V(BOX, Box, box)                                                             \
522   V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
523   V(ACCESSOR_PAIR, AccessorPair, accessor_pair)                                \
524   V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info)                     \
525   V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info)                       \
526   V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info)                     \
527   V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info)      \
528   V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info)            \
529   V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info)                        \
530   V(SCRIPT, Script, script)                                                    \
531   V(ALLOCATION_SITE, AllocationSite, allocation_site)                          \
532   V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento)                 \
533   V(CODE_CACHE, CodeCache, code_cache)                                         \
534   V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache)      \
535   V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info)                  \
536   V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)   \
537   V(DEBUG_INFO, DebugInfo, debug_info)                                         \
538   V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
539
540 // We use the full 8 bits of the instance_type field to encode heap object
541 // instance types.  The high-order bit (bit 7) is set if the object is not a
542 // string, and cleared if it is a string.
543 const uint32_t kIsNotStringMask = 0x80;
544 const uint32_t kStringTag = 0x0;
545 const uint32_t kNotStringTag = 0x80;
546
547 // Bit 6 indicates that the object is an internalized string (if set) or not.
548 // Bit 7 has to be clear as well.
549 const uint32_t kIsNotInternalizedMask = 0x40;
550 const uint32_t kNotInternalizedTag = 0x40;
551 const uint32_t kInternalizedTag = 0x0;
552
553 // If bit 7 is clear then bit 2 indicates whether the string consists of
554 // two-byte characters or one-byte characters.
555 const uint32_t kStringEncodingMask = 0x4;
556 const uint32_t kTwoByteStringTag = 0x0;
557 const uint32_t kOneByteStringTag = 0x4;
558
559 // If bit 7 is clear, the low-order 2 bits indicate the representation
560 // of the string.
561 const uint32_t kStringRepresentationMask = 0x03;
562 enum StringRepresentationTag {
563   kSeqStringTag = 0x0,
564   kConsStringTag = 0x1,
565   kExternalStringTag = 0x2,
566   kSlicedStringTag = 0x3
567 };
568 const uint32_t kIsIndirectStringMask = 0x1;
569 const uint32_t kIsIndirectStringTag = 0x1;
570 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);  // NOLINT
571 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);  // NOLINT
572 STATIC_ASSERT((kConsStringTag &
573                kIsIndirectStringMask) == kIsIndirectStringTag);  // NOLINT
574 STATIC_ASSERT((kSlicedStringTag &
575                kIsIndirectStringMask) == kIsIndirectStringTag);  // NOLINT
576
577 // Use this mask to distinguish between cons and slice only after making
578 // sure that the string is one of the two (an indirect string).
579 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
580 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
581
582 // If bit 7 is clear, then bit 3 indicates whether this two-byte
583 // string actually contains one byte data.
584 const uint32_t kOneByteDataHintMask = 0x08;
585 const uint32_t kOneByteDataHintTag = 0x08;
586
587 // If bit 7 is clear and string representation indicates an external string,
588 // then bit 4 indicates whether the data pointer is cached.
589 const uint32_t kShortExternalStringMask = 0x10;
590 const uint32_t kShortExternalStringTag = 0x10;
591
592
593 // A ConsString with an empty string as the right side is a candidate
594 // for being shortcut by the garbage collector. We don't allocate any
595 // non-flat internalized strings, so we do not shortcut them thereby
596 // avoiding turning internalized strings into strings. The bit-masks
597 // below contain the internalized bit as additional safety.
598 // See heap.cc, mark-compact.cc and objects-visiting.cc.
599 const uint32_t kShortcutTypeMask =
600     kIsNotStringMask |
601     kIsNotInternalizedMask |
602     kStringRepresentationMask;
603 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
604
605 static inline bool IsShortcutCandidate(int type) {
606   return ((type & kShortcutTypeMask) == kShortcutTypeTag);
607 }
608
609
610 enum InstanceType {
611   // String types.
612   INTERNALIZED_STRING_TYPE =
613       kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
614   ONE_BYTE_INTERNALIZED_STRING_TYPE =
615       kOneByteStringTag | kSeqStringTag | kInternalizedTag,
616   EXTERNAL_INTERNALIZED_STRING_TYPE =
617       kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
618   EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
619       kOneByteStringTag | kExternalStringTag | kInternalizedTag,
620   EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
621       EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
622       kInternalizedTag,
623   SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
624                                             kShortExternalStringTag |
625                                             kInternalizedTag,
626   SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
627       EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
628       kInternalizedTag,
629   SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
630       EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
631       kShortExternalStringTag | kInternalizedTag,
632   STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
633   ONE_BYTE_STRING_TYPE =
634       ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
635   CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
636   CONS_ONE_BYTE_STRING_TYPE =
637       kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
638   SLICED_STRING_TYPE =
639       kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
640   SLICED_ONE_BYTE_STRING_TYPE =
641       kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
642   EXTERNAL_STRING_TYPE =
643       EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
644   EXTERNAL_ONE_BYTE_STRING_TYPE =
645       EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
646   EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
647       EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
648       kNotInternalizedTag,
649   SHORT_EXTERNAL_STRING_TYPE =
650       SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651   SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
652       SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
653   SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
654       SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
655       kNotInternalizedTag,
656
657   // Non-string names
658   SYMBOL_TYPE = kNotStringTag,  // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
659
660   // Objects allocated in their own spaces (never in new space).
661   MAP_TYPE,
662   CODE_TYPE,
663   ODDBALL_TYPE,
664   CELL_TYPE,
665   PROPERTY_CELL_TYPE,
666
667   // "Data", objects that cannot contain non-map-word pointers to heap
668   // objects.
669   HEAP_NUMBER_TYPE,
670   MUTABLE_HEAP_NUMBER_TYPE,
671   FOREIGN_TYPE,
672   BYTE_ARRAY_TYPE,
673   FREE_SPACE_TYPE,
674   EXTERNAL_INT8_ARRAY_TYPE,  // FIRST_EXTERNAL_ARRAY_TYPE
675   EXTERNAL_UINT8_ARRAY_TYPE,
676   EXTERNAL_INT16_ARRAY_TYPE,
677   EXTERNAL_UINT16_ARRAY_TYPE,
678   EXTERNAL_INT32_ARRAY_TYPE,
679   EXTERNAL_UINT32_ARRAY_TYPE,
680   EXTERNAL_FLOAT32_ARRAY_TYPE,
681   EXTERNAL_FLOAT64_ARRAY_TYPE,
682   EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,  // LAST_EXTERNAL_ARRAY_TYPE
683   FIXED_INT8_ARRAY_TYPE,              // FIRST_FIXED_TYPED_ARRAY_TYPE
684   FIXED_UINT8_ARRAY_TYPE,
685   FIXED_INT16_ARRAY_TYPE,
686   FIXED_UINT16_ARRAY_TYPE,
687   FIXED_INT32_ARRAY_TYPE,
688   FIXED_UINT32_ARRAY_TYPE,
689   FIXED_FLOAT32_ARRAY_TYPE,
690   FIXED_FLOAT64_ARRAY_TYPE,
691   FIXED_UINT8_CLAMPED_ARRAY_TYPE,  // LAST_FIXED_TYPED_ARRAY_TYPE
692   FIXED_DOUBLE_ARRAY_TYPE,
693   FILLER_TYPE,  // LAST_DATA_TYPE
694
695   // Structs.
696   DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
697   DECLARED_ACCESSOR_INFO_TYPE,
698   EXECUTABLE_ACCESSOR_INFO_TYPE,
699   ACCESSOR_PAIR_TYPE,
700   ACCESS_CHECK_INFO_TYPE,
701   INTERCEPTOR_INFO_TYPE,
702   CALL_HANDLER_INFO_TYPE,
703   FUNCTION_TEMPLATE_INFO_TYPE,
704   OBJECT_TEMPLATE_INFO_TYPE,
705   SIGNATURE_INFO_TYPE,
706   TYPE_SWITCH_INFO_TYPE,
707   ALLOCATION_SITE_TYPE,
708   ALLOCATION_MEMENTO_TYPE,
709   SCRIPT_TYPE,
710   CODE_CACHE_TYPE,
711   POLYMORPHIC_CODE_CACHE_TYPE,
712   TYPE_FEEDBACK_INFO_TYPE,
713   ALIASED_ARGUMENTS_ENTRY_TYPE,
714   BOX_TYPE,
715   DEBUG_INFO_TYPE,
716   BREAK_POINT_INFO_TYPE,
717   FIXED_ARRAY_TYPE,
718   CONSTANT_POOL_ARRAY_TYPE,
719   SHARED_FUNCTION_INFO_TYPE,
720   WEAK_CELL_TYPE,
721
722   // All the following types are subtypes of JSReceiver, which corresponds to
723   // objects in the JS sense. The first and the last type in this range are
724   // the two forms of function. This organization enables using the same
725   // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
726   // NONCALLABLE_JS_OBJECT range.
727   JS_FUNCTION_PROXY_TYPE,  // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
728   JS_PROXY_TYPE,           // LAST_JS_PROXY_TYPE
729   JS_VALUE_TYPE,           // FIRST_JS_OBJECT_TYPE
730   JS_MESSAGE_OBJECT_TYPE,
731   JS_DATE_TYPE,
732   JS_OBJECT_TYPE,
733   JS_CONTEXT_EXTENSION_OBJECT_TYPE,
734   JS_GENERATOR_OBJECT_TYPE,
735   JS_MODULE_TYPE,
736   JS_GLOBAL_OBJECT_TYPE,
737   JS_BUILTINS_OBJECT_TYPE,
738   JS_GLOBAL_PROXY_TYPE,
739   JS_ARRAY_TYPE,
740   JS_ARRAY_BUFFER_TYPE,
741   JS_TYPED_ARRAY_TYPE,
742   JS_DATA_VIEW_TYPE,
743   JS_SET_TYPE,
744   JS_MAP_TYPE,
745   JS_SET_ITERATOR_TYPE,
746   JS_MAP_ITERATOR_TYPE,
747   JS_WEAK_MAP_TYPE,
748   JS_WEAK_SET_TYPE,
749   JS_REGEXP_TYPE,
750   JS_FUNCTION_TYPE,  // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
751
752   // Pseudo-types
753   FIRST_TYPE = 0x0,
754   LAST_TYPE = JS_FUNCTION_TYPE,
755   FIRST_NAME_TYPE = FIRST_TYPE,
756   LAST_NAME_TYPE = SYMBOL_TYPE,
757   FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
758   LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
759   FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
760   // Boundaries for testing for an external array.
761   FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
762   LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
763   // Boundaries for testing for a fixed typed array.
764   FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
765   LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
766   // Boundary for promotion to old data space/old pointer space.
767   LAST_DATA_TYPE = FILLER_TYPE,
768   // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
769   // Note that there is no range for JSObject or JSProxy, since their subtypes
770   // are not continuous in this enum! The enum ranges instead reflect the
771   // external class names, where proxies are treated as either ordinary objects,
772   // or functions.
773   FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
774   LAST_JS_RECEIVER_TYPE = LAST_TYPE,
775   // Boundaries for testing the types represented as JSObject
776   FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
777   LAST_JS_OBJECT_TYPE = LAST_TYPE,
778   // Boundaries for testing the types represented as JSProxy
779   FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
780   LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
781   // Boundaries for testing whether the type is a JavaScript object.
782   FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
783   LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
784   // Boundaries for testing the types for which typeof is "object".
785   FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
786   LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
787   // Note that the types for which typeof is "function" are not continuous.
788   // Define this so that we can put assertions on discrete checks.
789   NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
790 };
791
792 const int kExternalArrayTypeCount =
793     LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
794
795 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
796 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
797 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
798 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
799
800
801 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
802   V(FAST_ELEMENTS_SUB_TYPE)                   \
803   V(DICTIONARY_ELEMENTS_SUB_TYPE)             \
804   V(FAST_PROPERTIES_SUB_TYPE)                 \
805   V(DICTIONARY_PROPERTIES_SUB_TYPE)           \
806   V(MAP_CODE_CACHE_SUB_TYPE)                  \
807   V(SCOPE_INFO_SUB_TYPE)                      \
808   V(STRING_TABLE_SUB_TYPE)                    \
809   V(DESCRIPTOR_ARRAY_SUB_TYPE)                \
810   V(TRANSITION_ARRAY_SUB_TYPE)
811
812 enum FixedArraySubInstanceType {
813 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
814   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
815 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
816   LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
817 };
818
819
820 enum CompareResult {
821   LESS      = -1,
822   EQUAL     =  0,
823   GREATER   =  1,
824
825   NOT_EQUAL = GREATER
826 };
827
828
829 #define DECL_BOOLEAN_ACCESSORS(name)   \
830   inline bool name() const;            \
831   inline void set_##name(bool value);  \
832
833
834 #define DECL_ACCESSORS(name, type)                                      \
835   inline type* name() const;                                            \
836   inline void set_##name(type* value,                                   \
837                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
838
839
840 #define DECLARE_CAST(type)                              \
841   INLINE(static type* cast(Object* object));            \
842   INLINE(static const type* cast(const Object* object));
843
844
845 class AccessorPair;
846 class AllocationSite;
847 class AllocationSiteCreationContext;
848 class AllocationSiteUsageContext;
849 class ConsString;
850 class DictionaryElementsAccessor;
851 class ElementsAccessor;
852 class FixedArrayBase;
853 class FunctionLiteral;
854 class GlobalObject;
855 class LayoutDescriptor;
856 class LookupIterator;
857 class ObjectVisitor;
858 class StringStream;
859 class TypeFeedbackVector;
860 class WeakCell;
861
862 // We cannot just say "class HeapType;" if it is created from a template... =8-?
863 template<class> class TypeImpl;
864 struct HeapTypeConfig;
865 typedef TypeImpl<HeapTypeConfig> HeapType;
866
867
868 // A template-ized version of the IsXXX functions.
869 template <class C> inline bool Is(Object* obj);
870
871 #ifdef VERIFY_HEAP
872 #define DECLARE_VERIFIER(Name) void Name##Verify();
873 #else
874 #define DECLARE_VERIFIER(Name)
875 #endif
876
877 #ifdef OBJECT_PRINT
878 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os);  // NOLINT
879 #else
880 #define DECLARE_PRINTER(Name)
881 #endif
882
883
884 #define OBJECT_TYPE_LIST(V) \
885   V(Smi)                    \
886   V(HeapObject)             \
887   V(Number)
888
889 #define HEAP_OBJECT_TYPE_LIST(V)   \
890   V(HeapNumber)                    \
891   V(MutableHeapNumber)             \
892   V(Name)                          \
893   V(UniqueName)                    \
894   V(String)                        \
895   V(SeqString)                     \
896   V(ExternalString)                \
897   V(ConsString)                    \
898   V(SlicedString)                  \
899   V(ExternalTwoByteString)         \
900   V(ExternalOneByteString)         \
901   V(SeqTwoByteString)              \
902   V(SeqOneByteString)              \
903   V(InternalizedString)            \
904   V(Symbol)                        \
905                                    \
906   V(ExternalArray)                 \
907   V(ExternalInt8Array)             \
908   V(ExternalUint8Array)            \
909   V(ExternalInt16Array)            \
910   V(ExternalUint16Array)           \
911   V(ExternalInt32Array)            \
912   V(ExternalUint32Array)           \
913   V(ExternalFloat32Array)          \
914   V(ExternalFloat64Array)          \
915   V(ExternalUint8ClampedArray)     \
916   V(FixedTypedArrayBase)           \
917   V(FixedUint8Array)               \
918   V(FixedInt8Array)                \
919   V(FixedUint16Array)              \
920   V(FixedInt16Array)               \
921   V(FixedUint32Array)              \
922   V(FixedInt32Array)               \
923   V(FixedFloat32Array)             \
924   V(FixedFloat64Array)             \
925   V(FixedUint8ClampedArray)        \
926   V(ByteArray)                     \
927   V(FreeSpace)                     \
928   V(JSReceiver)                    \
929   V(JSObject)                      \
930   V(JSContextExtensionObject)      \
931   V(JSGeneratorObject)             \
932   V(JSModule)                      \
933   V(LayoutDescriptor)              \
934   V(Map)                           \
935   V(DescriptorArray)               \
936   V(TransitionArray)               \
937   V(TypeFeedbackVector)            \
938   V(DeoptimizationInputData)       \
939   V(DeoptimizationOutputData)      \
940   V(DependentCode)                 \
941   V(FixedArray)                    \
942   V(FixedDoubleArray)              \
943   V(WeakFixedArray)                \
944   V(ConstantPoolArray)             \
945   V(Context)                       \
946   V(ScriptContextTable)            \
947   V(NativeContext)                 \
948   V(ScopeInfo)                     \
949   V(JSFunction)                    \
950   V(Code)                          \
951   V(Oddball)                       \
952   V(SharedFunctionInfo)            \
953   V(JSValue)                       \
954   V(JSDate)                        \
955   V(JSMessageObject)               \
956   V(StringWrapper)                 \
957   V(Foreign)                       \
958   V(Boolean)                       \
959   V(JSArray)                       \
960   V(JSArrayBuffer)                 \
961   V(JSArrayBufferView)             \
962   V(JSTypedArray)                  \
963   V(JSDataView)                    \
964   V(JSProxy)                       \
965   V(JSFunctionProxy)               \
966   V(JSSet)                         \
967   V(JSMap)                         \
968   V(JSSetIterator)                 \
969   V(JSMapIterator)                 \
970   V(JSWeakCollection)              \
971   V(JSWeakMap)                     \
972   V(JSWeakSet)                     \
973   V(JSRegExp)                      \
974   V(HashTable)                     \
975   V(Dictionary)                    \
976   V(StringTable)                   \
977   V(JSFunctionResultCache)         \
978   V(NormalizedMapCache)            \
979   V(CompilationCacheTable)         \
980   V(CodeCacheHashTable)            \
981   V(PolymorphicCodeCacheHashTable) \
982   V(MapCache)                      \
983   V(Primitive)                     \
984   V(GlobalObject)                  \
985   V(JSGlobalObject)                \
986   V(JSBuiltinsObject)              \
987   V(JSGlobalProxy)                 \
988   V(UndetectableObject)            \
989   V(AccessCheckNeeded)             \
990   V(Cell)                          \
991   V(PropertyCell)                  \
992   V(WeakCell)                      \
993   V(ObjectHashTable)               \
994   V(WeakHashTable)                 \
995   V(OrderedHashTable)
996
997 // Object is the abstract superclass for all classes in the
998 // object hierarchy.
999 // Object does not use any virtual functions to avoid the
1000 // allocation of the C++ vtable.
1001 // Since both Smi and HeapObject are subclasses of Object no
1002 // data members can be present in Object.
1003 class Object {
1004  public:
1005   // Type testing.
1006   bool IsObject() const { return true; }
1007
1008 #define IS_TYPE_FUNCTION_DECL(type_)  INLINE(bool Is##type_() const);
1009   OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1010   HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1011 #undef IS_TYPE_FUNCTION_DECL
1012
1013   // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1014   // a keyed store is of the form a[expression] = foo.
1015   enum StoreFromKeyed {
1016     MAY_BE_STORE_FROM_KEYED,
1017     CERTAINLY_NOT_STORE_FROM_KEYED
1018   };
1019
1020   INLINE(bool IsFixedArrayBase() const);
1021   INLINE(bool IsExternal() const);
1022   INLINE(bool IsAccessorInfo() const);
1023
1024   INLINE(bool IsStruct() const);
1025 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1026   INLINE(bool Is##Name() const);
1027   STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1028 #undef DECLARE_STRUCT_PREDICATE
1029
1030   INLINE(bool IsSpecObject()) const;
1031   INLINE(bool IsSpecFunction()) const;
1032   INLINE(bool IsTemplateInfo()) const;
1033   INLINE(bool IsNameDictionary() const);
1034   INLINE(bool IsSeededNumberDictionary() const);
1035   INLINE(bool IsUnseededNumberDictionary() const);
1036   INLINE(bool IsOrderedHashSet() const);
1037   INLINE(bool IsOrderedHashMap() const);
1038   bool IsCallable() const;
1039
1040   // Oddball testing.
1041   INLINE(bool IsUndefined() const);
1042   INLINE(bool IsNull() const);
1043   INLINE(bool IsTheHole() const);
1044   INLINE(bool IsException() const);
1045   INLINE(bool IsUninitialized() const);
1046   INLINE(bool IsTrue() const);
1047   INLINE(bool IsFalse() const);
1048   INLINE(bool IsArgumentsMarker() const);
1049
1050   // Filler objects (fillers and free space objects).
1051   INLINE(bool IsFiller() const);
1052
1053   // Extract the number.
1054   inline double Number();
1055   INLINE(bool IsNaN() const);
1056   INLINE(bool IsMinusZero() const);
1057   bool ToInt32(int32_t* value);
1058   bool ToUint32(uint32_t* value);
1059
1060   inline Representation OptimalRepresentation() {
1061     if (!FLAG_track_fields) return Representation::Tagged();
1062     if (IsSmi()) {
1063       return Representation::Smi();
1064     } else if (FLAG_track_double_fields && IsHeapNumber()) {
1065       return Representation::Double();
1066     } else if (FLAG_track_computed_fields && IsUninitialized()) {
1067       return Representation::None();
1068     } else if (FLAG_track_heap_object_fields) {
1069       DCHECK(IsHeapObject());
1070       return Representation::HeapObject();
1071     } else {
1072       return Representation::Tagged();
1073     }
1074   }
1075
1076   inline bool FitsRepresentation(Representation representation) {
1077     if (FLAG_track_fields && representation.IsNone()) {
1078       return false;
1079     } else if (FLAG_track_fields && representation.IsSmi()) {
1080       return IsSmi();
1081     } else if (FLAG_track_double_fields && representation.IsDouble()) {
1082       return IsMutableHeapNumber() || IsNumber();
1083     } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1084       return IsHeapObject();
1085     }
1086     return true;
1087   }
1088
1089   Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1090
1091   inline static Handle<Object> NewStorageFor(Isolate* isolate,
1092                                              Handle<Object> object,
1093                                              Representation representation);
1094
1095   inline static Handle<Object> WrapForRead(Isolate* isolate,
1096                                            Handle<Object> object,
1097                                            Representation representation);
1098
1099   // Returns true if the object is of the correct type to be used as a
1100   // implementation of a JSObject's elements.
1101   inline bool HasValidElements();
1102
1103   inline bool HasSpecificClassOf(String* name);
1104
1105   bool BooleanValue();                                      // ECMA-262 9.2.
1106
1107   // Convert to a JSObject if needed.
1108   // native_context is used when creating wrapper object.
1109   static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1110                                                  Handle<Object> object);
1111   static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1112                                           Handle<Object> object,
1113                                           Handle<Context> context);
1114
1115   // Converts this to a Smi if possible.
1116   MUST_USE_RESULT static inline MaybeHandle<Smi> ToSmi(Isolate* isolate,
1117                                                        Handle<Object> object);
1118
1119   MUST_USE_RESULT static MaybeHandle<Object> GetProperty(LookupIterator* it);
1120
1121   // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1122   MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1123       Handle<Object> object, Handle<Name> key, Handle<Object> value,
1124       LanguageMode language_mode,
1125       StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1126
1127   MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1128       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1129       StoreFromKeyed store_mode);
1130
1131   MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1132       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1133       StoreFromKeyed store_mode);
1134
1135   MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1136       LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1137   MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1138       Isolate* isolate, Handle<Object> reciever, Handle<Object> name,
1139       Handle<Object> value, LanguageMode language_mode);
1140   MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyElement(
1141       Isolate* isolate, Handle<Object> receiver, uint32_t index,
1142       Handle<Object> value, LanguageMode language_mode);
1143   MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1144       Isolate* isolate, Handle<Object> name, Handle<Object> value,
1145       LanguageMode language_mode);
1146   MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1147       LookupIterator* it, Handle<Object> value);
1148   MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1149       LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1150       LanguageMode language_mode, StoreFromKeyed store_mode);
1151   MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1152       Handle<Object> object,
1153       Handle<Name> key);
1154   MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1155       Isolate* isolate,
1156       Handle<Object> object,
1157       const char* key);
1158   MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1159       Handle<Object> object,
1160       Handle<Name> key);
1161
1162   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1163       Handle<Object> receiver,
1164       Handle<Name> name,
1165       Handle<JSObject> holder,
1166       Handle<Object> structure);
1167   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1168       Handle<Object> receiver, Handle<Name> name, Handle<Object> value,
1169       Handle<JSObject> holder, Handle<Object> structure,
1170       LanguageMode language_mode);
1171
1172   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1173       Handle<Object> receiver,
1174       Handle<JSReceiver> getter);
1175   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1176       Handle<Object> receiver,
1177       Handle<JSReceiver> setter,
1178       Handle<Object> value);
1179
1180   MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1181       Isolate* isolate,
1182       Handle<Object> object,
1183       uint32_t index);
1184
1185   MUST_USE_RESULT static MaybeHandle<Object> GetElementWithReceiver(
1186       Isolate* isolate,
1187       Handle<Object> object,
1188       Handle<Object> receiver,
1189       uint32_t index);
1190
1191   MUST_USE_RESULT static MaybeHandle<Object> SetElementWithReceiver(
1192       Isolate* isolate, Handle<Object> object, Handle<Object> receiver,
1193       uint32_t index, Handle<Object> value, LanguageMode language_mode);
1194
1195   static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1196       Isolate* isolate, Handle<Object> receiver);
1197
1198   // Returns the permanent hash code associated with this object. May return
1199   // undefined if not yet created.
1200   Object* GetHash();
1201
1202   // Returns the permanent hash code associated with this object depending on
1203   // the actual object type. May create and store a hash code if needed and none
1204   // exists.
1205   static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1206
1207   // Checks whether this object has the same value as the given one.  This
1208   // function is implemented according to ES5, section 9.12 and can be used
1209   // to implement the Harmony "egal" function.
1210   bool SameValue(Object* other);
1211
1212   // Checks whether this object has the same value as the given one.
1213   // +0 and -0 are treated equal. Everything else is the same as SameValue.
1214   // This function is implemented according to ES6, section 7.2.4 and is used
1215   // by ES6 Map and Set.
1216   bool SameValueZero(Object* other);
1217
1218   // Tries to convert an object to an array index.  Returns true and sets
1219   // the output parameter if it succeeds.
1220   inline bool ToArrayIndex(uint32_t* index);
1221
1222   // Returns true if this is a JSValue containing a string and the index is
1223   // < the length of the string.  Used to implement [] on strings.
1224   inline bool IsStringObjectWithCharacterAt(uint32_t index);
1225
1226   DECLARE_VERIFIER(Object)
1227 #ifdef VERIFY_HEAP
1228   // Verify a pointer is a valid object pointer.
1229   static void VerifyPointer(Object* p);
1230 #endif
1231
1232   inline void VerifyApiCallResultType();
1233
1234   // Prints this object without details.
1235   void ShortPrint(FILE* out = stdout);
1236
1237   // Prints this object without details to a message accumulator.
1238   void ShortPrint(StringStream* accumulator);
1239
1240   void ShortPrint(std::ostream& os);  // NOLINT
1241
1242   DECLARE_CAST(Object)
1243
1244   // Layout description.
1245   static const int kHeaderSize = 0;  // Object does not take up any space.
1246
1247 #ifdef OBJECT_PRINT
1248   // For our gdb macros, we should perhaps change these in the future.
1249   void Print();
1250
1251   // Prints this object with details.
1252   void Print(std::ostream& os);  // NOLINT
1253 #else
1254   void Print() { ShortPrint(); }
1255   void Print(std::ostream& os) { ShortPrint(os); }  // NOLINT
1256 #endif
1257
1258  private:
1259   friend class LookupIterator;
1260   friend class PrototypeIterator;
1261
1262   // Return the map of the root of object's prototype chain.
1263   Map* GetRootMap(Isolate* isolate);
1264
1265   // Helper for SetProperty and SetSuperProperty.
1266   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1267       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1268       StoreFromKeyed store_mode, bool* found);
1269
1270   DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1271 };
1272
1273
1274 struct Brief {
1275   explicit Brief(const Object* const v) : value(v) {}
1276   const Object* value;
1277 };
1278
1279
1280 std::ostream& operator<<(std::ostream& os, const Brief& v);
1281
1282
1283 // Smi represents integer Numbers that can be stored in 31 bits.
1284 // Smis are immediate which means they are NOT allocated in the heap.
1285 // The this pointer has the following format: [31 bit signed int] 0
1286 // For long smis it has the following format:
1287 //     [32 bit signed int] [31 bits zero padding] 0
1288 // Smi stands for small integer.
1289 class Smi: public Object {
1290  public:
1291   // Returns the integer value.
1292   inline int value() const;
1293
1294   // Convert a value to a Smi object.
1295   static inline Smi* FromInt(int value);
1296
1297   static inline Smi* FromIntptr(intptr_t value);
1298
1299   // Returns whether value can be represented in a Smi.
1300   static inline bool IsValid(intptr_t value);
1301
1302   DECLARE_CAST(Smi)
1303
1304   // Dispatched behavior.
1305   void SmiPrint(std::ostream& os) const;  // NOLINT
1306   DECLARE_VERIFIER(Smi)
1307
1308   static const int kMinValue =
1309       (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1310   static const int kMaxValue = -(kMinValue + 1);
1311
1312  private:
1313   DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1314 };
1315
1316
1317 // Heap objects typically have a map pointer in their first word.  However,
1318 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1319 // encoded in the first word.  The class MapWord is an abstraction of the
1320 // value in a heap object's first word.
1321 class MapWord BASE_EMBEDDED {
1322  public:
1323   // Normal state: the map word contains a map pointer.
1324
1325   // Create a map word from a map pointer.
1326   static inline MapWord FromMap(const Map* map);
1327
1328   // View this map word as a map pointer.
1329   inline Map* ToMap();
1330
1331
1332   // Scavenge collection: the map word of live objects in the from space
1333   // contains a forwarding address (a heap object pointer in the to space).
1334
1335   // True if this map word is a forwarding address for a scavenge
1336   // collection.  Only valid during a scavenge collection (specifically,
1337   // when all map words are heap object pointers, i.e. not during a full GC).
1338   inline bool IsForwardingAddress();
1339
1340   // Create a map word from a forwarding address.
1341   static inline MapWord FromForwardingAddress(HeapObject* object);
1342
1343   // View this map word as a forwarding address.
1344   inline HeapObject* ToForwardingAddress();
1345
1346   static inline MapWord FromRawValue(uintptr_t value) {
1347     return MapWord(value);
1348   }
1349
1350   inline uintptr_t ToRawValue() {
1351     return value_;
1352   }
1353
1354  private:
1355   // HeapObject calls the private constructor and directly reads the value.
1356   friend class HeapObject;
1357
1358   explicit MapWord(uintptr_t value) : value_(value) {}
1359
1360   uintptr_t value_;
1361 };
1362
1363
1364 // HeapObject is the superclass for all classes describing heap allocated
1365 // objects.
1366 class HeapObject: public Object {
1367  public:
1368   // [map]: Contains a map which contains the object's reflective
1369   // information.
1370   inline Map* map() const;
1371   inline void set_map(Map* value);
1372   // The no-write-barrier version.  This is OK if the object is white and in
1373   // new space, or if the value is an immortal immutable object, like the maps
1374   // of primitive (non-JS) objects like strings, heap numbers etc.
1375   inline void set_map_no_write_barrier(Map* value);
1376
1377   // Get the map using acquire load.
1378   inline Map* synchronized_map();
1379   inline MapWord synchronized_map_word() const;
1380
1381   // Set the map using release store
1382   inline void synchronized_set_map(Map* value);
1383   inline void synchronized_set_map_no_write_barrier(Map* value);
1384   inline void synchronized_set_map_word(MapWord map_word);
1385
1386   // During garbage collection, the map word of a heap object does not
1387   // necessarily contain a map pointer.
1388   inline MapWord map_word() const;
1389   inline void set_map_word(MapWord map_word);
1390
1391   // The Heap the object was allocated in. Used also to access Isolate.
1392   inline Heap* GetHeap() const;
1393
1394   // Convenience method to get current isolate.
1395   inline Isolate* GetIsolate() const;
1396
1397   // Converts an address to a HeapObject pointer.
1398   static inline HeapObject* FromAddress(Address address);
1399
1400   // Returns the address of this HeapObject.
1401   inline Address address();
1402
1403   // Iterates over pointers contained in the object (including the Map)
1404   void Iterate(ObjectVisitor* v);
1405
1406   // Iterates over all pointers contained in the object except the
1407   // first map pointer.  The object type is given in the first
1408   // parameter. This function does not access the map pointer in the
1409   // object, and so is safe to call while the map pointer is modified.
1410   void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1411
1412   // Returns the heap object's size in bytes
1413   inline int Size();
1414
1415   // Returns true if this heap object may contain raw values, i.e., values that
1416   // look like pointers to heap objects.
1417   inline bool MayContainRawValues();
1418
1419   // Given a heap object's map pointer, returns the heap size in bytes
1420   // Useful when the map pointer field is used for other purposes.
1421   // GC internal.
1422   inline int SizeFromMap(Map* map);
1423
1424   // Returns the field at offset in obj, as a read/write Object* reference.
1425   // Does no checking, and is safe to use during GC, while maps are invalid.
1426   // Does not invoke write barrier, so should only be assigned to
1427   // during marking GC.
1428   static inline Object** RawField(HeapObject* obj, int offset);
1429
1430   // Adds the |code| object related to |name| to the code cache of this map. If
1431   // this map is a dictionary map that is shared, the map copied and installed
1432   // onto the object.
1433   static void UpdateMapCodeCache(Handle<HeapObject> object,
1434                                  Handle<Name> name,
1435                                  Handle<Code> code);
1436
1437   DECLARE_CAST(HeapObject)
1438
1439   // Return the write barrier mode for this. Callers of this function
1440   // must be able to present a reference to an DisallowHeapAllocation
1441   // object as a sign that they are not going to use this function
1442   // from code that allocates and thus invalidates the returned write
1443   // barrier mode.
1444   inline WriteBarrierMode GetWriteBarrierMode(
1445       const DisallowHeapAllocation& promise);
1446
1447   // Dispatched behavior.
1448   void HeapObjectShortPrint(std::ostream& os);  // NOLINT
1449 #ifdef OBJECT_PRINT
1450   void PrintHeader(std::ostream& os, const char* id);  // NOLINT
1451 #endif
1452   DECLARE_PRINTER(HeapObject)
1453   DECLARE_VERIFIER(HeapObject)
1454 #ifdef VERIFY_HEAP
1455   inline void VerifyObjectField(int offset);
1456   inline void VerifySmiField(int offset);
1457
1458   // Verify a pointer is a valid HeapObject pointer that points to object
1459   // areas in the heap.
1460   static void VerifyHeapPointer(Object* p);
1461 #endif
1462
1463   inline bool NeedsToEnsureDoubleAlignment();
1464
1465   // Layout description.
1466   // First field in a heap object is map.
1467   static const int kMapOffset = Object::kHeaderSize;
1468   static const int kHeaderSize = kMapOffset + kPointerSize;
1469
1470   STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1471
1472  protected:
1473   // helpers for calling an ObjectVisitor to iterate over pointers in the
1474   // half-open range [start, end) specified as integer offsets
1475   inline void IteratePointers(ObjectVisitor* v, int start, int end);
1476   // as above, for the single element at "offset"
1477   inline void IteratePointer(ObjectVisitor* v, int offset);
1478   // as above, for the next code link of a code object.
1479   inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1480
1481  private:
1482   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1483 };
1484
1485
1486 // This class describes a body of an object of a fixed size
1487 // in which all pointer fields are located in the [start_offset, end_offset)
1488 // interval.
1489 template<int start_offset, int end_offset, int size>
1490 class FixedBodyDescriptor {
1491  public:
1492   static const int kStartOffset = start_offset;
1493   static const int kEndOffset = end_offset;
1494   static const int kSize = size;
1495
1496   static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1497
1498   template<typename StaticVisitor>
1499   static inline void IterateBody(HeapObject* obj) {
1500     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1501                                  HeapObject::RawField(obj, end_offset));
1502   }
1503 };
1504
1505
1506 // This class describes a body of an object of a variable size
1507 // in which all pointer fields are located in the [start_offset, object_size)
1508 // interval.
1509 template<int start_offset>
1510 class FlexibleBodyDescriptor {
1511  public:
1512   static const int kStartOffset = start_offset;
1513
1514   static inline void IterateBody(HeapObject* obj,
1515                                  int object_size,
1516                                  ObjectVisitor* v);
1517
1518   template<typename StaticVisitor>
1519   static inline void IterateBody(HeapObject* obj, int object_size) {
1520     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1521                                  HeapObject::RawField(obj, object_size));
1522   }
1523 };
1524
1525
1526 // The HeapNumber class describes heap allocated numbers that cannot be
1527 // represented in a Smi (small integer)
1528 class HeapNumber: public HeapObject {
1529  public:
1530   // [value]: number value.
1531   inline double value() const;
1532   inline void set_value(double value);
1533
1534   DECLARE_CAST(HeapNumber)
1535
1536   // Dispatched behavior.
1537   bool HeapNumberBooleanValue();
1538
1539   void HeapNumberPrint(std::ostream& os);  // NOLINT
1540   DECLARE_VERIFIER(HeapNumber)
1541
1542   inline int get_exponent();
1543   inline int get_sign();
1544
1545   // Layout description.
1546   static const int kValueOffset = HeapObject::kHeaderSize;
1547   // IEEE doubles are two 32 bit words.  The first is just mantissa, the second
1548   // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1549   // words within double numbers are endian dependent and they are set
1550   // accordingly.
1551 #if defined(V8_TARGET_LITTLE_ENDIAN)
1552   static const int kMantissaOffset = kValueOffset;
1553   static const int kExponentOffset = kValueOffset + 4;
1554 #elif defined(V8_TARGET_BIG_ENDIAN)
1555   static const int kMantissaOffset = kValueOffset + 4;
1556   static const int kExponentOffset = kValueOffset;
1557 #else
1558 #error Unknown byte ordering
1559 #endif
1560
1561   static const int kSize = kValueOffset + kDoubleSize;
1562   static const uint32_t kSignMask = 0x80000000u;
1563   static const uint32_t kExponentMask = 0x7ff00000u;
1564   static const uint32_t kMantissaMask = 0xfffffu;
1565   static const int kMantissaBits = 52;
1566   static const int kExponentBits = 11;
1567   static const int kExponentBias = 1023;
1568   static const int kExponentShift = 20;
1569   static const int kInfinityOrNanExponent =
1570       (kExponentMask >> kExponentShift) - kExponentBias;
1571   static const int kMantissaBitsInTopWord = 20;
1572   static const int kNonMantissaBitsInTopWord = 12;
1573
1574  private:
1575   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1576 };
1577
1578
1579 enum EnsureElementsMode {
1580   DONT_ALLOW_DOUBLE_ELEMENTS,
1581   ALLOW_COPIED_DOUBLE_ELEMENTS,
1582   ALLOW_CONVERTED_DOUBLE_ELEMENTS
1583 };
1584
1585
1586 // Indicates whether a property should be set or (re)defined.  Setting of a
1587 // property causes attributes to remain unchanged, writability to be checked
1588 // and callbacks to be called.  Defining of a property causes attributes to
1589 // be updated and callbacks to be overridden.
1590 enum SetPropertyMode {
1591   SET_PROPERTY,
1592   DEFINE_PROPERTY
1593 };
1594
1595
1596 // Indicator for one component of an AccessorPair.
1597 enum AccessorComponent {
1598   ACCESSOR_GETTER,
1599   ACCESSOR_SETTER
1600 };
1601
1602
1603 // JSReceiver includes types on which properties can be defined, i.e.,
1604 // JSObject and JSProxy.
1605 class JSReceiver: public HeapObject {
1606  public:
1607   DECLARE_CAST(JSReceiver)
1608
1609   MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1610       Handle<JSReceiver> object, uint32_t index, Handle<Object> value,
1611       PropertyAttributes attributes, LanguageMode language_mode);
1612
1613   // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1614   MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1615       Handle<JSReceiver> object, Handle<Name> name);
1616   MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1617                                                            Handle<Name> name);
1618   MUST_USE_RESULT static inline Maybe<bool> HasElement(
1619       Handle<JSReceiver> object, uint32_t index);
1620   MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1621       Handle<JSReceiver> object, uint32_t index);
1622
1623   // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1624   MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1625       Handle<JSReceiver> object, Handle<Name> name,
1626       LanguageMode language_mode = SLOPPY);
1627   MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1628       Handle<JSReceiver> object, uint32_t index,
1629       LanguageMode language_mode = SLOPPY);
1630
1631   // Tests for the fast common case for property enumeration.
1632   bool IsSimpleEnum();
1633
1634   // Returns the class name ([[Class]] property in the specification).
1635   String* class_name();
1636
1637   // Returns the constructor name (the name (possibly, inferred name) of the
1638   // function that was used to instantiate the object).
1639   String* constructor_name();
1640
1641   MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1642       Handle<JSReceiver> object, Handle<Name> name);
1643   MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1644       LookupIterator* it);
1645   MUST_USE_RESULT static Maybe<PropertyAttributes> GetOwnPropertyAttributes(
1646       Handle<JSReceiver> object, Handle<Name> name);
1647
1648   MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttribute(
1649       Handle<JSReceiver> object, uint32_t index);
1650   MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1651       GetOwnElementAttribute(Handle<JSReceiver> object, uint32_t index);
1652
1653   // Retrieves a permanent object identity hash code. The undefined value might
1654   // be returned in case no hash was created yet.
1655   inline Object* GetIdentityHash();
1656
1657   // Retrieves a permanent object identity hash code. May create and store a
1658   // hash code if needed and none exists.
1659   inline static Handle<Smi> GetOrCreateIdentityHash(
1660       Handle<JSReceiver> object);
1661
1662   enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1663
1664   // Computes the enumerable keys for a JSObject. Used for implementing
1665   // "for (n in object) { }".
1666   MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1667       Handle<JSReceiver> object,
1668       KeyCollectionType type);
1669
1670  private:
1671   DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1672 };
1673
1674 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
1675 class ObjectHashTable;
1676
1677 // Forward declaration for JSObject::Copy.
1678 class AllocationSite;
1679
1680
1681 // The JSObject describes real heap allocated JavaScript objects with
1682 // properties.
1683 // Note that the map of JSObject changes during execution to enable inline
1684 // caching.
1685 class JSObject: public JSReceiver {
1686  public:
1687   // [properties]: Backing storage for properties.
1688   // properties is a FixedArray in the fast case and a Dictionary in the
1689   // slow case.
1690   DECL_ACCESSORS(properties, FixedArray)  // Get and set fast properties.
1691   inline void initialize_properties();
1692   inline bool HasFastProperties();
1693   inline NameDictionary* property_dictionary();  // Gets slow properties.
1694
1695   // [elements]: The elements (properties with names that are integers).
1696   //
1697   // Elements can be in two general modes: fast and slow. Each mode
1698   // corrensponds to a set of object representations of elements that
1699   // have something in common.
1700   //
1701   // In the fast mode elements is a FixedArray and so each element can
1702   // be quickly accessed. This fact is used in the generated code. The
1703   // elements array can have one of three maps in this mode:
1704   // fixed_array_map, sloppy_arguments_elements_map or
1705   // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1706   // the elements array may be shared by a few objects and so before
1707   // writing to any element the array must be copied. Use
1708   // EnsureWritableFastElements in this case.
1709   //
1710   // In the slow mode the elements is either a NumberDictionary, an
1711   // ExternalArray, or a FixedArray parameter map for a (sloppy)
1712   // arguments object.
1713   DECL_ACCESSORS(elements, FixedArrayBase)
1714   inline void initialize_elements();
1715   static void ResetElements(Handle<JSObject> object);
1716   static inline void SetMapAndElements(Handle<JSObject> object,
1717                                        Handle<Map> map,
1718                                        Handle<FixedArrayBase> elements);
1719   inline ElementsKind GetElementsKind();
1720   inline ElementsAccessor* GetElementsAccessor();
1721   // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1722   inline bool HasFastSmiElements();
1723   // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1724   inline bool HasFastObjectElements();
1725   // Returns true if an object has elements of FAST_ELEMENTS or
1726   // FAST_SMI_ONLY_ELEMENTS.
1727   inline bool HasFastSmiOrObjectElements();
1728   // Returns true if an object has any of the fast elements kinds.
1729   inline bool HasFastElements();
1730   // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1731   // ElementsKind.
1732   inline bool HasFastDoubleElements();
1733   // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1734   // ElementsKind.
1735   inline bool HasFastHoleyElements();
1736   inline bool HasSloppyArgumentsElements();
1737   inline bool HasDictionaryElements();
1738
1739   inline bool HasExternalUint8ClampedElements();
1740   inline bool HasExternalArrayElements();
1741   inline bool HasExternalInt8Elements();
1742   inline bool HasExternalUint8Elements();
1743   inline bool HasExternalInt16Elements();
1744   inline bool HasExternalUint16Elements();
1745   inline bool HasExternalInt32Elements();
1746   inline bool HasExternalUint32Elements();
1747   inline bool HasExternalFloat32Elements();
1748   inline bool HasExternalFloat64Elements();
1749
1750   inline bool HasFixedTypedArrayElements();
1751
1752   inline bool HasFixedUint8ClampedElements();
1753   inline bool HasFixedArrayElements();
1754   inline bool HasFixedInt8Elements();
1755   inline bool HasFixedUint8Elements();
1756   inline bool HasFixedInt16Elements();
1757   inline bool HasFixedUint16Elements();
1758   inline bool HasFixedInt32Elements();
1759   inline bool HasFixedUint32Elements();
1760   inline bool HasFixedFloat32Elements();
1761   inline bool HasFixedFloat64Elements();
1762
1763   bool HasFastArgumentsElements();
1764   bool HasDictionaryArgumentsElements();
1765   inline SeededNumberDictionary* element_dictionary();  // Gets slow elements.
1766
1767   // Requires: HasFastElements().
1768   static Handle<FixedArray> EnsureWritableFastElements(
1769       Handle<JSObject> object);
1770
1771   // Collects elements starting at index 0.
1772   // Undefined values are placed after non-undefined values.
1773   // Returns the number of non-undefined values.
1774   static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1775                                                uint32_t limit);
1776   // As PrepareElementsForSort, but only on objects where elements is
1777   // a dictionary, and it will stay a dictionary.  Collates undefined and
1778   // unexisting elements below limit from position zero of the elements.
1779   static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1780                                                    uint32_t limit);
1781
1782   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1783       LookupIterator* it, Handle<Object> value);
1784
1785   // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1786   // grant an exemption to ExecutableAccessor callbacks in some cases.
1787   enum ExecutableAccessorInfoHandling {
1788     DEFAULT_HANDLING,
1789     DONT_FORCE_FIELD
1790   };
1791
1792   MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1793       Handle<JSObject> object,
1794       Handle<Name> key,
1795       Handle<Object> value,
1796       PropertyAttributes attributes,
1797       ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1798
1799   static void AddProperty(Handle<JSObject> object, Handle<Name> key,
1800                           Handle<Object> value, PropertyAttributes attributes);
1801
1802   // Extend the receiver with a single fast property appeared first in the
1803   // passed map. This also extends the property backing store if necessary.
1804   static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1805
1806   // Migrates the given object to a map whose field representations are the
1807   // lowest upper bound of all known representations for that field.
1808   static void MigrateInstance(Handle<JSObject> instance);
1809
1810   // Migrates the given object only if the target map is already available,
1811   // or returns false if such a map is not yet available.
1812   static bool TryMigrateInstance(Handle<JSObject> instance);
1813
1814   // Sets the property value in a normalized object given (key, value, details).
1815   // Handles the special representation of JS global objects.
1816   static void SetNormalizedProperty(Handle<JSObject> object,
1817                                     Handle<Name> key,
1818                                     Handle<Object> value,
1819                                     PropertyDetails details);
1820
1821   static void OptimizeAsPrototype(Handle<JSObject> object,
1822                                   PrototypeOptimizationMode mode);
1823   static void ReoptimizeIfPrototype(Handle<JSObject> object);
1824   static void RegisterPrototypeUser(Handle<JSObject> prototype,
1825                                     Handle<HeapObject> user);
1826   static void UnregisterPrototypeUser(Handle<JSObject> prototype,
1827                                       Handle<HeapObject> user);
1828
1829   // Retrieve interceptors.
1830   InterceptorInfo* GetNamedInterceptor();
1831   InterceptorInfo* GetIndexedInterceptor();
1832
1833   // Used from JSReceiver.
1834   MUST_USE_RESULT static Maybe<PropertyAttributes>
1835       GetPropertyAttributesWithInterceptor(Handle<JSObject> holder,
1836                                            Handle<Object> receiver,
1837                                            Handle<Name> name);
1838   MUST_USE_RESULT static Maybe<PropertyAttributes>
1839       GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1840   MUST_USE_RESULT static Maybe<PropertyAttributes>
1841       GetElementAttributeWithReceiver(Handle<JSObject> object,
1842                                       Handle<JSReceiver> receiver,
1843                                       uint32_t index, bool check_prototype);
1844
1845   // Retrieves an AccessorPair property from the given object. Might return
1846   // undefined if the property doesn't exist or is of a different kind.
1847   MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1848       Handle<JSObject> object,
1849       Handle<Name> name,
1850       AccessorComponent component);
1851
1852   // Defines an AccessorPair property on the given object.
1853   // TODO(mstarzinger): Rename to SetAccessor().
1854   static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1855                                             Handle<Name> name,
1856                                             Handle<Object> getter,
1857                                             Handle<Object> setter,
1858                                             PropertyAttributes attributes);
1859
1860   // Defines an AccessorInfo property on the given object.
1861   MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1862       Handle<JSObject> object,
1863       Handle<AccessorInfo> info);
1864
1865   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1866       Handle<JSObject> object,
1867       Handle<Object> receiver,
1868       Handle<Name> name);
1869
1870   // Accessors for hidden properties object.
1871   //
1872   // Hidden properties are not own properties of the object itself.
1873   // Instead they are stored in an auxiliary structure kept as an own
1874   // property with a special name Heap::hidden_string(). But if the
1875   // receiver is a JSGlobalProxy then the auxiliary object is a property
1876   // of its prototype, and if it's a detached proxy, then you can't have
1877   // hidden properties.
1878
1879   // Sets a hidden property on this object. Returns this object if successful,
1880   // undefined if called on a detached proxy.
1881   static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1882                                           Handle<Name> key,
1883                                           Handle<Object> value);
1884   // Gets the value of a hidden property with the given key. Returns the hole
1885   // if the property doesn't exist (or if called on a detached proxy),
1886   // otherwise returns the value set for the key.
1887   Object* GetHiddenProperty(Handle<Name> key);
1888   // Deletes a hidden property. Deleting a non-existing property is
1889   // considered successful.
1890   static void DeleteHiddenProperty(Handle<JSObject> object,
1891                                    Handle<Name> key);
1892   // Returns true if the object has a property with the hidden string as name.
1893   static bool HasHiddenProperties(Handle<JSObject> object);
1894
1895   static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1896
1897   static inline void ValidateElements(Handle<JSObject> object);
1898
1899   // Makes sure that this object can contain HeapObject as elements.
1900   static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1901
1902   // Makes sure that this object can contain the specified elements.
1903   static inline void EnsureCanContainElements(
1904       Handle<JSObject> object,
1905       Object** elements,
1906       uint32_t count,
1907       EnsureElementsMode mode);
1908   static inline void EnsureCanContainElements(
1909       Handle<JSObject> object,
1910       Handle<FixedArrayBase> elements,
1911       uint32_t length,
1912       EnsureElementsMode mode);
1913   static void EnsureCanContainElements(
1914       Handle<JSObject> object,
1915       Arguments* arguments,
1916       uint32_t first_arg,
1917       uint32_t arg_count,
1918       EnsureElementsMode mode);
1919
1920   // Would we convert a fast elements array to dictionary mode given
1921   // an access at key?
1922   bool WouldConvertToSlowElements(Handle<Object> key);
1923   // Do we want to keep the elements in fast case when increasing the
1924   // capacity?
1925   bool ShouldConvertToSlowElements(int new_capacity);
1926   // Returns true if the backing storage for the slow-case elements of
1927   // this object takes up nearly as much space as a fast-case backing
1928   // storage would.  In that case the JSObject should have fast
1929   // elements.
1930   bool ShouldConvertToFastElements();
1931   // Returns true if the elements of JSObject contains only values that can be
1932   // represented in a FixedDoubleArray and has at least one value that can only
1933   // be represented as a double and not a Smi.
1934   bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1935
1936   // Computes the new capacity when expanding the elements of a JSObject.
1937   static int NewElementsCapacity(int old_capacity) {
1938     // (old_capacity + 50%) + 16
1939     return old_capacity + (old_capacity >> 1) + 16;
1940   }
1941
1942   // These methods do not perform access checks!
1943   MUST_USE_RESULT static MaybeHandle<AccessorPair> GetOwnElementAccessorPair(
1944       Handle<JSObject> object, uint32_t index);
1945
1946   MUST_USE_RESULT static MaybeHandle<Object> SetFastElement(
1947       Handle<JSObject> object, uint32_t index, Handle<Object> value,
1948       LanguageMode language_mode, bool check_prototype);
1949
1950   MUST_USE_RESULT static inline MaybeHandle<Object> SetOwnElement(
1951       Handle<JSObject> object, uint32_t index, Handle<Object> value,
1952       LanguageMode language_mode);
1953
1954   MUST_USE_RESULT static MaybeHandle<Object> SetOwnElement(
1955       Handle<JSObject> object, uint32_t index, Handle<Object> value,
1956       PropertyAttributes attributes, LanguageMode language_mode);
1957
1958   // Empty handle is returned if the element cannot be set to the given value.
1959   MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1960       Handle<JSObject> object, uint32_t index, Handle<Object> value,
1961       PropertyAttributes attributes, LanguageMode language_mode,
1962       bool check_prototype = true, SetPropertyMode set_mode = SET_PROPERTY);
1963
1964   // Returns the index'th element.
1965   // The undefined object if index is out of bounds.
1966   MUST_USE_RESULT static MaybeHandle<Object> GetElementWithInterceptor(
1967       Handle<JSObject> object, Handle<Object> receiver, uint32_t index,
1968       bool check_prototype);
1969
1970   enum SetFastElementsCapacitySmiMode {
1971     kAllowSmiElements,
1972     kForceSmiElements,
1973     kDontAllowSmiElements
1974   };
1975
1976   // Replace the elements' backing store with fast elements of the given
1977   // capacity.  Update the length for JSArrays.  Returns the new backing
1978   // store.
1979   static Handle<FixedArray> SetFastElementsCapacityAndLength(
1980       Handle<JSObject> object,
1981       int capacity,
1982       int length,
1983       SetFastElementsCapacitySmiMode smi_mode);
1984   static void SetFastDoubleElementsCapacityAndLength(
1985       Handle<JSObject> object,
1986       int capacity,
1987       int length);
1988
1989   // Lookup interceptors are used for handling properties controlled by host
1990   // objects.
1991   inline bool HasNamedInterceptor();
1992   inline bool HasIndexedInterceptor();
1993
1994   // Computes the enumerable keys from interceptors. Used for debug mirrors and
1995   // by JSReceiver::GetKeys.
1996   MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1997       Handle<JSObject> object,
1998       Handle<JSReceiver> receiver);
1999   MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2000       Handle<JSObject> object,
2001       Handle<JSReceiver> receiver);
2002
2003   // Support functions for v8 api (needed for correct interceptor behavior).
2004   MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2005       Handle<JSObject> object, Handle<Name> key);
2006   MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2007       Handle<JSObject> object, uint32_t index);
2008   MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2009       Handle<JSObject> object, Handle<Name> key);
2010
2011   // Get the header size for a JSObject.  Used to compute the index of
2012   // internal fields as well as the number of internal fields.
2013   inline int GetHeaderSize();
2014
2015   inline int GetInternalFieldCount();
2016   inline int GetInternalFieldOffset(int index);
2017   inline Object* GetInternalField(int index);
2018   inline void SetInternalField(int index, Object* value);
2019   inline void SetInternalField(int index, Smi* value);
2020
2021   // Returns the number of properties on this object filtering out properties
2022   // with the specified attributes (ignoring interceptors).
2023   int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2024   // Fill in details for properties into storage starting at the specified
2025   // index.
2026   void GetOwnPropertyNames(
2027       FixedArray* storage, int index, PropertyAttributes filter = NONE);
2028
2029   // Returns the number of properties on this object filtering out properties
2030   // with the specified attributes (ignoring interceptors).
2031   int NumberOfOwnElements(PropertyAttributes filter);
2032   // Returns the number of enumerable elements (ignoring interceptors).
2033   int NumberOfEnumElements();
2034   // Returns the number of elements on this object filtering out elements
2035   // with the specified attributes (ignoring interceptors).
2036   int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2037   // Count and fill in the enumerable elements into storage.
2038   // (storage->length() == NumberOfEnumElements()).
2039   // If storage is NULL, will count the elements without adding
2040   // them to any storage.
2041   // Returns the number of enumerable elements.
2042   int GetEnumElementKeys(FixedArray* storage);
2043
2044   // Returns a new map with all transitions dropped from the object's current
2045   // map and the ElementsKind set.
2046   static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2047                                               ElementsKind to_kind);
2048   static void TransitionElementsKind(Handle<JSObject> object,
2049                                      ElementsKind to_kind);
2050
2051   static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2052
2053   // Convert the object to use the canonical dictionary
2054   // representation. If the object is expected to have additional properties
2055   // added this number can be indicated to have the backing store allocated to
2056   // an initial capacity for holding these properties.
2057   static void NormalizeProperties(Handle<JSObject> object,
2058                                   PropertyNormalizationMode mode,
2059                                   int expected_additional_properties,
2060                                   const char* reason);
2061
2062   // Convert and update the elements backing store to be a
2063   // SeededNumberDictionary dictionary.  Returns the backing after conversion.
2064   static Handle<SeededNumberDictionary> NormalizeElements(
2065       Handle<JSObject> object);
2066
2067   // Transform slow named properties to fast variants.
2068   static void MigrateSlowToFast(Handle<JSObject> object,
2069                                 int unused_property_fields, const char* reason);
2070
2071   inline bool IsUnboxedDoubleField(FieldIndex index);
2072
2073   // Access fast-case object properties at index.
2074   static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2075                                        Representation representation,
2076                                        FieldIndex index);
2077   inline Object* RawFastPropertyAt(FieldIndex index);
2078   inline double RawFastDoublePropertyAt(FieldIndex index);
2079
2080   inline void FastPropertyAtPut(FieldIndex index, Object* value);
2081   inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2082   inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2083   void WriteToField(int descriptor, Object* value);
2084
2085   // Access to in object properties.
2086   inline int GetInObjectPropertyOffset(int index);
2087   inline Object* InObjectPropertyAt(int index);
2088   inline Object* InObjectPropertyAtPut(int index,
2089                                        Object* value,
2090                                        WriteBarrierMode mode
2091                                        = UPDATE_WRITE_BARRIER);
2092
2093   // Set the object's prototype (only JSReceiver and null are allowed values).
2094   MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2095       Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2096
2097   // Initializes the body after properties slot, properties slot is
2098   // initialized by set_properties.  Fill the pre-allocated fields with
2099   // pre_allocated_value and the rest with filler_value.
2100   // Note: this call does not update write barrier, the caller is responsible
2101   // to ensure that |filler_value| can be collected without WB here.
2102   inline void InitializeBody(Map* map,
2103                              Object* pre_allocated_value,
2104                              Object* filler_value);
2105
2106   // Check whether this object references another object
2107   bool ReferencesObject(Object* obj);
2108
2109   // Disalow further properties to be added to the object.
2110   MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2111       Handle<JSObject> object);
2112
2113   // ES5 Object.seal
2114   MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2115
2116   // ES5 Object.freeze
2117   MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2118
2119   // Called the first time an object is observed with ES7 Object.observe.
2120   static void SetObserved(Handle<JSObject> object);
2121
2122   // Copy object.
2123   enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2124
2125   static Handle<JSObject> Copy(Handle<JSObject> object);
2126   MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2127       Handle<JSObject> object,
2128       AllocationSiteUsageContext* site_context,
2129       DeepCopyHints hints = kNoHints);
2130   MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2131       Handle<JSObject> object,
2132       AllocationSiteCreationContext* site_context);
2133
2134   static Handle<Object> GetDataProperty(Handle<JSObject> object,
2135                                         Handle<Name> key);
2136   static Handle<Object> GetDataProperty(LookupIterator* it);
2137
2138   DECLARE_CAST(JSObject)
2139
2140   // Dispatched behavior.
2141   void JSObjectShortPrint(StringStream* accumulator);
2142   DECLARE_PRINTER(JSObject)
2143   DECLARE_VERIFIER(JSObject)
2144 #ifdef OBJECT_PRINT
2145   void PrintProperties(std::ostream& os);   // NOLINT
2146   void PrintElements(std::ostream& os);     // NOLINT
2147 #endif
2148 #if defined(DEBUG) || defined(OBJECT_PRINT)
2149   void PrintTransitions(std::ostream& os);  // NOLINT
2150 #endif
2151
2152   static void PrintElementsTransition(
2153       FILE* file, Handle<JSObject> object,
2154       ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2155       ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2156
2157   void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2158
2159 #ifdef DEBUG
2160   // Structure for collecting spill information about JSObjects.
2161   class SpillInformation {
2162    public:
2163     void Clear();
2164     void Print();
2165     int number_of_objects_;
2166     int number_of_objects_with_fast_properties_;
2167     int number_of_objects_with_fast_elements_;
2168     int number_of_fast_used_fields_;
2169     int number_of_fast_unused_fields_;
2170     int number_of_slow_used_properties_;
2171     int number_of_slow_unused_properties_;
2172     int number_of_fast_used_elements_;
2173     int number_of_fast_unused_elements_;
2174     int number_of_slow_used_elements_;
2175     int number_of_slow_unused_elements_;
2176   };
2177
2178   void IncrementSpillStatistics(SpillInformation* info);
2179 #endif
2180
2181 #ifdef VERIFY_HEAP
2182   // If a GC was caused while constructing this object, the elements pointer
2183   // may point to a one pointer filler map. The object won't be rooted, but
2184   // our heap verification code could stumble across it.
2185   bool ElementsAreSafeToExamine();
2186 #endif
2187
2188   Object* SlowReverseLookup(Object* value);
2189
2190   // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2191   // Also maximal value of JSArray's length property.
2192   static const uint32_t kMaxElementCount = 0xffffffffu;
2193
2194   // Constants for heuristics controlling conversion of fast elements
2195   // to slow elements.
2196
2197   // Maximal gap that can be introduced by adding an element beyond
2198   // the current elements length.
2199   static const uint32_t kMaxGap = 1024;
2200
2201   // Maximal length of fast elements array that won't be checked for
2202   // being dense enough on expansion.
2203   static const int kMaxUncheckedFastElementsLength = 5000;
2204
2205   // Same as above but for old arrays. This limit is more strict. We
2206   // don't want to be wasteful with long lived objects.
2207   static const int kMaxUncheckedOldFastElementsLength = 500;
2208
2209   // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2210   // permissible values (see the DCHECK in heap.cc).
2211   static const int kInitialMaxFastElementArray = 100000;
2212
2213   // This constant applies only to the initial map of "$Object" aka
2214   // "global.Object" and not to arbitrary other JSObject maps.
2215   static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2216
2217   static const int kMaxInstanceSize = 255 * kPointerSize;
2218   // When extending the backing storage for property values, we increase
2219   // its size by more than the 1 entry necessary, so sequentially adding fields
2220   // to the same object requires fewer allocations and copies.
2221   static const int kFieldsAdded = 3;
2222
2223   // Layout description.
2224   static const int kPropertiesOffset = HeapObject::kHeaderSize;
2225   static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2226   static const int kHeaderSize = kElementsOffset + kPointerSize;
2227
2228   STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2229
2230   class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2231    public:
2232     static inline int SizeOf(Map* map, HeapObject* object);
2233   };
2234
2235   Context* GetCreationContext();
2236
2237   // Enqueue change record for Object.observe. May cause GC.
2238   MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2239       Handle<JSObject> object, const char* type, Handle<Name> name,
2240       Handle<Object> old_value);
2241
2242  private:
2243   friend class DictionaryElementsAccessor;
2244   friend class JSReceiver;
2245   friend class Object;
2246
2247   static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2248   static void MigrateFastToSlow(Handle<JSObject> object,
2249                                 Handle<Map> new_map,
2250                                 int expected_additional_properties);
2251
2252   static void UpdateAllocationSite(Handle<JSObject> object,
2253                                    ElementsKind to_kind);
2254
2255   // Used from Object::GetProperty().
2256   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2257       LookupIterator* it);
2258
2259   MUST_USE_RESULT static MaybeHandle<Object> GetElementWithCallback(
2260       Handle<JSObject> object,
2261       Handle<Object> receiver,
2262       Handle<Object> structure,
2263       uint32_t index,
2264       Handle<Object> holder);
2265
2266   MUST_USE_RESULT static Maybe<PropertyAttributes>
2267       GetElementAttributeWithInterceptor(Handle<JSObject> object,
2268                                          Handle<JSReceiver> receiver,
2269                                          uint32_t index, bool continue_search);
2270
2271   // Queries indexed interceptor on an object for property attributes.
2272   //
2273   // We determine property attributes as follows:
2274   // - if interceptor has a query callback, then the  property attributes are
2275   //   the result of query callback for index.
2276   // - otherwise if interceptor has a getter callback and it returns
2277   //   non-empty value on index, then the property attributes is NONE
2278   //   (property is present, and it is enumerable, configurable, writable)
2279   // - otherwise there are no property attributes that can be inferred for
2280   //   interceptor, and this function returns ABSENT.
2281   MUST_USE_RESULT static Maybe<PropertyAttributes>
2282       GetElementAttributeFromInterceptor(Handle<JSObject> object,
2283                                          Handle<Object> receiver,
2284                                          uint32_t index);
2285
2286   MUST_USE_RESULT static Maybe<PropertyAttributes>
2287       GetElementAttributeWithoutInterceptor(Handle<JSObject> object,
2288                                             Handle<JSReceiver> receiver,
2289                                             uint32_t index,
2290                                             bool continue_search);
2291   MUST_USE_RESULT static MaybeHandle<Object> SetElementWithCallback(
2292       Handle<Object> object, Handle<Object> structure, uint32_t index,
2293       Handle<Object> value, Handle<JSObject> holder,
2294       LanguageMode language_mode);
2295   MUST_USE_RESULT static MaybeHandle<Object> SetElementWithInterceptor(
2296       Handle<JSObject> object, uint32_t index, Handle<Object> value,
2297       PropertyAttributes attributes, LanguageMode language_mode,
2298       bool check_prototype, SetPropertyMode set_mode);
2299   MUST_USE_RESULT static MaybeHandle<Object> SetElementWithoutInterceptor(
2300       Handle<JSObject> object, uint32_t index, Handle<Object> value,
2301       PropertyAttributes attributes, LanguageMode language_mode,
2302       bool check_prototype, SetPropertyMode set_mode);
2303   MUST_USE_RESULT
2304   static MaybeHandle<Object> SetElementWithCallbackSetterInPrototypes(
2305       Handle<JSObject> object, uint32_t index, Handle<Object> value,
2306       bool* found, LanguageMode language_mode);
2307   MUST_USE_RESULT static MaybeHandle<Object> SetDictionaryElement(
2308       Handle<JSObject> object, uint32_t index, Handle<Object> value,
2309       PropertyAttributes attributes, LanguageMode language_mode,
2310       bool check_prototype, SetPropertyMode set_mode = SET_PROPERTY);
2311   MUST_USE_RESULT static MaybeHandle<Object> SetFastDoubleElement(
2312       Handle<JSObject> object, uint32_t index, Handle<Object> value,
2313       LanguageMode language_mode, bool check_prototype = true);
2314   MUST_USE_RESULT static MaybeHandle<Object> GetElementWithFailedAccessCheck(
2315       Isolate* isolate, Handle<JSObject> object, Handle<Object> receiver,
2316       uint32_t index);
2317   MUST_USE_RESULT static Maybe<PropertyAttributes>
2318   GetElementAttributesWithFailedAccessCheck(Isolate* isolate,
2319                                             Handle<JSObject> object,
2320                                             Handle<Object> receiver,
2321                                             uint32_t index);
2322
2323   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2324       LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
2325
2326   // Add a property to a slow-case object.
2327   static void AddSlowProperty(Handle<JSObject> object,
2328                               Handle<Name> name,
2329                               Handle<Object> value,
2330                               PropertyAttributes attributes);
2331
2332   MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
2333       Handle<JSObject> object, Handle<Name> name, LanguageMode language_mode);
2334   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2335       Handle<JSObject> holder, Handle<JSObject> receiver, Handle<Name> name);
2336
2337   // Deletes an existing named property in a normalized object.
2338   static void DeleteNormalizedProperty(Handle<JSObject> object,
2339                                        Handle<Name> name);
2340
2341   MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
2342       Handle<JSObject> object, uint32_t index, LanguageMode language_mode);
2343   MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithInterceptor(
2344       Handle<JSObject> object,
2345       uint32_t index);
2346
2347   bool ReferencesObjectFromElements(FixedArray* elements,
2348                                     ElementsKind kind,
2349                                     Object* object);
2350
2351   // Returns true if most of the elements backing storage is used.
2352   bool HasDenseElements();
2353
2354   // Gets the current elements capacity and the number of used elements.
2355   void GetElementsCapacityAndUsage(int* capacity, int* used);
2356
2357   static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
2358   static void SetElementCallback(Handle<JSObject> object,
2359                                  uint32_t index,
2360                                  Handle<Object> structure,
2361                                  PropertyAttributes attributes);
2362   static void SetPropertyCallback(Handle<JSObject> object,
2363                                   Handle<Name> name,
2364                                   Handle<Object> structure,
2365                                   PropertyAttributes attributes);
2366   static void DefineElementAccessor(Handle<JSObject> object,
2367                                     uint32_t index,
2368                                     Handle<Object> getter,
2369                                     Handle<Object> setter,
2370                                     PropertyAttributes attributes);
2371
2372   // Return the hash table backing store or the inline stored identity hash,
2373   // whatever is found.
2374   MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2375
2376   // Return the hash table backing store for hidden properties.  If there is no
2377   // backing store, allocate one.
2378   static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2379       Handle<JSObject> object);
2380
2381   // Set the hidden property backing store to either a hash table or
2382   // the inline-stored identity hash.
2383   static Handle<Object> SetHiddenPropertiesHashTable(
2384       Handle<JSObject> object,
2385       Handle<Object> value);
2386
2387   MUST_USE_RESULT Object* GetIdentityHash();
2388
2389   static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2390
2391   static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2392       Handle<JSObject> object);
2393
2394   // Helper for fast versions of preventExtensions, seal, and freeze.
2395   // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2396   template <PropertyAttributes attrs>
2397   MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2398       Handle<JSObject> object);
2399
2400   DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2401 };
2402
2403
2404 // Common superclass for FixedArrays that allow implementations to share
2405 // common accessors and some code paths.
2406 class FixedArrayBase: public HeapObject {
2407  public:
2408   // [length]: length of the array.
2409   inline int length() const;
2410   inline void set_length(int value);
2411
2412   // Get and set the length using acquire loads and release stores.
2413   inline int synchronized_length() const;
2414   inline void synchronized_set_length(int value);
2415
2416   DECLARE_CAST(FixedArrayBase)
2417
2418   // Layout description.
2419   // Length is smi tagged when it is stored.
2420   static const int kLengthOffset = HeapObject::kHeaderSize;
2421   static const int kHeaderSize = kLengthOffset + kPointerSize;
2422 };
2423
2424
2425 class FixedDoubleArray;
2426 class IncrementalMarking;
2427
2428
2429 // FixedArray describes fixed-sized arrays with element type Object*.
2430 class FixedArray: public FixedArrayBase {
2431  public:
2432   // Setter and getter for elements.
2433   inline Object* get(int index) const;
2434   static inline Handle<Object> get(Handle<FixedArray> array, int index);
2435   // Setter that uses write barrier.
2436   inline void set(int index, Object* value);
2437   inline bool is_the_hole(int index);
2438
2439   // Setter that doesn't need write barrier.
2440   inline void set(int index, Smi* value);
2441   // Setter with explicit barrier mode.
2442   inline void set(int index, Object* value, WriteBarrierMode mode);
2443
2444   // Setters for frequently used oddballs located in old space.
2445   inline void set_undefined(int index);
2446   inline void set_null(int index);
2447   inline void set_the_hole(int index);
2448
2449   inline Object** GetFirstElementAddress();
2450   inline bool ContainsOnlySmisOrHoles();
2451
2452   // Gives access to raw memory which stores the array's data.
2453   inline Object** data_start();
2454
2455   inline void FillWithHoles(int from, int to);
2456
2457   // Shrink length and insert filler objects.
2458   void Shrink(int length);
2459
2460   // Copy operation.
2461   static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2462                                      int new_length,
2463                                      PretenureFlag pretenure = NOT_TENURED);
2464
2465   enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2466
2467   // Add the elements of a JSArray to this FixedArray.
2468   MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2469       Handle<FixedArray> content, Handle<JSObject> array,
2470       KeyFilter filter = ALL_KEYS);
2471
2472   // Computes the union of keys and return the result.
2473   // Used for implementing "for (n in object) { }"
2474   MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2475       Handle<FixedArray> first,
2476       Handle<FixedArray> second);
2477
2478   // Copy a sub array from the receiver to dest.
2479   void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2480
2481   // Garbage collection support.
2482   static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2483
2484   // Code Generation support.
2485   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2486
2487   // Garbage collection support.
2488   Object** RawFieldOfElementAt(int index) {
2489     return HeapObject::RawField(this, OffsetOfElementAt(index));
2490   }
2491
2492   DECLARE_CAST(FixedArray)
2493
2494   // Maximal allowed size, in bytes, of a single FixedArray.
2495   // Prevents overflowing size computations, as well as extreme memory
2496   // consumption.
2497   static const int kMaxSize = 128 * MB * kPointerSize;
2498   // Maximally allowed length of a FixedArray.
2499   static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2500
2501   // Dispatched behavior.
2502   DECLARE_PRINTER(FixedArray)
2503   DECLARE_VERIFIER(FixedArray)
2504 #ifdef DEBUG
2505   // Checks if two FixedArrays have identical contents.
2506   bool IsEqualTo(FixedArray* other);
2507 #endif
2508
2509   // Swap two elements in a pair of arrays.  If this array and the
2510   // numbers array are the same object, the elements are only swapped
2511   // once.
2512   void SwapPairs(FixedArray* numbers, int i, int j);
2513
2514   // Sort prefix of this array and the numbers array as pairs wrt. the
2515   // numbers.  If the numbers array and the this array are the same
2516   // object, the prefix of this array is sorted.
2517   void SortPairs(FixedArray* numbers, uint32_t len);
2518
2519   class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2520    public:
2521     static inline int SizeOf(Map* map, HeapObject* object) {
2522       return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2523     }
2524   };
2525
2526  protected:
2527   // Set operation on FixedArray without using write barriers. Can
2528   // only be used for storing old space objects or smis.
2529   static inline void NoWriteBarrierSet(FixedArray* array,
2530                                        int index,
2531                                        Object* value);
2532
2533   // Set operation on FixedArray without incremental write barrier. Can
2534   // only be used if the object is guaranteed to be white (whiteness witness
2535   // is present).
2536   static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2537                                                   int index,
2538                                                   Object* value);
2539
2540  private:
2541   STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2542
2543   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2544 };
2545
2546
2547 // FixedDoubleArray describes fixed-sized arrays with element type double.
2548 class FixedDoubleArray: public FixedArrayBase {
2549  public:
2550   // Setter and getter for elements.
2551   inline double get_scalar(int index);
2552   inline uint64_t get_representation(int index);
2553   static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2554   inline void set(int index, double value);
2555   inline void set_the_hole(int index);
2556
2557   // Checking for the hole.
2558   inline bool is_the_hole(int index);
2559
2560   // Garbage collection support.
2561   inline static int SizeFor(int length) {
2562     return kHeaderSize + length * kDoubleSize;
2563   }
2564
2565   // Gives access to raw memory which stores the array's data.
2566   inline double* data_start();
2567
2568   inline void FillWithHoles(int from, int to);
2569
2570   // Code Generation support.
2571   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2572
2573   DECLARE_CAST(FixedDoubleArray)
2574
2575   // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2576   // Prevents overflowing size computations, as well as extreme memory
2577   // consumption.
2578   static const int kMaxSize = 512 * MB;
2579   // Maximally allowed length of a FixedArray.
2580   static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2581
2582   // Dispatched behavior.
2583   DECLARE_PRINTER(FixedDoubleArray)
2584   DECLARE_VERIFIER(FixedDoubleArray)
2585
2586  private:
2587   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2588 };
2589
2590
2591 class WeakFixedArray : public FixedArray {
2592  public:
2593   enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2594
2595   // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2596   static Handle<WeakFixedArray> Add(
2597       Handle<Object> maybe_array, Handle<HeapObject> value,
2598       SearchForDuplicates search_for_duplicates = kAlwaysAdd);
2599
2600   void Remove(Handle<HeapObject> value);
2601
2602   inline Object* Get(int index) const;
2603   inline int Length() const;
2604
2605   DECLARE_CAST(WeakFixedArray)
2606
2607  private:
2608   static const int kLastUsedIndexIndex = 0;
2609   static const int kFirstIndex = 1;
2610
2611   static Handle<WeakFixedArray> Allocate(
2612       Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2613
2614   static void Set(Handle<WeakFixedArray> array, int index,
2615                   Handle<HeapObject> value);
2616   inline void clear(int index);
2617   inline bool IsEmptySlot(int index) const;
2618
2619   inline int last_used_index() const;
2620   inline void set_last_used_index(int index);
2621
2622   // Disallow inherited setters.
2623   void set(int index, Smi* value);
2624   void set(int index, Object* value);
2625   void set(int index, Object* value, WriteBarrierMode mode);
2626   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2627 };
2628
2629
2630 // ConstantPoolArray describes a fixed-sized array containing constant pool
2631 // entries.
2632 //
2633 // A ConstantPoolArray can be structured in two different ways depending upon
2634 // whether it is extended or small. The is_extended_layout() method can be used
2635 // to discover which layout the constant pool has.
2636 //
2637 // The format of a small constant pool is:
2638 //   [kSmallLayout1Offset]                    : Small section layout bitmap 1
2639 //   [kSmallLayout2Offset]                    : Small section layout bitmap 2
2640 //   [first_index(INT64, SMALL_SECTION)]      : 64 bit entries
2641 //    ...                                     :  ...
2642 //   [first_index(CODE_PTR, SMALL_SECTION)]   : code pointer entries
2643 //    ...                                     :  ...
2644 //   [first_index(HEAP_PTR, SMALL_SECTION)]   : heap pointer entries
2645 //    ...                                     :  ...
2646 //   [first_index(INT32, SMALL_SECTION)]      : 32 bit entries
2647 //    ...                                     :  ...
2648 //
2649 // If the constant pool has an extended layout, the extended section constant
2650 // pool also contains an extended section, which has the following format at
2651 // location get_extended_section_header_offset():
2652 //   [kExtendedInt64CountOffset]              : count of extended 64 bit entries
2653 //   [kExtendedCodePtrCountOffset]            : count of extended code pointers
2654 //   [kExtendedHeapPtrCountOffset]            : count of extended heap pointers
2655 //   [kExtendedInt32CountOffset]              : count of extended 32 bit entries
2656 //   [first_index(INT64, EXTENDED_SECTION)]   : 64 bit entries
2657 //    ...                                     :  ...
2658 //   [first_index(CODE_PTR, EXTENDED_SECTION)]: code pointer entries
2659 //    ...                                     :  ...
2660 //   [first_index(HEAP_PTR, EXTENDED_SECTION)]: heap pointer entries
2661 //    ...                                     :  ...
2662 //   [first_index(INT32, EXTENDED_SECTION)]   : 32 bit entries
2663 //    ...                                     :  ...
2664 //
2665 class ConstantPoolArray: public HeapObject {
2666  public:
2667   enum WeakObjectState { NO_WEAK_OBJECTS, WEAK_OBJECTS_IN_OPTIMIZED_CODE };
2668
2669   enum Type {
2670     INT64 = 0,
2671     CODE_PTR,
2672     HEAP_PTR,
2673     INT32,
2674     // Number of types stored by the ConstantPoolArrays.
2675     NUMBER_OF_TYPES,
2676     FIRST_TYPE = INT64,
2677     LAST_TYPE = INT32
2678   };
2679
2680   enum LayoutSection {
2681     SMALL_SECTION = 0,
2682     EXTENDED_SECTION,
2683     NUMBER_OF_LAYOUT_SECTIONS
2684   };
2685
2686   class NumberOfEntries BASE_EMBEDDED {
2687    public:
2688     inline NumberOfEntries() {
2689       for (int i = 0; i < NUMBER_OF_TYPES; i++) {
2690         element_counts_[i] = 0;
2691       }
2692     }
2693
2694     inline NumberOfEntries(int int64_count, int code_ptr_count,
2695                            int heap_ptr_count, int int32_count) {
2696       element_counts_[INT64] = int64_count;
2697       element_counts_[CODE_PTR] = code_ptr_count;
2698       element_counts_[HEAP_PTR] = heap_ptr_count;
2699       element_counts_[INT32] = int32_count;
2700     }
2701
2702     inline NumberOfEntries(ConstantPoolArray* array, LayoutSection section) {
2703       element_counts_[INT64] = array->number_of_entries(INT64, section);
2704       element_counts_[CODE_PTR] = array->number_of_entries(CODE_PTR, section);
2705       element_counts_[HEAP_PTR] = array->number_of_entries(HEAP_PTR, section);
2706       element_counts_[INT32] = array->number_of_entries(INT32, section);
2707     }
2708
2709     inline void increment(Type type);
2710     inline int equals(const NumberOfEntries& other) const;
2711     inline bool is_empty() const;
2712     inline int count_of(Type type) const;
2713     inline int base_of(Type type) const;
2714     inline int total_count() const;
2715     inline int are_in_range(int min, int max) const;
2716
2717    private:
2718     int element_counts_[NUMBER_OF_TYPES];
2719   };
2720
2721   class Iterator BASE_EMBEDDED {
2722    public:
2723     inline Iterator(ConstantPoolArray* array, Type type)
2724         : array_(array),
2725           type_(type),
2726           final_section_(array->final_section()),
2727           current_section_(SMALL_SECTION),
2728           next_index_(array->first_index(type, SMALL_SECTION)) {
2729       update_section();
2730     }
2731
2732     inline Iterator(ConstantPoolArray* array, Type type, LayoutSection section)
2733         : array_(array),
2734           type_(type),
2735           final_section_(section),
2736           current_section_(section),
2737           next_index_(array->first_index(type, section)) {
2738       update_section();
2739     }
2740
2741     inline int next_index();
2742     inline bool is_finished();
2743
2744    private:
2745     inline void update_section();
2746     ConstantPoolArray* array_;
2747     const Type type_;
2748     const LayoutSection final_section_;
2749
2750     LayoutSection current_section_;
2751     int next_index_;
2752   };
2753
2754   // Getters for the first index, the last index and the count of entries of
2755   // a given type for a given layout section.
2756   inline int first_index(Type type, LayoutSection layout_section);
2757   inline int last_index(Type type, LayoutSection layout_section);
2758   inline int number_of_entries(Type type, LayoutSection layout_section);
2759
2760   // Returns the type of the entry at the given index.
2761   inline Type get_type(int index);
2762   inline bool offset_is_type(int offset, Type type);
2763
2764   // Setter and getter for pool elements.
2765   inline Address get_code_ptr_entry(int index);
2766   inline Object* get_heap_ptr_entry(int index);
2767   inline int64_t get_int64_entry(int index);
2768   inline int32_t get_int32_entry(int index);
2769   inline double get_int64_entry_as_double(int index);
2770
2771   inline void set(int index, Address value);
2772   inline void set(int index, Object* value);
2773   inline void set(int index, int64_t value);
2774   inline void set(int index, double value);
2775   inline void set(int index, int32_t value);
2776
2777   // Setters which take a raw offset rather than an index (for code generation).
2778   inline void set_at_offset(int offset, int32_t value);
2779   inline void set_at_offset(int offset, int64_t value);
2780   inline void set_at_offset(int offset, double value);
2781   inline void set_at_offset(int offset, Address value);
2782   inline void set_at_offset(int offset, Object* value);
2783
2784   // Setter and getter for weak objects state
2785   inline void set_weak_object_state(WeakObjectState state);
2786   inline WeakObjectState get_weak_object_state();
2787
2788   // Returns true if the constant pool has an extended layout, false if it has
2789   // only the small layout.
2790   inline bool is_extended_layout();
2791
2792   // Returns the last LayoutSection in this constant pool array.
2793   inline LayoutSection final_section();
2794
2795   // Set up initial state for a small layout constant pool array.
2796   inline void Init(const NumberOfEntries& small);
2797
2798   // Set up initial state for an extended layout constant pool array.
2799   inline void InitExtended(const NumberOfEntries& small,
2800                            const NumberOfEntries& extended);
2801
2802   // Clears the pointer entries with GC safe values.
2803   void ClearPtrEntries(Isolate* isolate);
2804
2805   // returns the total number of entries in the constant pool array.
2806   inline int length();
2807
2808   // Garbage collection support.
2809   inline int size();
2810
2811
2812   inline static int MaxInt64Offset(int number_of_int64) {
2813     return kFirstEntryOffset + (number_of_int64 * kInt64Size);
2814   }
2815
2816   inline static int SizeFor(const NumberOfEntries& small) {
2817     int size = kFirstEntryOffset +
2818         (small.count_of(INT64)  * kInt64Size) +
2819         (small.count_of(CODE_PTR) * kPointerSize) +
2820         (small.count_of(HEAP_PTR) * kPointerSize) +
2821         (small.count_of(INT32) * kInt32Size);
2822     return RoundUp(size, kPointerSize);
2823   }
2824
2825   inline static int SizeForExtended(const NumberOfEntries& small,
2826                                     const NumberOfEntries& extended) {
2827     int size = SizeFor(small);
2828     size = RoundUp(size, kInt64Size);  // Align extended header to 64 bits.
2829     size += kExtendedFirstOffset +
2830         (extended.count_of(INT64) * kInt64Size) +
2831         (extended.count_of(CODE_PTR) * kPointerSize) +
2832         (extended.count_of(HEAP_PTR) * kPointerSize) +
2833         (extended.count_of(INT32) * kInt32Size);
2834     return RoundUp(size, kPointerSize);
2835   }
2836
2837   inline static int entry_size(Type type) {
2838     switch (type) {
2839       case INT32:
2840         return kInt32Size;
2841       case INT64:
2842         return kInt64Size;
2843       case CODE_PTR:
2844       case HEAP_PTR:
2845         return kPointerSize;
2846       default:
2847         UNREACHABLE();
2848         return 0;
2849     }
2850   }
2851
2852   // Code Generation support.
2853   inline int OffsetOfElementAt(int index) {
2854     int offset;
2855     LayoutSection section;
2856     if (is_extended_layout() && index >= first_extended_section_index()) {
2857       section = EXTENDED_SECTION;
2858       offset = get_extended_section_header_offset() + kExtendedFirstOffset;
2859     } else {
2860       section = SMALL_SECTION;
2861       offset = kFirstEntryOffset;
2862     }
2863
2864     // Add offsets for the preceding type sections.
2865     DCHECK(index <= last_index(LAST_TYPE, section));
2866     for (Type type = FIRST_TYPE; index > last_index(type, section);
2867          type = next_type(type)) {
2868       offset += entry_size(type) * number_of_entries(type, section);
2869     }
2870
2871     // Add offset for the index in it's type.
2872     Type type = get_type(index);
2873     offset += entry_size(type) * (index - first_index(type, section));
2874     return offset;
2875   }
2876
2877   DECLARE_CAST(ConstantPoolArray)
2878
2879   // Garbage collection support.
2880   Object** RawFieldOfElementAt(int index) {
2881     return HeapObject::RawField(this, OffsetOfElementAt(index));
2882   }
2883
2884   // Small Layout description.
2885   static const int kSmallLayout1Offset = HeapObject::kHeaderSize;
2886   static const int kSmallLayout2Offset = kSmallLayout1Offset + kInt32Size;
2887   static const int kHeaderSize = kSmallLayout2Offset + kInt32Size;
2888   static const int kFirstEntryOffset = ROUND_UP(kHeaderSize, kInt64Size);
2889
2890   static const int kSmallLayoutCountBits = 10;
2891   static const int kMaxSmallEntriesPerType = (1 << kSmallLayoutCountBits) - 1;
2892
2893   // Fields in kSmallLayout1Offset.
2894   class Int64CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2895   class CodePtrCountField: public BitField<int, 11, kSmallLayoutCountBits> {};
2896   class HeapPtrCountField: public BitField<int, 21, kSmallLayoutCountBits> {};
2897   class IsExtendedField: public BitField<bool, 31, 1> {};
2898
2899   // Fields in kSmallLayout2Offset.
2900   class Int32CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2901   class TotalCountField: public BitField<int, 11, 12> {};
2902   class WeakObjectStateField: public BitField<WeakObjectState, 23, 2> {};
2903
2904   // Extended layout description, which starts at
2905   // get_extended_section_header_offset().
2906   static const int kExtendedInt64CountOffset = 0;
2907   static const int kExtendedCodePtrCountOffset =
2908       kExtendedInt64CountOffset + kInt32Size;
2909   static const int kExtendedHeapPtrCountOffset =
2910       kExtendedCodePtrCountOffset + kInt32Size;
2911   static const int kExtendedInt32CountOffset =
2912       kExtendedHeapPtrCountOffset + kInt32Size;
2913   static const int kExtendedFirstOffset =
2914       kExtendedInt32CountOffset + kInt32Size;
2915
2916   // Dispatched behavior.
2917   void ConstantPoolIterateBody(ObjectVisitor* v);
2918
2919   DECLARE_PRINTER(ConstantPoolArray)
2920   DECLARE_VERIFIER(ConstantPoolArray)
2921
2922  private:
2923   inline int first_extended_section_index();
2924   inline int get_extended_section_header_offset();
2925
2926   inline static Type next_type(Type type) {
2927     DCHECK(type >= FIRST_TYPE && type < NUMBER_OF_TYPES);
2928     int type_int = static_cast<int>(type);
2929     return static_cast<Type>(++type_int);
2930   }
2931
2932   DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
2933 };
2934
2935
2936 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2937 // The format of the these objects is:
2938 //   [0]: Number of descriptors
2939 //   [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2940 //          [0]: pointer to fixed array with enum cache
2941 //          [1]: either Smi(0) or pointer to fixed array with indices
2942 //   [2]: first key
2943 //   [2 + number of descriptors * kDescriptorSize]: start of slack
2944 class DescriptorArray: public FixedArray {
2945  public:
2946   // Returns true for both shared empty_descriptor_array and for smis, which the
2947   // map uses to encode additional bit fields when the descriptor array is not
2948   // yet used.
2949   inline bool IsEmpty();
2950
2951   // Returns the number of descriptors in the array.
2952   int number_of_descriptors() {
2953     DCHECK(length() >= kFirstIndex || IsEmpty());
2954     int len = length();
2955     return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2956   }
2957
2958   int number_of_descriptors_storage() {
2959     int len = length();
2960     return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2961   }
2962
2963   int NumberOfSlackDescriptors() {
2964     return number_of_descriptors_storage() - number_of_descriptors();
2965   }
2966
2967   inline void SetNumberOfDescriptors(int number_of_descriptors);
2968   inline int number_of_entries() { return number_of_descriptors(); }
2969
2970   bool HasEnumCache() {
2971     return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2972   }
2973
2974   void CopyEnumCacheFrom(DescriptorArray* array) {
2975     set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2976   }
2977
2978   FixedArray* GetEnumCache() {
2979     DCHECK(HasEnumCache());
2980     FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2981     return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2982   }
2983
2984   bool HasEnumIndicesCache() {
2985     if (IsEmpty()) return false;
2986     Object* object = get(kEnumCacheIndex);
2987     if (object->IsSmi()) return false;
2988     FixedArray* bridge = FixedArray::cast(object);
2989     return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2990   }
2991
2992   FixedArray* GetEnumIndicesCache() {
2993     DCHECK(HasEnumIndicesCache());
2994     FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2995     return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2996   }
2997
2998   Object** GetEnumCacheSlot() {
2999     DCHECK(HasEnumCache());
3000     return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
3001                                 kEnumCacheOffset);
3002   }
3003
3004   void ClearEnumCache();
3005
3006   // Initialize or change the enum cache,
3007   // using the supplied storage for the small "bridge".
3008   void SetEnumCache(FixedArray* bridge_storage,
3009                     FixedArray* new_cache,
3010                     Object* new_index_cache);
3011
3012   bool CanHoldValue(int descriptor, Object* value);
3013
3014   // Accessors for fetching instance descriptor at descriptor number.
3015   inline Name* GetKey(int descriptor_number);
3016   inline Object** GetKeySlot(int descriptor_number);
3017   inline Object* GetValue(int descriptor_number);
3018   inline void SetValue(int descriptor_number, Object* value);
3019   inline Object** GetValueSlot(int descriptor_number);
3020   static inline int GetValueOffset(int descriptor_number);
3021   inline Object** GetDescriptorStartSlot(int descriptor_number);
3022   inline Object** GetDescriptorEndSlot(int descriptor_number);
3023   inline PropertyDetails GetDetails(int descriptor_number);
3024   inline PropertyType GetType(int descriptor_number);
3025   inline int GetFieldIndex(int descriptor_number);
3026   inline HeapType* GetFieldType(int descriptor_number);
3027   inline Object* GetConstant(int descriptor_number);
3028   inline Object* GetCallbacksObject(int descriptor_number);
3029   inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3030
3031   inline Name* GetSortedKey(int descriptor_number);
3032   inline int GetSortedKeyIndex(int descriptor_number);
3033   inline void SetSortedKey(int pointer, int descriptor_number);
3034   inline void SetRepresentation(int descriptor_number,
3035                                 Representation representation);
3036
3037   // Accessor for complete descriptor.
3038   inline void Get(int descriptor_number, Descriptor* desc);
3039   inline void Set(int descriptor_number, Descriptor* desc);
3040   void Replace(int descriptor_number, Descriptor* descriptor);
3041
3042   // Append automatically sets the enumeration index. This should only be used
3043   // to add descriptors in bulk at the end, followed by sorting the descriptor
3044   // array.
3045   inline void Append(Descriptor* desc);
3046
3047   static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
3048                                           int enumeration_index,
3049                                           int slack = 0);
3050
3051   static Handle<DescriptorArray> CopyUpToAddAttributes(
3052       Handle<DescriptorArray> desc,
3053       int enumeration_index,
3054       PropertyAttributes attributes,
3055       int slack = 0);
3056
3057   // Sort the instance descriptors by the hash codes of their keys.
3058   void Sort();
3059
3060   // Search the instance descriptors for given name.
3061   INLINE(int Search(Name* name, int number_of_own_descriptors));
3062
3063   // As the above, but uses DescriptorLookupCache and updates it when
3064   // necessary.
3065   INLINE(int SearchWithCache(Name* name, Map* map));
3066
3067   // Allocates a DescriptorArray, but returns the singleton
3068   // empty descriptor array object if number_of_descriptors is 0.
3069   static Handle<DescriptorArray> Allocate(Isolate* isolate,
3070                                           int number_of_descriptors,
3071                                           int slack = 0);
3072
3073   DECLARE_CAST(DescriptorArray)
3074
3075   // Constant for denoting key was not found.
3076   static const int kNotFound = -1;
3077
3078   static const int kDescriptorLengthIndex = 0;
3079   static const int kEnumCacheIndex = 1;
3080   static const int kFirstIndex = 2;
3081
3082   // The length of the "bridge" to the enum cache.
3083   static const int kEnumCacheBridgeLength = 2;
3084   static const int kEnumCacheBridgeCacheIndex = 0;
3085   static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3086
3087   // Layout description.
3088   static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3089   static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3090   static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3091
3092   // Layout description for the bridge array.
3093   static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3094
3095   // Layout of descriptor.
3096   static const int kDescriptorKey = 0;
3097   static const int kDescriptorDetails = 1;
3098   static const int kDescriptorValue = 2;
3099   static const int kDescriptorSize = 3;
3100
3101 #if defined(DEBUG) || defined(OBJECT_PRINT)
3102   // For our gdb macros, we should perhaps change these in the future.
3103   void Print();
3104
3105   // Print all the descriptors.
3106   void PrintDescriptors(std::ostream& os);  // NOLINT
3107 #endif
3108
3109 #ifdef DEBUG
3110   // Is the descriptor array sorted and without duplicates?
3111   bool IsSortedNoDuplicates(int valid_descriptors = -1);
3112
3113   // Is the descriptor array consistent with the back pointers in targets?
3114   bool IsConsistentWithBackPointers(Map* current_map);
3115
3116   // Are two DescriptorArrays equal?
3117   bool IsEqualTo(DescriptorArray* other);
3118 #endif
3119
3120   // Returns the fixed array length required to hold number_of_descriptors
3121   // descriptors.
3122   static int LengthFor(int number_of_descriptors) {
3123     return ToKeyIndex(number_of_descriptors);
3124   }
3125
3126  private:
3127   // WhitenessWitness is used to prove that a descriptor array is white
3128   // (unmarked), so incremental write barriers can be skipped because the
3129   // marking invariant cannot be broken and slots pointing into evacuation
3130   // candidates will be discovered when the object is scanned. A witness is
3131   // always stack-allocated right after creating an array. By allocating a
3132   // witness, incremental marking is globally disabled. The witness is then
3133   // passed along wherever needed to statically prove that the array is known to
3134   // be white.
3135   class WhitenessWitness {
3136    public:
3137     inline explicit WhitenessWitness(DescriptorArray* array);
3138     inline ~WhitenessWitness();
3139
3140    private:
3141     IncrementalMarking* marking_;
3142   };
3143
3144   // An entry in a DescriptorArray, represented as an (array, index) pair.
3145   class Entry {
3146    public:
3147     inline explicit Entry(DescriptorArray* descs, int index) :
3148         descs_(descs), index_(index) { }
3149
3150     inline PropertyType type() { return descs_->GetType(index_); }
3151     inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3152
3153    private:
3154     DescriptorArray* descs_;
3155     int index_;
3156   };
3157
3158   // Conversion from descriptor number to array indices.
3159   static int ToKeyIndex(int descriptor_number) {
3160     return kFirstIndex +
3161            (descriptor_number * kDescriptorSize) +
3162            kDescriptorKey;
3163   }
3164
3165   static int ToDetailsIndex(int descriptor_number) {
3166     return kFirstIndex +
3167            (descriptor_number * kDescriptorSize) +
3168            kDescriptorDetails;
3169   }
3170
3171   static int ToValueIndex(int descriptor_number) {
3172     return kFirstIndex +
3173            (descriptor_number * kDescriptorSize) +
3174            kDescriptorValue;
3175   }
3176
3177   // Transfer a complete descriptor from the src descriptor array to this
3178   // descriptor array.
3179   void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
3180
3181   inline void Set(int descriptor_number,
3182                   Descriptor* desc,
3183                   const WhitenessWitness&);
3184
3185   // Swap first and second descriptor.
3186   inline void SwapSortedKeys(int first, int second);
3187
3188   DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3189 };
3190
3191
3192 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3193
3194 template <SearchMode search_mode, typename T>
3195 inline int Search(T* array, Name* name, int valid_entries = 0,
3196                   int* out_insertion_index = NULL);
3197
3198
3199 // HashTable is a subclass of FixedArray that implements a hash table
3200 // that uses open addressing and quadratic probing.
3201 //
3202 // In order for the quadratic probing to work, elements that have not
3203 // yet been used and elements that have been deleted are
3204 // distinguished.  Probing continues when deleted elements are
3205 // encountered and stops when unused elements are encountered.
3206 //
3207 // - Elements with key == undefined have not been used yet.
3208 // - Elements with key == the_hole have been deleted.
3209 //
3210 // The hash table class is parameterized with a Shape and a Key.
3211 // Shape must be a class with the following interface:
3212 //   class ExampleShape {
3213 //    public:
3214 //      // Tells whether key matches other.
3215 //     static bool IsMatch(Key key, Object* other);
3216 //     // Returns the hash value for key.
3217 //     static uint32_t Hash(Key key);
3218 //     // Returns the hash value for object.
3219 //     static uint32_t HashForObject(Key key, Object* object);
3220 //     // Convert key to an object.
3221 //     static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
3222 //     // The prefix size indicates number of elements in the beginning
3223 //     // of the backing storage.
3224 //     static const int kPrefixSize = ..;
3225 //     // The Element size indicates number of elements per entry.
3226 //     static const int kEntrySize = ..;
3227 //   };
3228 // The prefix size indicates an amount of memory in the
3229 // beginning of the backing storage that can be used for non-element
3230 // information by subclasses.
3231
3232 template<typename Key>
3233 class BaseShape {
3234  public:
3235   static const bool UsesSeed = false;
3236   static uint32_t Hash(Key key) { return 0; }
3237   static uint32_t SeededHash(Key key, uint32_t seed) {
3238     DCHECK(UsesSeed);
3239     return Hash(key);
3240   }
3241   static uint32_t HashForObject(Key key, Object* object) { return 0; }
3242   static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3243     DCHECK(UsesSeed);
3244     return HashForObject(key, object);
3245   }
3246 };
3247
3248 template<typename Derived, typename Shape, typename Key>
3249 class HashTable: public FixedArray {
3250  public:
3251   // Wrapper methods
3252   inline uint32_t Hash(Key key) {
3253     if (Shape::UsesSeed) {
3254       return Shape::SeededHash(key, GetHeap()->HashSeed());
3255     } else {
3256       return Shape::Hash(key);
3257     }
3258   }
3259
3260   inline uint32_t HashForObject(Key key, Object* object) {
3261     if (Shape::UsesSeed) {
3262       return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3263     } else {
3264       return Shape::HashForObject(key, object);
3265     }
3266   }
3267
3268   // Returns the number of elements in the hash table.
3269   int NumberOfElements() {
3270     return Smi::cast(get(kNumberOfElementsIndex))->value();
3271   }
3272
3273   // Returns the number of deleted elements in the hash table.
3274   int NumberOfDeletedElements() {
3275     return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3276   }
3277
3278   // Returns the capacity of the hash table.
3279   int Capacity() {
3280     return Smi::cast(get(kCapacityIndex))->value();
3281   }
3282
3283   // ElementAdded should be called whenever an element is added to a
3284   // hash table.
3285   void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3286
3287   // ElementRemoved should be called whenever an element is removed from
3288   // a hash table.
3289   void ElementRemoved() {
3290     SetNumberOfElements(NumberOfElements() - 1);
3291     SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3292   }
3293   void ElementsRemoved(int n) {
3294     SetNumberOfElements(NumberOfElements() - n);
3295     SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3296   }
3297
3298   // Returns a new HashTable object.
3299   MUST_USE_RESULT static Handle<Derived> New(
3300       Isolate* isolate,
3301       int at_least_space_for,
3302       MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3303       PretenureFlag pretenure = NOT_TENURED);
3304
3305   // Computes the required capacity for a table holding the given
3306   // number of elements. May be more than HashTable::kMaxCapacity.
3307   static int ComputeCapacity(int at_least_space_for);
3308
3309   // Returns the key at entry.
3310   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3311
3312   // Tells whether k is a real key.  The hole and undefined are not allowed
3313   // as keys and can be used to indicate missing or deleted elements.
3314   bool IsKey(Object* k) {
3315     return !k->IsTheHole() && !k->IsUndefined();
3316   }
3317
3318   // Garbage collection support.
3319   void IteratePrefix(ObjectVisitor* visitor);
3320   void IterateElements(ObjectVisitor* visitor);
3321
3322   DECLARE_CAST(HashTable)
3323
3324   // Compute the probe offset (quadratic probing).
3325   INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3326     return (n + n * n) >> 1;
3327   }
3328
3329   static const int kNumberOfElementsIndex = 0;
3330   static const int kNumberOfDeletedElementsIndex = 1;
3331   static const int kCapacityIndex = 2;
3332   static const int kPrefixStartIndex = 3;
3333   static const int kElementsStartIndex =
3334       kPrefixStartIndex + Shape::kPrefixSize;
3335   static const int kEntrySize = Shape::kEntrySize;
3336   static const int kElementsStartOffset =
3337       kHeaderSize + kElementsStartIndex * kPointerSize;
3338   static const int kCapacityOffset =
3339       kHeaderSize + kCapacityIndex * kPointerSize;
3340
3341   // Constant used for denoting a absent entry.
3342   static const int kNotFound = -1;
3343
3344   // Maximal capacity of HashTable. Based on maximal length of underlying
3345   // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3346   // cannot overflow.
3347   static const int kMaxCapacity =
3348       (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3349
3350   // Find entry for key otherwise return kNotFound.
3351   inline int FindEntry(Key key);
3352   int FindEntry(Isolate* isolate, Key key);
3353
3354   // Rehashes the table in-place.
3355   void Rehash(Key key);
3356
3357  protected:
3358   friend class ObjectHashTable;
3359
3360   // Find the entry at which to insert element with the given key that
3361   // has the given hash value.
3362   uint32_t FindInsertionEntry(uint32_t hash);
3363
3364   // Returns the index for an entry (of the key)
3365   static inline int EntryToIndex(int entry) {
3366     return (entry * kEntrySize) + kElementsStartIndex;
3367   }
3368
3369   // Update the number of elements in the hash table.
3370   void SetNumberOfElements(int nof) {
3371     set(kNumberOfElementsIndex, Smi::FromInt(nof));
3372   }
3373
3374   // Update the number of deleted elements in the hash table.
3375   void SetNumberOfDeletedElements(int nod) {
3376     set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3377   }
3378
3379   // Sets the capacity of the hash table.
3380   void SetCapacity(int capacity) {
3381     // To scale a computed hash code to fit within the hash table, we
3382     // use bit-wise AND with a mask, so the capacity must be positive
3383     // and non-zero.
3384     DCHECK(capacity > 0);
3385     DCHECK(capacity <= kMaxCapacity);
3386     set(kCapacityIndex, Smi::FromInt(capacity));
3387   }
3388
3389
3390   // Returns probe entry.
3391   static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3392     DCHECK(base::bits::IsPowerOfTwo32(size));
3393     return (hash + GetProbeOffset(number)) & (size - 1);
3394   }
3395
3396   inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3397     return hash & (size - 1);
3398   }
3399
3400   inline static uint32_t NextProbe(
3401       uint32_t last, uint32_t number, uint32_t size) {
3402     return (last + number) & (size - 1);
3403   }
3404
3405   // Attempt to shrink hash table after removal of key.
3406   MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3407
3408   // Ensure enough space for n additional elements.
3409   MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3410       Handle<Derived> table,
3411       int n,
3412       Key key,
3413       PretenureFlag pretenure = NOT_TENURED);
3414
3415  private:
3416   // Returns _expected_ if one of entries given by the first _probe_ probes is
3417   // equal to  _expected_. Otherwise, returns the entry given by the probe
3418   // number _probe_.
3419   uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3420
3421   void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3422
3423   // Rehashes this hash-table into the new table.
3424   void Rehash(Handle<Derived> new_table, Key key);
3425 };
3426
3427
3428 // HashTableKey is an abstract superclass for virtual key behavior.
3429 class HashTableKey {
3430  public:
3431   // Returns whether the other object matches this key.
3432   virtual bool IsMatch(Object* other) = 0;
3433   // Returns the hash value for this key.
3434   virtual uint32_t Hash() = 0;
3435   // Returns the hash value for object.
3436   virtual uint32_t HashForObject(Object* key) = 0;
3437   // Returns the key object for storing into the hash table.
3438   MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3439   // Required.
3440   virtual ~HashTableKey() {}
3441 };
3442
3443
3444 class StringTableShape : public BaseShape<HashTableKey*> {
3445  public:
3446   static inline bool IsMatch(HashTableKey* key, Object* value) {
3447     return key->IsMatch(value);
3448   }
3449
3450   static inline uint32_t Hash(HashTableKey* key) {
3451     return key->Hash();
3452   }
3453
3454   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3455     return key->HashForObject(object);
3456   }
3457
3458   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3459
3460   static const int kPrefixSize = 0;
3461   static const int kEntrySize = 1;
3462 };
3463
3464 class SeqOneByteString;
3465
3466 // StringTable.
3467 //
3468 // No special elements in the prefix and the element size is 1
3469 // because only the string itself (the key) needs to be stored.
3470 class StringTable: public HashTable<StringTable,
3471                                     StringTableShape,
3472                                     HashTableKey*> {
3473  public:
3474   // Find string in the string table. If it is not there yet, it is
3475   // added. The return value is the string found.
3476   static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3477   static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3478
3479   // Tries to internalize given string and returns string handle on success
3480   // or an empty handle otherwise.
3481   MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3482       Isolate* isolate,
3483       Handle<String> string);
3484
3485   // Looks up a string that is equal to the given string and returns
3486   // string handle if it is found, or an empty handle otherwise.
3487   MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3488       Isolate* isolate,
3489       Handle<String> str);
3490   MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3491       Isolate* isolate,
3492       uint16_t c1,
3493       uint16_t c2);
3494
3495   static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3496
3497   DECLARE_CAST(StringTable)
3498
3499  private:
3500   template <bool seq_one_byte>
3501   friend class JsonParser;
3502
3503   DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3504 };
3505
3506
3507 template <typename Derived, typename Shape, typename Key>
3508 class Dictionary: public HashTable<Derived, Shape, Key> {
3509  protected:
3510   typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3511
3512  public:
3513   // Returns the value at entry.
3514   Object* ValueAt(int entry) {
3515     return this->get(DerivedHashTable::EntryToIndex(entry) + 1);
3516   }
3517
3518   // Set the value for entry.
3519   void ValueAtPut(int entry, Object* value) {
3520     this->set(DerivedHashTable::EntryToIndex(entry) + 1, value);
3521   }
3522
3523   // Returns the property details for the property at entry.
3524   PropertyDetails DetailsAt(int entry) {
3525     DCHECK(entry >= 0);  // Not found is -1, which is not caught by get().
3526     return PropertyDetails(
3527         Smi::cast(this->get(DerivedHashTable::EntryToIndex(entry) + 2)));
3528   }
3529
3530   // Set the details for entry.
3531   void DetailsAtPut(int entry, PropertyDetails value) {
3532     this->set(DerivedHashTable::EntryToIndex(entry) + 2, value.AsSmi());
3533   }
3534
3535   // Sorting support
3536   void CopyValuesTo(FixedArray* elements);
3537
3538   // Delete a property from the dictionary.
3539   static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3540
3541   // Attempt to shrink the dictionary after deletion of key.
3542   MUST_USE_RESULT static inline Handle<Derived> Shrink(
3543       Handle<Derived> dictionary,
3544       Key key) {
3545     return DerivedHashTable::Shrink(dictionary, key);
3546   }
3547
3548   // Returns the number of elements in the dictionary filtering out properties
3549   // with the specified attributes.
3550   int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3551
3552   // Returns the number of enumerable elements in the dictionary.
3553   int NumberOfEnumElements();
3554
3555   // Returns true if the dictionary contains any elements that are non-writable,
3556   // non-configurable, non-enumerable, or have getters/setters.
3557   bool HasComplexElements();
3558
3559   enum SortMode { UNSORTED, SORTED };
3560   // Copies keys to preallocated fixed array.
3561   void CopyKeysTo(FixedArray* storage,
3562                   PropertyAttributes filter,
3563                   SortMode sort_mode);
3564   // Fill in details for properties into storage.
3565   void CopyKeysTo(FixedArray* storage,
3566                   int index,
3567                   PropertyAttributes filter,
3568                   SortMode sort_mode);
3569
3570   // Accessors for next enumeration index.
3571   void SetNextEnumerationIndex(int index) {
3572     DCHECK(index != 0);
3573     this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3574   }
3575
3576   int NextEnumerationIndex() {
3577     return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3578   }
3579
3580   // Creates a new dictionary.
3581   MUST_USE_RESULT static Handle<Derived> New(
3582       Isolate* isolate,
3583       int at_least_space_for,
3584       PretenureFlag pretenure = NOT_TENURED);
3585
3586   // Ensure enough space for n additional elements.
3587   static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3588
3589 #ifdef OBJECT_PRINT
3590   void Print(std::ostream& os);  // NOLINT
3591 #endif
3592   // Returns the key (slow).
3593   Object* SlowReverseLookup(Object* value);
3594
3595   // Sets the entry to (key, value) pair.
3596   inline void SetEntry(int entry,
3597                        Handle<Object> key,
3598                        Handle<Object> value);
3599   inline void SetEntry(int entry,
3600                        Handle<Object> key,
3601                        Handle<Object> value,
3602                        PropertyDetails details);
3603
3604   MUST_USE_RESULT static Handle<Derived> Add(
3605       Handle<Derived> dictionary,
3606       Key key,
3607       Handle<Object> value,
3608       PropertyDetails details);
3609
3610   // Returns iteration indices array for the |dictionary|.
3611   // Values are direct indices in the |HashTable| array.
3612   static Handle<FixedArray> BuildIterationIndicesArray(
3613       Handle<Derived> dictionary);
3614
3615  protected:
3616   // Generic at put operation.
3617   MUST_USE_RESULT static Handle<Derived> AtPut(
3618       Handle<Derived> dictionary,
3619       Key key,
3620       Handle<Object> value);
3621
3622   // Add entry to dictionary.
3623   static void AddEntry(
3624       Handle<Derived> dictionary,
3625       Key key,
3626       Handle<Object> value,
3627       PropertyDetails details,
3628       uint32_t hash);
3629
3630   // Generate new enumeration indices to avoid enumeration index overflow.
3631   // Returns iteration indices array for the |dictionary|.
3632   static Handle<FixedArray> GenerateNewEnumerationIndices(
3633       Handle<Derived> dictionary);
3634   static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3635   static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3636 };
3637
3638
3639 class NameDictionaryShape : public BaseShape<Handle<Name> > {
3640  public:
3641   static inline bool IsMatch(Handle<Name> key, Object* other);
3642   static inline uint32_t Hash(Handle<Name> key);
3643   static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3644   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3645   static const int kPrefixSize = 2;
3646   static const int kEntrySize = 3;
3647   static const bool kIsEnumerable = true;
3648 };
3649
3650
3651 class NameDictionary: public Dictionary<NameDictionary,
3652                                         NameDictionaryShape,
3653                                         Handle<Name> > {
3654   typedef Dictionary<
3655       NameDictionary, NameDictionaryShape, Handle<Name> > DerivedDictionary;
3656
3657  public:
3658   DECLARE_CAST(NameDictionary)
3659
3660   // Copies enumerable keys to preallocated fixed array.
3661   void CopyEnumKeysTo(FixedArray* storage);
3662   inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3663       Handle<NameDictionary> dictionary);
3664
3665   // Find entry for key, otherwise return kNotFound. Optimized version of
3666   // HashTable::FindEntry.
3667   int FindEntry(Handle<Name> key);
3668 };
3669
3670
3671 class NumberDictionaryShape : public BaseShape<uint32_t> {
3672  public:
3673   static inline bool IsMatch(uint32_t key, Object* other);
3674   static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3675   static const int kEntrySize = 3;
3676   static const bool kIsEnumerable = false;
3677 };
3678
3679
3680 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3681  public:
3682   static const bool UsesSeed = true;
3683   static const int kPrefixSize = 2;
3684
3685   static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3686   static inline uint32_t SeededHashForObject(uint32_t key,
3687                                              uint32_t seed,
3688                                              Object* object);
3689 };
3690
3691
3692 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3693  public:
3694   static const int kPrefixSize = 0;
3695
3696   static inline uint32_t Hash(uint32_t key);
3697   static inline uint32_t HashForObject(uint32_t key, Object* object);
3698 };
3699
3700
3701 class SeededNumberDictionary
3702     : public Dictionary<SeededNumberDictionary,
3703                         SeededNumberDictionaryShape,
3704                         uint32_t> {
3705  public:
3706   DECLARE_CAST(SeededNumberDictionary)
3707
3708   // Type specific at put (default NONE attributes is used when adding).
3709   MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3710       Handle<SeededNumberDictionary> dictionary,
3711       uint32_t key,
3712       Handle<Object> value);
3713   MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3714       Handle<SeededNumberDictionary> dictionary,
3715       uint32_t key,
3716       Handle<Object> value,
3717       PropertyDetails details);
3718
3719   // Set an existing entry or add a new one if needed.
3720   // Return the updated dictionary.
3721   MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3722       Handle<SeededNumberDictionary> dictionary,
3723       uint32_t key,
3724       Handle<Object> value,
3725       PropertyDetails details);
3726
3727   void UpdateMaxNumberKey(uint32_t key);
3728
3729   // If slow elements are required we will never go back to fast-case
3730   // for the elements kept in this dictionary.  We require slow
3731   // elements if an element has been added at an index larger than
3732   // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3733   // when defining a getter or setter with a number key.
3734   inline bool requires_slow_elements();
3735   inline void set_requires_slow_elements();
3736
3737   // Get the value of the max number key that has been added to this
3738   // dictionary.  max_number_key can only be called if
3739   // requires_slow_elements returns false.
3740   inline uint32_t max_number_key();
3741
3742   // Bit masks.
3743   static const int kRequiresSlowElementsMask = 1;
3744   static const int kRequiresSlowElementsTagSize = 1;
3745   static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3746 };
3747
3748
3749 class UnseededNumberDictionary
3750     : public Dictionary<UnseededNumberDictionary,
3751                         UnseededNumberDictionaryShape,
3752                         uint32_t> {
3753  public:
3754   DECLARE_CAST(UnseededNumberDictionary)
3755
3756   // Type specific at put (default NONE attributes is used when adding).
3757   MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3758       Handle<UnseededNumberDictionary> dictionary,
3759       uint32_t key,
3760       Handle<Object> value);
3761   MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3762       Handle<UnseededNumberDictionary> dictionary,
3763       uint32_t key,
3764       Handle<Object> value);
3765
3766   // Set an existing entry or add a new one if needed.
3767   // Return the updated dictionary.
3768   MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3769       Handle<UnseededNumberDictionary> dictionary,
3770       uint32_t key,
3771       Handle<Object> value);
3772 };
3773
3774
3775 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3776  public:
3777   static inline bool IsMatch(Handle<Object> key, Object* other);
3778   static inline uint32_t Hash(Handle<Object> key);
3779   static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3780   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3781   static const int kPrefixSize = 0;
3782   static const int kEntrySize = 2;
3783 };
3784
3785
3786 // ObjectHashTable maps keys that are arbitrary objects to object values by
3787 // using the identity hash of the key for hashing purposes.
3788 class ObjectHashTable: public HashTable<ObjectHashTable,
3789                                         ObjectHashTableShape,
3790                                         Handle<Object> > {
3791   typedef HashTable<
3792       ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3793  public:
3794   DECLARE_CAST(ObjectHashTable)
3795
3796   // Attempt to shrink hash table after removal of key.
3797   MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3798       Handle<ObjectHashTable> table,
3799       Handle<Object> key);
3800
3801   // Looks up the value associated with the given key. The hole value is
3802   // returned in case the key is not present.
3803   Object* Lookup(Handle<Object> key);
3804
3805   // Adds (or overwrites) the value associated with the given key.
3806   static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3807                                      Handle<Object> key,
3808                                      Handle<Object> value);
3809
3810   // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3811   static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3812                                         Handle<Object> key,
3813                                         bool* was_present);
3814
3815  private:
3816   friend class MarkCompactCollector;
3817
3818   void AddEntry(int entry, Object* key, Object* value);
3819   void RemoveEntry(int entry);
3820
3821   // Returns the index to the value of an entry.
3822   static inline int EntryToValueIndex(int entry) {
3823     return EntryToIndex(entry) + 1;
3824   }
3825 };
3826
3827
3828 // OrderedHashTable is a HashTable with Object keys that preserves
3829 // insertion order. There are Map and Set interfaces (OrderedHashMap
3830 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3831 //
3832 // Only Object* keys are supported, with Object::SameValueZero() used as the
3833 // equality operator and Object::GetHash() for the hash function.
3834 //
3835 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3836 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3837 // Originally attributed to Tyler Close.
3838 //
3839 // Memory layout:
3840 //   [0]: bucket count
3841 //   [1]: element count
3842 //   [2]: deleted element count
3843 //   [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3844 //                            offset into the data table (see below) where the
3845 //                            first item in this bucket is stored.
3846 //   [3 + NumberOfBuckets()..length]: "data table", an array of length
3847 //                            Capacity() * kEntrySize, where the first entrysize
3848 //                            items are handled by the derived class and the
3849 //                            item at kChainOffset is another entry into the
3850 //                            data table indicating the next entry in this hash
3851 //                            bucket.
3852 //
3853 // When we transition the table to a new version we obsolete it and reuse parts
3854 // of the memory to store information how to transition an iterator to the new
3855 // table:
3856 //
3857 // Memory layout for obsolete table:
3858 //   [0]: bucket count
3859 //   [1]: Next newer table
3860 //   [2]: Number of removed holes or -1 when the table was cleared.
3861 //   [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3862 //   [3 + NumberOfRemovedHoles()..length]: Not used
3863 //
3864 template<class Derived, class Iterator, int entrysize>
3865 class OrderedHashTable: public FixedArray {
3866  public:
3867   // Returns an OrderedHashTable with a capacity of at least |capacity|.
3868   static Handle<Derived> Allocate(
3869       Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3870
3871   // Returns an OrderedHashTable (possibly |table|) with enough space
3872   // to add at least one new element.
3873   static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3874
3875   // Returns an OrderedHashTable (possibly |table|) that's shrunken
3876   // if possible.
3877   static Handle<Derived> Shrink(Handle<Derived> table);
3878
3879   // Returns a new empty OrderedHashTable and records the clearing so that
3880   // exisiting iterators can be updated.
3881   static Handle<Derived> Clear(Handle<Derived> table);
3882
3883   // Returns an OrderedHashTable (possibly |table|) where |key| has been
3884   // removed.
3885   static Handle<Derived> Remove(Handle<Derived> table, Handle<Object> key,
3886       bool* was_present);
3887
3888   // Returns kNotFound if the key isn't present.
3889   int FindEntry(Handle<Object> key, int hash);
3890
3891   // Like the above, but doesn't require the caller to provide a hash.
3892   int FindEntry(Handle<Object> key);
3893
3894   int NumberOfElements() {
3895     return Smi::cast(get(kNumberOfElementsIndex))->value();
3896   }
3897
3898   int NumberOfDeletedElements() {
3899     return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3900   }
3901
3902   int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3903
3904   int NumberOfBuckets() {
3905     return Smi::cast(get(kNumberOfBucketsIndex))->value();
3906   }
3907
3908   // Returns the index into the data table where the new entry
3909   // should be placed. The table is assumed to have enough space
3910   // for a new entry.
3911   int AddEntry(int hash);
3912
3913   // Removes the entry, and puts the_hole in entrysize pointers
3914   // (leaving the hash table chain intact).
3915   void RemoveEntry(int entry);
3916
3917   // Returns an index into |this| for the given entry.
3918   int EntryToIndex(int entry) {
3919     return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3920   }
3921
3922   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3923
3924   bool IsObsolete() {
3925     return !get(kNextTableIndex)->IsSmi();
3926   }
3927
3928   // The next newer table. This is only valid if the table is obsolete.
3929   Derived* NextTable() {
3930     return Derived::cast(get(kNextTableIndex));
3931   }
3932
3933   // When the table is obsolete we store the indexes of the removed holes.
3934   int RemovedIndexAt(int index) {
3935     return Smi::cast(get(kRemovedHolesIndex + index))->value();
3936   }
3937
3938   static const int kNotFound = -1;
3939   static const int kMinCapacity = 4;
3940
3941   static const int kNumberOfBucketsIndex = 0;
3942   static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3943   static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3944   static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3945   static const int kNextTableIndex = kNumberOfElementsIndex;
3946
3947   static const int kNumberOfBucketsOffset =
3948       kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3949   static const int kNumberOfElementsOffset =
3950       kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3951   static const int kNumberOfDeletedElementsOffset =
3952       kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3953   static const int kHashTableStartOffset =
3954       kHeaderSize + kHashTableStartIndex * kPointerSize;
3955   static const int kNextTableOffset =
3956       kHeaderSize + kNextTableIndex * kPointerSize;
3957
3958   static const int kEntrySize = entrysize + 1;
3959   static const int kChainOffset = entrysize;
3960
3961   static const int kLoadFactor = 2;
3962
3963   // NumberOfDeletedElements is set to kClearedTableSentinel when
3964   // the table is cleared, which allows iterator transitions to
3965   // optimize that case.
3966   static const int kClearedTableSentinel = -1;
3967
3968  private:
3969   static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3970
3971   void SetNumberOfBuckets(int num) {
3972     set(kNumberOfBucketsIndex, Smi::FromInt(num));
3973   }
3974
3975   void SetNumberOfElements(int num) {
3976     set(kNumberOfElementsIndex, Smi::FromInt(num));
3977   }
3978
3979   void SetNumberOfDeletedElements(int num) {
3980     set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3981   }
3982
3983   int Capacity() {
3984     return NumberOfBuckets() * kLoadFactor;
3985   }
3986
3987   // Returns the next entry for the given entry.
3988   int ChainAt(int entry) {
3989     return Smi::cast(get(EntryToIndex(entry) + kChainOffset))->value();
3990   }
3991
3992   int HashToBucket(int hash) {
3993     return hash & (NumberOfBuckets() - 1);
3994   }
3995
3996   int HashToEntry(int hash) {
3997     int bucket = HashToBucket(hash);
3998     return Smi::cast(get(kHashTableStartIndex + bucket))->value();
3999   }
4000
4001   void SetNextTable(Derived* next_table) {
4002     set(kNextTableIndex, next_table);
4003   }
4004
4005   void SetRemovedIndexAt(int index, int removed_index) {
4006     return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
4007   }
4008
4009   static const int kRemovedHolesIndex = kHashTableStartIndex;
4010
4011   static const int kMaxCapacity =
4012       (FixedArray::kMaxLength - kHashTableStartIndex)
4013       / (1 + (kEntrySize * kLoadFactor));
4014 };
4015
4016
4017 class JSSetIterator;
4018
4019
4020 class OrderedHashSet: public OrderedHashTable<
4021     OrderedHashSet, JSSetIterator, 1> {
4022  public:
4023   DECLARE_CAST(OrderedHashSet)
4024
4025   bool Contains(Handle<Object> key);
4026   static Handle<OrderedHashSet> Add(
4027       Handle<OrderedHashSet> table, Handle<Object> key);
4028 };
4029
4030
4031 class JSMapIterator;
4032
4033
4034 class OrderedHashMap:public OrderedHashTable<
4035     OrderedHashMap, JSMapIterator, 2> {
4036  public:
4037   DECLARE_CAST(OrderedHashMap)
4038
4039   Object* Lookup(Handle<Object> key);
4040   static Handle<OrderedHashMap> Put(
4041       Handle<OrderedHashMap> table,
4042       Handle<Object> key,
4043       Handle<Object> value);
4044
4045   Object* ValueAt(int entry) {
4046     return get(EntryToIndex(entry) + kValueOffset);
4047   }
4048
4049   static const int kValueOffset = 1;
4050 };
4051
4052
4053 template <int entrysize>
4054 class WeakHashTableShape : public BaseShape<Handle<Object> > {
4055  public:
4056   static inline bool IsMatch(Handle<Object> key, Object* other);
4057   static inline uint32_t Hash(Handle<Object> key);
4058   static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4059   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4060   static const int kPrefixSize = 0;
4061   static const int kEntrySize = entrysize;
4062 };
4063
4064
4065 // WeakHashTable maps keys that are arbitrary heap objects to heap object
4066 // values. The table wraps the keys in weak cells and store values directly.
4067 // Thus it references keys weakly and values strongly.
4068 class WeakHashTable: public HashTable<WeakHashTable,
4069                                       WeakHashTableShape<2>,
4070                                       Handle<Object> > {
4071   typedef HashTable<
4072       WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
4073  public:
4074   DECLARE_CAST(WeakHashTable)
4075
4076   // Looks up the value associated with the given key. The hole value is
4077   // returned in case the key is not present.
4078   Object* Lookup(Handle<HeapObject> key);
4079
4080   // Adds (or overwrites) the value associated with the given key. Mapping a
4081   // key to the hole value causes removal of the whole entry.
4082   MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
4083                                                    Handle<HeapObject> key,
4084                                                    Handle<HeapObject> value);
4085
4086  private:
4087   friend class MarkCompactCollector;
4088
4089   void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
4090
4091   // Returns the index to the value of an entry.
4092   static inline int EntryToValueIndex(int entry) {
4093     return EntryToIndex(entry) + 1;
4094   }
4095 };
4096
4097
4098 // JSFunctionResultCache caches results of some JSFunction invocation.
4099 // It is a fixed array with fixed structure:
4100 //   [0]: factory function
4101 //   [1]: finger index
4102 //   [2]: current cache size
4103 //   [3]: dummy field.
4104 // The rest of array are key/value pairs.
4105 class JSFunctionResultCache: public FixedArray {
4106  public:
4107   static const int kFactoryIndex = 0;
4108   static const int kFingerIndex = kFactoryIndex + 1;
4109   static const int kCacheSizeIndex = kFingerIndex + 1;
4110   static const int kDummyIndex = kCacheSizeIndex + 1;
4111   static const int kEntriesIndex = kDummyIndex + 1;
4112
4113   static const int kEntrySize = 2;  // key + value
4114
4115   static const int kFactoryOffset = kHeaderSize;
4116   static const int kFingerOffset = kFactoryOffset + kPointerSize;
4117   static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4118
4119   inline void MakeZeroSize();
4120   inline void Clear();
4121
4122   inline int size();
4123   inline void set_size(int size);
4124   inline int finger_index();
4125   inline void set_finger_index(int finger_index);
4126
4127   DECLARE_CAST(JSFunctionResultCache)
4128
4129   DECLARE_VERIFIER(JSFunctionResultCache)
4130 };
4131
4132
4133 // ScopeInfo represents information about different scopes of a source
4134 // program  and the allocation of the scope's variables. Scope information
4135 // is stored in a compressed form in ScopeInfo objects and is used
4136 // at runtime (stack dumps, deoptimization, etc.).
4137
4138 // This object provides quick access to scope info details for runtime
4139 // routines.
4140 class ScopeInfo : public FixedArray {
4141  public:
4142   DECLARE_CAST(ScopeInfo)
4143
4144   // Return the type of this scope.
4145   ScopeType scope_type();
4146
4147   // Does this scope call eval?
4148   bool CallsEval();
4149
4150   // Return the language mode of this scope.
4151   LanguageMode language_mode();
4152
4153   // Does this scope make a sloppy eval call?
4154   bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
4155
4156   // Return the total number of locals allocated on the stack and in the
4157   // context. This includes the parameters that are allocated in the context.
4158   int LocalCount();
4159
4160   // Return the number of stack slots for code. This number consists of two
4161   // parts:
4162   //  1. One stack slot per stack allocated local.
4163   //  2. One stack slot for the function name if it is stack allocated.
4164   int StackSlotCount();
4165
4166   // Return the number of context slots for code if a context is allocated. This
4167   // number consists of three parts:
4168   //  1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4169   //  2. One context slot per context allocated local.
4170   //  3. One context slot for the function name if it is context allocated.
4171   // Parameters allocated in the context count as context allocated locals. If
4172   // no contexts are allocated for this scope ContextLength returns 0.
4173   int ContextLength();
4174
4175   // Is this scope the scope of a named function expression?
4176   bool HasFunctionName();
4177
4178   // Return if this has context allocated locals.
4179   bool HasHeapAllocatedLocals();
4180
4181   // Return if contexts are allocated for this scope.
4182   bool HasContext();
4183
4184   // Return if this is a function scope with "use asm".
4185   bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
4186
4187   // Return if this is a nested function within an asm module scope.
4188   bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
4189
4190   bool IsSimpleParameterList() {
4191     return IsSimpleParameterListField::decode(Flags());
4192   }
4193
4194   // Return the function_name if present.
4195   String* FunctionName();
4196
4197   // Return the name of the given parameter.
4198   String* ParameterName(int var);
4199
4200   // Return the name of the given local.
4201   String* LocalName(int var);
4202
4203   // Return the name of the given stack local.
4204   String* StackLocalName(int var);
4205
4206   // Return the name of the given context local.
4207   String* ContextLocalName(int var);
4208
4209   // Return the mode of the given context local.
4210   VariableMode ContextLocalMode(int var);
4211
4212   // Return the initialization flag of the given context local.
4213   InitializationFlag ContextLocalInitFlag(int var);
4214
4215   // Return the initialization flag of the given context local.
4216   MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
4217
4218   // Return true if this local was introduced by the compiler, and should not be
4219   // exposed to the user in a debugger.
4220   bool LocalIsSynthetic(int var);
4221
4222   // Lookup support for serialized scope info. Returns the
4223   // the stack slot index for a given slot name if the slot is
4224   // present; otherwise returns a value < 0. The name must be an internalized
4225   // string.
4226   int StackSlotIndex(String* name);
4227
4228   // Lookup support for serialized scope info. Returns the
4229   // context slot index for a given slot name if the slot is present; otherwise
4230   // returns a value < 0. The name must be an internalized string.
4231   // If the slot is present and mode != NULL, sets *mode to the corresponding
4232   // mode for that variable.
4233   static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4234                               VariableMode* mode, InitializationFlag* init_flag,
4235                               MaybeAssignedFlag* maybe_assigned_flag);
4236
4237   // Lookup support for serialized scope info. Returns the
4238   // parameter index for a given parameter name if the parameter is present;
4239   // otherwise returns a value < 0. The name must be an internalized string.
4240   int ParameterIndex(String* name);
4241
4242   // Lookup support for serialized scope info. Returns the function context
4243   // slot index if the function name is present and context-allocated (named
4244   // function expressions, only), otherwise returns a value < 0. The name
4245   // must be an internalized string.
4246   int FunctionContextSlotIndex(String* name, VariableMode* mode);
4247
4248
4249   // Copies all the context locals into an object used to materialize a scope.
4250   static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4251                                              Handle<Context> context,
4252                                              Handle<JSObject> scope_object);
4253
4254
4255   static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4256
4257   // Serializes empty scope info.
4258   static ScopeInfo* Empty(Isolate* isolate);
4259
4260 #ifdef DEBUG
4261   void Print();
4262 #endif
4263
4264   // The layout of the static part of a ScopeInfo is as follows. Each entry is
4265   // numeric and occupies one array slot.
4266   // 1. A set of properties of the scope
4267   // 2. The number of parameters. This only applies to function scopes. For
4268   //    non-function scopes this is 0.
4269   // 3. The number of non-parameter variables allocated on the stack.
4270   // 4. The number of non-parameter and parameter variables allocated in the
4271   //    context.
4272 #define FOR_EACH_NUMERIC_FIELD(V)          \
4273   V(Flags)                                 \
4274   V(ParameterCount)                        \
4275   V(StackLocalCount)                       \
4276   V(ContextLocalCount)
4277
4278 #define FIELD_ACCESSORS(name)                            \
4279   void Set##name(int value) {                            \
4280     set(k##name, Smi::FromInt(value));                   \
4281   }                                                      \
4282   int name() {                                           \
4283     if (length() > 0) {                                  \
4284       return Smi::cast(get(k##name))->value();           \
4285     } else {                                             \
4286       return 0;                                          \
4287     }                                                    \
4288   }
4289   FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4290 #undef FIELD_ACCESSORS
4291
4292  private:
4293   enum {
4294 #define DECL_INDEX(name) k##name,
4295   FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4296 #undef DECL_INDEX
4297 #undef FOR_EACH_NUMERIC_FIELD
4298     kVariablePartIndex
4299   };
4300
4301   // The layout of the variable part of a ScopeInfo is as follows:
4302   // 1. ParameterEntries:
4303   //    This part stores the names of the parameters for function scopes. One
4304   //    slot is used per parameter, so in total this part occupies
4305   //    ParameterCount() slots in the array. For other scopes than function
4306   //    scopes ParameterCount() is 0.
4307   // 2. StackLocalEntries:
4308   //    Contains the names of local variables that are allocated on the stack,
4309   //    in increasing order of the stack slot index. One slot is used per stack
4310   //    local, so in total this part occupies StackLocalCount() slots in the
4311   //    array.
4312   // 3. ContextLocalNameEntries:
4313   //    Contains the names of local variables and parameters that are allocated
4314   //    in the context. They are stored in increasing order of the context slot
4315   //    index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4316   //    context local, so in total this part occupies ContextLocalCount() slots
4317   //    in the array.
4318   // 4. ContextLocalInfoEntries:
4319   //    Contains the variable modes and initialization flags corresponding to
4320   //    the context locals in ContextLocalNameEntries. One slot is used per
4321   //    context local, so in total this part occupies ContextLocalCount()
4322   //    slots in the array.
4323   // 5. FunctionNameEntryIndex:
4324   //    If the scope belongs to a named function expression this part contains
4325   //    information about the function variable. It always occupies two array
4326   //    slots:  a. The name of the function variable.
4327   //            b. The context or stack slot index for the variable.
4328   int ParameterEntriesIndex();
4329   int StackLocalEntriesIndex();
4330   int ContextLocalNameEntriesIndex();
4331   int ContextLocalInfoEntriesIndex();
4332   int FunctionNameEntryIndex();
4333
4334   // Location of the function variable for named function expressions.
4335   enum FunctionVariableInfo {
4336     NONE,     // No function name present.
4337     STACK,    // Function
4338     CONTEXT,
4339     UNUSED
4340   };
4341
4342   // Properties of scopes.
4343   class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4344   class CallsEvalField : public BitField<bool, 4, 1> {};
4345   STATIC_ASSERT(LANGUAGE_END == 3);
4346   class LanguageModeField : public BitField<LanguageMode, 5, 2> {};
4347   class FunctionVariableField : public BitField<FunctionVariableInfo, 7, 2> {};
4348   class FunctionVariableMode : public BitField<VariableMode, 9, 3> {};
4349   class AsmModuleField : public BitField<bool, 12, 1> {};
4350   class AsmFunctionField : public BitField<bool, 13, 1> {};
4351   class IsSimpleParameterListField
4352       : public BitField<bool, AsmFunctionField::kNext, 1> {};
4353
4354   // BitFields representing the encoded information for context locals in the
4355   // ContextLocalInfoEntries part.
4356   class ContextLocalMode:      public BitField<VariableMode,         0, 3> {};
4357   class ContextLocalInitFlag:  public BitField<InitializationFlag,   3, 1> {};
4358   class ContextLocalMaybeAssignedFlag
4359       : public BitField<MaybeAssignedFlag, 4, 1> {};
4360 };
4361
4362
4363 // The cache for maps used by normalized (dictionary mode) objects.
4364 // Such maps do not have property descriptors, so a typical program
4365 // needs very limited number of distinct normalized maps.
4366 class NormalizedMapCache: public FixedArray {
4367  public:
4368   static Handle<NormalizedMapCache> New(Isolate* isolate);
4369
4370   MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4371                                        PropertyNormalizationMode mode);
4372   void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4373
4374   void Clear();
4375
4376   DECLARE_CAST(NormalizedMapCache)
4377
4378   static inline bool IsNormalizedMapCache(const Object* obj);
4379
4380   DECLARE_VERIFIER(NormalizedMapCache)
4381  private:
4382   static const int kEntries = 64;
4383
4384   static inline int GetIndex(Handle<Map> map);
4385
4386   // The following declarations hide base class methods.
4387   Object* get(int index);
4388   void set(int index, Object* value);
4389 };
4390
4391
4392 // ByteArray represents fixed sized byte arrays.  Used for the relocation info
4393 // that is attached to code objects.
4394 class ByteArray: public FixedArrayBase {
4395  public:
4396   inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4397
4398   // Setter and getter.
4399   inline byte get(int index);
4400   inline void set(int index, byte value);
4401
4402   // Treat contents as an int array.
4403   inline int get_int(int index);
4404
4405   static int SizeFor(int length) {
4406     return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4407   }
4408   // We use byte arrays for free blocks in the heap.  Given a desired size in
4409   // bytes that is a multiple of the word size and big enough to hold a byte
4410   // array, this function returns the number of elements a byte array should
4411   // have.
4412   static int LengthFor(int size_in_bytes) {
4413     DCHECK(IsAligned(size_in_bytes, kPointerSize));
4414     DCHECK(size_in_bytes >= kHeaderSize);
4415     return size_in_bytes - kHeaderSize;
4416   }
4417
4418   // Returns data start address.
4419   inline Address GetDataStartAddress();
4420
4421   // Returns a pointer to the ByteArray object for a given data start address.
4422   static inline ByteArray* FromDataStartAddress(Address address);
4423
4424   DECLARE_CAST(ByteArray)
4425
4426   // Dispatched behavior.
4427   inline int ByteArraySize() {
4428     return SizeFor(this->length());
4429   }
4430   DECLARE_PRINTER(ByteArray)
4431   DECLARE_VERIFIER(ByteArray)
4432
4433   // Layout description.
4434   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4435
4436   // Maximal memory consumption for a single ByteArray.
4437   static const int kMaxSize = 512 * MB;
4438   // Maximal length of a single ByteArray.
4439   static const int kMaxLength = kMaxSize - kHeaderSize;
4440
4441  private:
4442   DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4443 };
4444
4445
4446 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4447 // They look like heap objects (are heap object tagged and have a map) so that
4448 // the heap remains iterable.  They have a size and a next pointer.
4449 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4450 // in the free list.
4451 class FreeSpace: public HeapObject {
4452  public:
4453   // [size]: size of the free space including the header.
4454   inline int size() const;
4455   inline void set_size(int value);
4456
4457   inline int nobarrier_size() const;
4458   inline void nobarrier_set_size(int value);
4459
4460   inline int Size() { return size(); }
4461
4462   // Accessors for the next field.
4463   inline FreeSpace* next();
4464   inline FreeSpace** next_address();
4465   inline void set_next(FreeSpace* next);
4466
4467   inline static FreeSpace* cast(HeapObject* obj);
4468
4469   // Dispatched behavior.
4470   DECLARE_PRINTER(FreeSpace)
4471   DECLARE_VERIFIER(FreeSpace)
4472
4473   // Layout description.
4474   // Size is smi tagged when it is stored.
4475   static const int kSizeOffset = HeapObject::kHeaderSize;
4476   static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4477
4478  private:
4479   DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4480 };
4481
4482
4483 // V has parameters (Type, type, TYPE, C type, element_size)
4484 #define TYPED_ARRAYS(V) \
4485   V(Uint8, uint8, UINT8, uint8_t, 1)                                           \
4486   V(Int8, int8, INT8, int8_t, 1)                                               \
4487   V(Uint16, uint16, UINT16, uint16_t, 2)                                       \
4488   V(Int16, int16, INT16, int16_t, 2)                                           \
4489   V(Uint32, uint32, UINT32, uint32_t, 4)                                       \
4490   V(Int32, int32, INT32, int32_t, 4)                                           \
4491   V(Float32, float32, FLOAT32, float, 4)                                       \
4492   V(Float64, float64, FLOAT64, double, 8)                                      \
4493   V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4494
4495
4496
4497 // An ExternalArray represents a fixed-size array of primitive values
4498 // which live outside the JavaScript heap. Its subclasses are used to
4499 // implement the CanvasArray types being defined in the WebGL
4500 // specification. As of this writing the first public draft is not yet
4501 // available, but Khronos members can access the draft at:
4502 //   https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4503 //
4504 // The semantics of these arrays differ from CanvasPixelArray.
4505 // Out-of-range values passed to the setter are converted via a C
4506 // cast, not clamping. Out-of-range indices cause exceptions to be
4507 // raised rather than being silently ignored.
4508 class ExternalArray: public FixedArrayBase {
4509  public:
4510   inline bool is_the_hole(int index) { return false; }
4511
4512   // [external_pointer]: The pointer to the external memory area backing this
4513   // external array.
4514   DECL_ACCESSORS(external_pointer, void)  // Pointer to the data store.
4515
4516   DECLARE_CAST(ExternalArray)
4517
4518   // Maximal acceptable length for an external array.
4519   static const int kMaxLength = 0x3fffffff;
4520
4521   // ExternalArray headers are not quadword aligned.
4522   static const int kExternalPointerOffset =
4523       POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4524   static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4525   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4526
4527  private:
4528   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4529 };
4530
4531
4532 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4533 // semantics used for implementing the CanvasPixelArray object. Please see the
4534 // specification at:
4535
4536 // http://www.whatwg.org/specs/web-apps/current-work/
4537 //                      multipage/the-canvas-element.html#canvaspixelarray
4538 // In particular, write access clamps the value written to 0 or 255 if the
4539 // value written is outside this range.
4540 class ExternalUint8ClampedArray: public ExternalArray {
4541  public:
4542   inline uint8_t* external_uint8_clamped_pointer();
4543
4544   // Setter and getter.
4545   inline uint8_t get_scalar(int index);
4546   static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4547                                    int index);
4548   inline void set(int index, uint8_t value);
4549
4550   // This accessor applies the correct conversion from Smi, HeapNumber
4551   // and undefined and clamps the converted value between 0 and 255.
4552   static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4553                                  uint32_t index,
4554                                  Handle<Object> value);
4555
4556   DECLARE_CAST(ExternalUint8ClampedArray)
4557
4558   // Dispatched behavior.
4559   DECLARE_PRINTER(ExternalUint8ClampedArray)
4560   DECLARE_VERIFIER(ExternalUint8ClampedArray)
4561
4562  private:
4563   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4564 };
4565
4566
4567 class ExternalInt8Array: public ExternalArray {
4568  public:
4569   // Setter and getter.
4570   inline int8_t get_scalar(int index);
4571   static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4572   inline void set(int index, int8_t value);
4573
4574   // This accessor applies the correct conversion from Smi, HeapNumber
4575   // and undefined.
4576   static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4577                                  uint32_t index,
4578                                  Handle<Object> value);
4579
4580   DECLARE_CAST(ExternalInt8Array)
4581
4582   // Dispatched behavior.
4583   DECLARE_PRINTER(ExternalInt8Array)
4584   DECLARE_VERIFIER(ExternalInt8Array)
4585
4586  private:
4587   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4588 };
4589
4590
4591 class ExternalUint8Array: public ExternalArray {
4592  public:
4593   // Setter and getter.
4594   inline uint8_t get_scalar(int index);
4595   static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4596   inline void set(int index, uint8_t value);
4597
4598   // This accessor applies the correct conversion from Smi, HeapNumber
4599   // and undefined.
4600   static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4601                                  uint32_t index,
4602                                  Handle<Object> value);
4603
4604   DECLARE_CAST(ExternalUint8Array)
4605
4606   // Dispatched behavior.
4607   DECLARE_PRINTER(ExternalUint8Array)
4608   DECLARE_VERIFIER(ExternalUint8Array)
4609
4610  private:
4611   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4612 };
4613
4614
4615 class ExternalInt16Array: public ExternalArray {
4616  public:
4617   // Setter and getter.
4618   inline int16_t get_scalar(int index);
4619   static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4620   inline void set(int index, int16_t value);
4621
4622   // This accessor applies the correct conversion from Smi, HeapNumber
4623   // and undefined.
4624   static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4625                                  uint32_t index,
4626                                  Handle<Object> value);
4627
4628   DECLARE_CAST(ExternalInt16Array)
4629
4630   // Dispatched behavior.
4631   DECLARE_PRINTER(ExternalInt16Array)
4632   DECLARE_VERIFIER(ExternalInt16Array)
4633
4634  private:
4635   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4636 };
4637
4638
4639 class ExternalUint16Array: public ExternalArray {
4640  public:
4641   // Setter and getter.
4642   inline uint16_t get_scalar(int index);
4643   static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4644                                    int index);
4645   inline void set(int index, uint16_t value);
4646
4647   // This accessor applies the correct conversion from Smi, HeapNumber
4648   // and undefined.
4649   static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4650                                  uint32_t index,
4651                                  Handle<Object> value);
4652
4653   DECLARE_CAST(ExternalUint16Array)
4654
4655   // Dispatched behavior.
4656   DECLARE_PRINTER(ExternalUint16Array)
4657   DECLARE_VERIFIER(ExternalUint16Array)
4658
4659  private:
4660   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4661 };
4662
4663
4664 class ExternalInt32Array: public ExternalArray {
4665  public:
4666   // Setter and getter.
4667   inline int32_t get_scalar(int index);
4668   static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4669   inline void set(int index, int32_t value);
4670
4671   // This accessor applies the correct conversion from Smi, HeapNumber
4672   // and undefined.
4673   static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4674                                  uint32_t index,
4675                                  Handle<Object> value);
4676
4677   DECLARE_CAST(ExternalInt32Array)
4678
4679   // Dispatched behavior.
4680   DECLARE_PRINTER(ExternalInt32Array)
4681   DECLARE_VERIFIER(ExternalInt32Array)
4682
4683  private:
4684   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4685 };
4686
4687
4688 class ExternalUint32Array: public ExternalArray {
4689  public:
4690   // Setter and getter.
4691   inline uint32_t get_scalar(int index);
4692   static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4693                                    int index);
4694   inline void set(int index, uint32_t value);
4695
4696   // This accessor applies the correct conversion from Smi, HeapNumber
4697   // and undefined.
4698   static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
4699                                  uint32_t index,
4700                                  Handle<Object> value);
4701
4702   DECLARE_CAST(ExternalUint32Array)
4703
4704   // Dispatched behavior.
4705   DECLARE_PRINTER(ExternalUint32Array)
4706   DECLARE_VERIFIER(ExternalUint32Array)
4707
4708  private:
4709   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4710 };
4711
4712
4713 class ExternalFloat32Array: public ExternalArray {
4714  public:
4715   // Setter and getter.
4716   inline float get_scalar(int index);
4717   static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4718                                    int index);
4719   inline void set(int index, float value);
4720
4721   // This accessor applies the correct conversion from Smi, HeapNumber
4722   // and undefined.
4723   static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
4724                                  uint32_t index,
4725                                  Handle<Object> value);
4726
4727   DECLARE_CAST(ExternalFloat32Array)
4728
4729   // Dispatched behavior.
4730   DECLARE_PRINTER(ExternalFloat32Array)
4731   DECLARE_VERIFIER(ExternalFloat32Array)
4732
4733  private:
4734   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4735 };
4736
4737
4738 class ExternalFloat64Array: public ExternalArray {
4739  public:
4740   // Setter and getter.
4741   inline double get_scalar(int index);
4742   static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4743                                    int index);
4744   inline void set(int index, double value);
4745
4746   // This accessor applies the correct conversion from Smi, HeapNumber
4747   // and undefined.
4748   static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
4749                                  uint32_t index,
4750                                  Handle<Object> value);
4751
4752   DECLARE_CAST(ExternalFloat64Array)
4753
4754   // Dispatched behavior.
4755   DECLARE_PRINTER(ExternalFloat64Array)
4756   DECLARE_VERIFIER(ExternalFloat64Array)
4757
4758  private:
4759   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4760 };
4761
4762
4763 class FixedTypedArrayBase: public FixedArrayBase {
4764  public:
4765   DECLARE_CAST(FixedTypedArrayBase)
4766
4767   static const int kDataOffset = kHeaderSize;
4768
4769   inline int size();
4770
4771   inline int TypedArraySize(InstanceType type);
4772
4773   // Use with care: returns raw pointer into heap.
4774   inline void* DataPtr();
4775
4776   inline int DataSize();
4777
4778  private:
4779   inline int DataSize(InstanceType type);
4780
4781   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4782 };
4783
4784
4785 template <class Traits>
4786 class FixedTypedArray: public FixedTypedArrayBase {
4787  public:
4788   typedef typename Traits::ElementType ElementType;
4789   static const InstanceType kInstanceType = Traits::kInstanceType;
4790
4791   DECLARE_CAST(FixedTypedArray<Traits>)
4792
4793   static inline int ElementOffset(int index) {
4794     return kDataOffset + index * sizeof(ElementType);
4795   }
4796
4797   static inline int SizeFor(int length) {
4798     return ElementOffset(length);
4799   }
4800
4801   inline ElementType get_scalar(int index);
4802   static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4803   inline void set(int index, ElementType value);
4804
4805   static inline ElementType from_int(int value);
4806   static inline ElementType from_double(double value);
4807
4808   // This accessor applies the correct conversion from Smi, HeapNumber
4809   // and undefined.
4810   static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
4811                                  uint32_t index,
4812                                  Handle<Object> value);
4813
4814   DECLARE_PRINTER(FixedTypedArray)
4815   DECLARE_VERIFIER(FixedTypedArray)
4816
4817  private:
4818   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4819 };
4820
4821 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size)         \
4822   class Type##ArrayTraits {                                                   \
4823    public:   /* NOLINT */                                                     \
4824     typedef elementType ElementType;                                          \
4825     static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE;      \
4826     static const char* Designator() { return #type " array"; }                \
4827     static inline Handle<Object> ToHandle(Isolate* isolate,                   \
4828                                           elementType scalar);                \
4829     static inline elementType defaultValue();                                 \
4830   };                                                                          \
4831                                                                               \
4832   typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4833
4834 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4835
4836 #undef FIXED_TYPED_ARRAY_TRAITS
4837
4838
4839 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4840 // data for code generated by the Hydrogen/Lithium compiler.  It also
4841 // contains information about functions that were inlined.  If N different
4842 // functions were inlined then first N elements of the literal array will
4843 // contain these functions.
4844 //
4845 // It can be empty.
4846 class DeoptimizationInputData: public FixedArray {
4847  public:
4848   // Layout description.  Indices in the array.
4849   static const int kTranslationByteArrayIndex = 0;
4850   static const int kInlinedFunctionCountIndex = 1;
4851   static const int kLiteralArrayIndex = 2;
4852   static const int kOsrAstIdIndex = 3;
4853   static const int kOsrPcOffsetIndex = 4;
4854   static const int kOptimizationIdIndex = 5;
4855   static const int kSharedFunctionInfoIndex = 6;
4856   static const int kWeakCellCacheIndex = 7;
4857   static const int kFirstDeoptEntryIndex = 8;
4858
4859   // Offsets of deopt entry elements relative to the start of the entry.
4860   static const int kAstIdRawOffset = 0;
4861   static const int kTranslationIndexOffset = 1;
4862   static const int kArgumentsStackHeightOffset = 2;
4863   static const int kPcOffset = 3;
4864   static const int kDeoptEntrySize = 4;
4865
4866   // Simple element accessors.
4867 #define DEFINE_ELEMENT_ACCESSORS(name, type)      \
4868   type* name() {                                  \
4869     return type::cast(get(k##name##Index));       \
4870   }                                               \
4871   void Set##name(type* value) {                   \
4872     set(k##name##Index, value);                   \
4873   }
4874
4875   DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4876   DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4877   DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4878   DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4879   DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4880   DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4881   DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4882   DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4883
4884 #undef DEFINE_ELEMENT_ACCESSORS
4885
4886   // Accessors for elements of the ith deoptimization entry.
4887 #define DEFINE_ENTRY_ACCESSORS(name, type)                      \
4888   type* name(int i) {                                           \
4889     return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4890   }                                                             \
4891   void Set##name(int i, type* value) {                          \
4892     set(IndexForEntry(i) + k##name##Offset, value);             \
4893   }
4894
4895   DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4896   DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4897   DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4898   DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4899
4900 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4901
4902   BailoutId AstId(int i) {
4903     return BailoutId(AstIdRaw(i)->value());
4904   }
4905
4906   void SetAstId(int i, BailoutId value) {
4907     SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4908   }
4909
4910   int DeoptCount() {
4911     return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4912   }
4913
4914   // Allocates a DeoptimizationInputData.
4915   static Handle<DeoptimizationInputData> New(Isolate* isolate,
4916                                              int deopt_entry_count,
4917                                              PretenureFlag pretenure);
4918
4919   DECLARE_CAST(DeoptimizationInputData)
4920
4921 #ifdef ENABLE_DISASSEMBLER
4922   void DeoptimizationInputDataPrint(std::ostream& os);  // NOLINT
4923 #endif
4924
4925  private:
4926   static int IndexForEntry(int i) {
4927     return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4928   }
4929
4930
4931   static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4932 };
4933
4934
4935 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4936 // data for code generated by the full compiler.
4937 // The format of the these objects is
4938 //   [i * 2]: Ast ID for ith deoptimization.
4939 //   [i * 2 + 1]: PC and state of ith deoptimization
4940 class DeoptimizationOutputData: public FixedArray {
4941  public:
4942   int DeoptPoints() { return length() / 2; }
4943
4944   BailoutId AstId(int index) {
4945     return BailoutId(Smi::cast(get(index * 2))->value());
4946   }
4947
4948   void SetAstId(int index, BailoutId id) {
4949     set(index * 2, Smi::FromInt(id.ToInt()));
4950   }
4951
4952   Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4953   void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4954
4955   static int LengthOfFixedArray(int deopt_points) {
4956     return deopt_points * 2;
4957   }
4958
4959   // Allocates a DeoptimizationOutputData.
4960   static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4961                                               int number_of_deopt_points,
4962                                               PretenureFlag pretenure);
4963
4964   DECLARE_CAST(DeoptimizationOutputData)
4965
4966 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4967   void DeoptimizationOutputDataPrint(std::ostream& os);  // NOLINT
4968 #endif
4969 };
4970
4971
4972 // Forward declaration.
4973 class Cell;
4974 class PropertyCell;
4975 class SafepointEntry;
4976 class TypeFeedbackInfo;
4977
4978 // Code describes objects with on-the-fly generated machine code.
4979 class Code: public HeapObject {
4980  public:
4981   // Opaque data type for encapsulating code flags like kind, inline
4982   // cache state, and arguments count.
4983   typedef uint32_t Flags;
4984
4985 #define NON_IC_KIND_LIST(V) \
4986   V(FUNCTION)               \
4987   V(OPTIMIZED_FUNCTION)     \
4988   V(STUB)                   \
4989   V(HANDLER)                \
4990   V(BUILTIN)                \
4991   V(REGEXP)
4992
4993 #define IC_KIND_LIST(V) \
4994   V(LOAD_IC)            \
4995   V(KEYED_LOAD_IC)      \
4996   V(CALL_IC)            \
4997   V(STORE_IC)           \
4998   V(KEYED_STORE_IC)     \
4999   V(BINARY_OP_IC)       \
5000   V(COMPARE_IC)         \
5001   V(COMPARE_NIL_IC)     \
5002   V(TO_BOOLEAN_IC)
5003
5004 #define CODE_KIND_LIST(V) \
5005   NON_IC_KIND_LIST(V)     \
5006   IC_KIND_LIST(V)
5007
5008   enum Kind {
5009 #define DEFINE_CODE_KIND_ENUM(name) name,
5010     CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5011 #undef DEFINE_CODE_KIND_ENUM
5012     NUMBER_OF_KINDS
5013   };
5014
5015   // No more than 16 kinds. The value is currently encoded in four bits in
5016   // Flags.
5017   STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5018
5019   static const char* Kind2String(Kind kind);
5020
5021   // Types of stubs.
5022   enum StubType {
5023     NORMAL,
5024     FAST
5025   };
5026
5027   static const int kPrologueOffsetNotSet = -1;
5028
5029 #ifdef ENABLE_DISASSEMBLER
5030   // Printing
5031   static const char* ICState2String(InlineCacheState state);
5032   static const char* StubType2String(StubType type);
5033   static void PrintExtraICState(std::ostream& os,  // NOLINT
5034                                 Kind kind, ExtraICState extra);
5035   void Disassemble(const char* name, std::ostream& os);  // NOLINT
5036 #endif  // ENABLE_DISASSEMBLER
5037
5038   // [instruction_size]: Size of the native instructions
5039   inline int instruction_size() const;
5040   inline void set_instruction_size(int value);
5041
5042   // [relocation_info]: Code relocation information
5043   DECL_ACCESSORS(relocation_info, ByteArray)
5044   void InvalidateRelocation();
5045   void InvalidateEmbeddedObjects();
5046
5047   // [handler_table]: Fixed array containing offsets of exception handlers.
5048   DECL_ACCESSORS(handler_table, FixedArray)
5049
5050   // [deoptimization_data]: Array containing data for deopt.
5051   DECL_ACCESSORS(deoptimization_data, FixedArray)
5052
5053   // [raw_type_feedback_info]: This field stores various things, depending on
5054   // the kind of the code object.
5055   //   FUNCTION           => type feedback information.
5056   //   STUB and ICs       => major/minor key as Smi.
5057   DECL_ACCESSORS(raw_type_feedback_info, Object)
5058   inline Object* type_feedback_info();
5059   inline void set_type_feedback_info(
5060       Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5061   inline uint32_t stub_key();
5062   inline void set_stub_key(uint32_t key);
5063
5064   // [next_code_link]: Link for lists of optimized or deoptimized code.
5065   // Note that storage for this field is overlapped with typefeedback_info.
5066   DECL_ACCESSORS(next_code_link, Object)
5067
5068   // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5069   // field does not have to be traced during garbage collection since
5070   // it is only used by the garbage collector itself.
5071   DECL_ACCESSORS(gc_metadata, Object)
5072
5073   // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5074   // at the moment when this object was created.
5075   inline void set_ic_age(int count);
5076   inline int ic_age() const;
5077
5078   // [prologue_offset]: Offset of the function prologue, used for aging
5079   // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5080   inline int prologue_offset() const;
5081   inline void set_prologue_offset(int offset);
5082
5083   // Unchecked accessors to be used during GC.
5084   inline ByteArray* unchecked_relocation_info();
5085
5086   inline int relocation_size();
5087
5088   // [flags]: Various code flags.
5089   inline Flags flags();
5090   inline void set_flags(Flags flags);
5091
5092   // [flags]: Access to specific code flags.
5093   inline Kind kind();
5094   inline InlineCacheState ic_state();  // Only valid for IC stubs.
5095   inline ExtraICState extra_ic_state();  // Only valid for IC stubs.
5096
5097   inline StubType type();  // Only valid for monomorphic IC stubs.
5098
5099   // Testers for IC stub kinds.
5100   inline bool is_inline_cache_stub();
5101   inline bool is_debug_stub();
5102   inline bool is_handler() { return kind() == HANDLER; }
5103   inline bool is_load_stub() { return kind() == LOAD_IC; }
5104   inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5105   inline bool is_store_stub() { return kind() == STORE_IC; }
5106   inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5107   inline bool is_call_stub() { return kind() == CALL_IC; }
5108   inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5109   inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5110   inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5111   inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5112   inline bool is_keyed_stub();
5113   inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5114   inline bool embeds_maps_weakly() {
5115     Kind k = kind();
5116     return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5117             k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5118            ic_state() == MONOMORPHIC;
5119   }
5120
5121   inline bool IsCodeStubOrIC();
5122
5123   inline void set_raw_kind_specific_flags1(int value);
5124   inline void set_raw_kind_specific_flags2(int value);
5125
5126   // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5127   // object was generated by either the hydrogen or the TurboFan optimizing
5128   // compiler (but it may not be an optimized function).
5129   inline bool is_crankshafted();
5130   inline bool is_hydrogen_stub();  // Crankshafted, but not a function.
5131   inline void set_is_crankshafted(bool value);
5132
5133   // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5134   // code object was generated by the TurboFan optimizing compiler.
5135   inline bool is_turbofanned();
5136   inline void set_is_turbofanned(bool value);
5137
5138   // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
5139   // embedded objects in code should be treated weakly.
5140   inline bool can_have_weak_objects();
5141   inline void set_can_have_weak_objects(bool value);
5142
5143   // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5144   inline bool optimizable();
5145   inline void set_optimizable(bool value);
5146
5147   // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5148   // deoptimization support.
5149   inline bool has_deoptimization_support();
5150   inline void set_has_deoptimization_support(bool value);
5151
5152   // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5153   // been compiled with debug break slots.
5154   inline bool has_debug_break_slots();
5155   inline void set_has_debug_break_slots(bool value);
5156
5157   // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5158   // been compiled with IsOptimizing set to true.
5159   inline bool is_compiled_optimizable();
5160   inline void set_compiled_optimizable(bool value);
5161
5162   // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5163   // reloc info includes runtime and external references to support
5164   // serialization/deserialization.
5165   inline bool has_reloc_info_for_serialization();
5166   inline void set_has_reloc_info_for_serialization(bool value);
5167
5168   // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5169   // how long the function has been marked for OSR and therefore which
5170   // level of loop nesting we are willing to do on-stack replacement
5171   // for.
5172   inline void set_allow_osr_at_loop_nesting_level(int level);
5173   inline int allow_osr_at_loop_nesting_level();
5174
5175   // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5176   // the code object was seen on the stack with no IC patching going on.
5177   inline int profiler_ticks();
5178   inline void set_profiler_ticks(int ticks);
5179
5180   // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5181   // For builtins, tells which builtin index it has.
5182   // Note that builtins can have a code kind other than BUILTIN, which means
5183   // that for arbitrary code objects, this index value may be random garbage.
5184   // To verify in that case, compare the code object to the indexed builtin.
5185   inline int builtin_index();
5186   inline void set_builtin_index(int id);
5187
5188   // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5189   // reserved in the code prologue.
5190   inline unsigned stack_slots();
5191   inline void set_stack_slots(unsigned slots);
5192
5193   // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5194   // the instruction stream where the safepoint table starts.
5195   inline unsigned safepoint_table_offset();
5196   inline void set_safepoint_table_offset(unsigned offset);
5197
5198   // [back_edge_table_start]: For kind FUNCTION, the offset in the
5199   // instruction stream where the back edge table starts.
5200   inline unsigned back_edge_table_offset();
5201   inline void set_back_edge_table_offset(unsigned offset);
5202
5203   inline bool back_edges_patched_for_osr();
5204
5205   // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5206   inline byte to_boolean_state();
5207
5208   // [has_function_cache]: For kind STUB tells whether there is a function
5209   // cache is passed to the stub.
5210   inline bool has_function_cache();
5211   inline void set_has_function_cache(bool flag);
5212
5213
5214   // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5215   // the code is going to be deoptimized because of dead embedded maps.
5216   inline bool marked_for_deoptimization();
5217   inline void set_marked_for_deoptimization(bool flag);
5218
5219   // [constant_pool]: The constant pool for this function.
5220   inline ConstantPoolArray* constant_pool();
5221   inline void set_constant_pool(Object* constant_pool);
5222
5223   // Get the safepoint entry for the given pc.
5224   SafepointEntry GetSafepointEntry(Address pc);
5225
5226   // Find an object in a stub with a specified map
5227   Object* FindNthObject(int n, Map* match_map);
5228
5229   // Find the first allocation site in an IC stub.
5230   AllocationSite* FindFirstAllocationSite();
5231
5232   // Find the first map in an IC stub.
5233   Map* FindFirstMap();
5234   void FindAllMaps(MapHandleList* maps);
5235
5236   // Find the first handler in an IC stub.
5237   Code* FindFirstHandler();
5238
5239   // Find |length| handlers and put them into |code_list|. Returns false if not
5240   // enough handlers can be found.
5241   bool FindHandlers(CodeHandleList* code_list, int length = -1);
5242
5243   // Find the handler for |map|.
5244   MaybeHandle<Code> FindHandlerForMap(Map* map);
5245
5246   // Find the first name in an IC stub.
5247   Name* FindFirstName();
5248
5249   class FindAndReplacePattern;
5250   // For each (map-to-find, object-to-replace) pair in the pattern, this
5251   // function replaces the corresponding placeholder in the code with the
5252   // object-to-replace. The function assumes that pairs in the pattern come in
5253   // the same order as the placeholders in the code.
5254   // If the placeholder is a weak cell, then the value of weak cell is matched
5255   // against the map-to-find.
5256   void FindAndReplace(const FindAndReplacePattern& pattern);
5257
5258   // The entire code object including its header is copied verbatim to the
5259   // snapshot so that it can be written in one, fast, memcpy during
5260   // deserialization. The deserializer will overwrite some pointers, rather
5261   // like a runtime linker, but the random allocation addresses used in the
5262   // mksnapshot process would still be present in the unlinked snapshot data,
5263   // which would make snapshot production non-reproducible. This method wipes
5264   // out the to-be-overwritten header data for reproducible snapshots.
5265   inline void WipeOutHeader();
5266
5267   // Flags operations.
5268   static inline Flags ComputeFlags(
5269       Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5270       ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5271       CacheHolderFlag holder = kCacheOnReceiver);
5272
5273   static inline Flags ComputeMonomorphicFlags(
5274       Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5275       CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5276
5277   static inline Flags ComputeHandlerFlags(
5278       Kind handler_kind, StubType type = NORMAL,
5279       CacheHolderFlag holder = kCacheOnReceiver);
5280
5281   static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5282   static inline StubType ExtractTypeFromFlags(Flags flags);
5283   static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5284   static inline Kind ExtractKindFromFlags(Flags flags);
5285   static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5286
5287   static inline Flags RemoveTypeFromFlags(Flags flags);
5288   static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5289
5290   // Convert a target address into a code object.
5291   static inline Code* GetCodeFromTargetAddress(Address address);
5292
5293   // Convert an entry address into an object.
5294   static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5295
5296   // Returns the address of the first instruction.
5297   inline byte* instruction_start();
5298
5299   // Returns the address right after the last instruction.
5300   inline byte* instruction_end();
5301
5302   // Returns the size of the instructions, padding, and relocation information.
5303   inline int body_size();
5304
5305   // Returns the address of the first relocation info (read backwards!).
5306   inline byte* relocation_start();
5307
5308   // Code entry point.
5309   inline byte* entry();
5310
5311   // Returns true if pc is inside this object's instructions.
5312   inline bool contains(byte* pc);
5313
5314   // Relocate the code by delta bytes. Called to signal that this code
5315   // object has been moved by delta bytes.
5316   void Relocate(intptr_t delta);
5317
5318   // Migrate code described by desc.
5319   void CopyFrom(const CodeDesc& desc);
5320
5321   // Returns the object size for a given body (used for allocation).
5322   static int SizeFor(int body_size) {
5323     DCHECK_SIZE_TAG_ALIGNED(body_size);
5324     return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5325   }
5326
5327   // Calculate the size of the code object to report for log events. This takes
5328   // the layout of the code object into account.
5329   int ExecutableSize() {
5330     // Check that the assumptions about the layout of the code object holds.
5331     DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5332               Code::kHeaderSize);
5333     return instruction_size() + Code::kHeaderSize;
5334   }
5335
5336   // Locating source position.
5337   int SourcePosition(Address pc);
5338   int SourceStatementPosition(Address pc);
5339
5340   DECLARE_CAST(Code)
5341
5342   // Dispatched behavior.
5343   int CodeSize() { return SizeFor(body_size()); }
5344   inline void CodeIterateBody(ObjectVisitor* v);
5345
5346   template<typename StaticVisitor>
5347   inline void CodeIterateBody(Heap* heap);
5348
5349   DECLARE_PRINTER(Code)
5350   DECLARE_VERIFIER(Code)
5351
5352   void ClearInlineCaches();
5353   void ClearInlineCaches(Kind kind);
5354
5355   BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5356   uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5357
5358 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5359   enum Age {
5360     kNotExecutedCodeAge = -2,
5361     kExecutedOnceCodeAge = -1,
5362     kNoAgeCodeAge = 0,
5363     CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5364     kAfterLastCodeAge,
5365     kFirstCodeAge = kNotExecutedCodeAge,
5366     kLastCodeAge = kAfterLastCodeAge - 1,
5367     kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5368     kIsOldCodeAge = kSexagenarianCodeAge,
5369     kPreAgedCodeAge = kIsOldCodeAge - 1
5370   };
5371 #undef DECLARE_CODE_AGE_ENUM
5372
5373   // Code aging.  Indicates how many full GCs this code has survived without
5374   // being entered through the prologue.  Used to determine when it is
5375   // relatively safe to flush this code object and replace it with the lazy
5376   // compilation stub.
5377   static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5378   static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5379   void MakeYoung(Isolate* isolate);
5380   void MakeOlder(MarkingParity);
5381   static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5382   bool IsOld();
5383   Age GetAge();
5384   // Gets the raw code age, including psuedo code-age values such as
5385   // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5386   Age GetRawAge();
5387   static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5388     return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5389   }
5390
5391   void PrintDeoptLocation(FILE* out, int bailout_id);
5392   bool CanDeoptAt(Address pc);
5393
5394 #ifdef VERIFY_HEAP
5395   void VerifyEmbeddedObjectsDependency();
5396 #endif
5397
5398 #ifdef DEBUG
5399   enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5400   void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5401 #endif  // DEBUG
5402
5403   inline bool CanContainWeakObjects() {
5404     // is_turbofanned() implies !can_have_weak_objects().
5405     DCHECK(!is_optimized_code() || !is_turbofanned() ||
5406            !can_have_weak_objects());
5407     return is_optimized_code() && can_have_weak_objects();
5408   }
5409
5410   inline bool IsWeakObject(Object* object) {
5411     return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5412   }
5413
5414   static inline bool IsWeakObjectInOptimizedCode(Object* object);
5415
5416   static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5417   WeakCell* CachedWeakCell();
5418
5419   // Max loop nesting marker used to postpose OSR. We don't take loop
5420   // nesting that is deeper than 5 levels into account.
5421   static const int kMaxLoopNestingMarker = 6;
5422
5423   // Layout description.
5424   static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5425   static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5426   static const int kDeoptimizationDataOffset =
5427       kHandlerTableOffset + kPointerSize;
5428   // For FUNCTION kind, we store the type feedback info here.
5429   static const int kTypeFeedbackInfoOffset =
5430       kDeoptimizationDataOffset + kPointerSize;
5431   static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5432   static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5433   static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5434   static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5435   static const int kFlagsOffset = kICAgeOffset + kIntSize;
5436   static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5437   static const int kKindSpecificFlags2Offset =
5438       kKindSpecificFlags1Offset + kIntSize;
5439   // Note: We might be able to squeeze this into the flags above.
5440   static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5441   static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5442
5443   static const int kHeaderPaddingStart = kConstantPoolOffset + kPointerSize;
5444
5445   // Add padding to align the instruction start following right after
5446   // the Code object header.
5447   static const int kHeaderSize =
5448       (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5449   // Ensure that the slot for the constant pool pointer is aligned.
5450   STATIC_ASSERT((kConstantPoolOffset & kPointerAlignmentMask) == 0);
5451
5452   // Byte offsets within kKindSpecificFlags1Offset.
5453   static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5454
5455   static const int kFullCodeFlags = kOptimizableOffset + 1;
5456   class FullCodeFlagsHasDeoptimizationSupportField:
5457       public BitField<bool, 0, 1> {};  // NOLINT
5458   class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5459   class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5460   class FullCodeFlagsHasRelocInfoForSerialization
5461       : public BitField<bool, 3, 1> {};
5462
5463   static const int kProfilerTicksOffset = kFullCodeFlags + 1;
5464
5465   // Flags layout.  BitField<type, shift, size>.
5466   class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5467   class TypeField : public BitField<StubType, 4, 1> {};
5468   class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5469   class KindField : public BitField<Kind, 7, 4> {};
5470   class ExtraICStateField: public BitField<ExtraICState, 11,
5471       PlatformSmiTagging::kSmiValueSize - 11 + 1> {};  // NOLINT
5472
5473   // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5474   static const int kStackSlotsFirstBit = 0;
5475   static const int kStackSlotsBitCount = 24;
5476   static const int kHasFunctionCacheBit =
5477       kStackSlotsFirstBit + kStackSlotsBitCount;
5478   static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5479   static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5480   static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5481
5482   STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5483   STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5484
5485   class StackSlotsField: public BitField<int,
5486       kStackSlotsFirstBit, kStackSlotsBitCount> {};  // NOLINT
5487   class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5488   };  // NOLINT
5489   class MarkedForDeoptimizationField
5490       : public BitField<bool, kMarkedForDeoptimizationBit, 1> {};   // NOLINT
5491   class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5492   };  // NOLINT
5493   class CanHaveWeakObjectsField
5494       : public BitField<bool, kCanHaveWeakObjects, 1> {};  // NOLINT
5495
5496   // KindSpecificFlags2 layout (ALL)
5497   static const int kIsCrankshaftedBit = 0;
5498   class IsCrankshaftedField: public BitField<bool,
5499       kIsCrankshaftedBit, 1> {};  // NOLINT
5500
5501   // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5502   static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5503   static const int kSafepointTableOffsetBitCount = 24;
5504
5505   STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5506                 kSafepointTableOffsetBitCount <= 32);
5507   STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5508
5509   class SafepointTableOffsetField: public BitField<int,
5510       kSafepointTableOffsetFirstBit,
5511       kSafepointTableOffsetBitCount> {};  // NOLINT
5512
5513   // KindSpecificFlags2 layout (FUNCTION)
5514   class BackEdgeTableOffsetField: public BitField<int,
5515       kIsCrankshaftedBit + 1, 27> {};  // NOLINT
5516   class AllowOSRAtLoopNestingLevelField: public BitField<int,
5517       kIsCrankshaftedBit + 1 + 27, 4> {};  // NOLINT
5518   STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5519
5520   static const int kArgumentsBits = 16;
5521   static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5522
5523   // This constant should be encodable in an ARM instruction.
5524   static const int kFlagsNotUsedInLookup =
5525       TypeField::kMask | CacheHolderField::kMask;
5526
5527  private:
5528   friend class RelocIterator;
5529   friend class Deoptimizer;  // For FindCodeAgeSequence.
5530
5531   void ClearInlineCaches(Kind* kind);
5532
5533   // Code aging
5534   byte* FindCodeAgeSequence();
5535   static void GetCodeAgeAndParity(Code* code, Age* age,
5536                                   MarkingParity* parity);
5537   static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5538                                   MarkingParity* parity);
5539   static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5540
5541   // Code aging -- platform-specific
5542   static void PatchPlatformCodeAge(Isolate* isolate,
5543                                    byte* sequence, Age age,
5544                                    MarkingParity parity);
5545
5546   DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5547 };
5548
5549
5550 class CompilationInfo;
5551
5552 // This class describes the layout of dependent codes array of a map. The
5553 // array is partitioned into several groups of dependent codes. Each group
5554 // contains codes with the same dependency on the map. The array has the
5555 // following layout for n dependency groups:
5556 //
5557 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5558 // | C1 | C2 | ... | Cn | group 1 |  group 2 | ... | group n | undefined |
5559 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5560 //
5561 // The first n elements are Smis, each of them specifies the number of codes
5562 // in the corresponding group. The subsequent elements contain grouped code
5563 // objects in weak cells. The suffix of the array can be filled with the
5564 // undefined value if the number of codes is less than the length of the
5565 // array. The order of the code objects within a group is not preserved.
5566 //
5567 // All code indexes used in the class are counted starting from the first
5568 // code object of the first group. In other words, code index 0 corresponds
5569 // to array index n = kCodesStartIndex.
5570
5571 class DependentCode: public FixedArray {
5572  public:
5573   enum DependencyGroup {
5574     // Group of code that weakly embed this map and depend on being
5575     // deoptimized when the map is garbage collected.
5576     kWeakCodeGroup,
5577     // Group of code that embed a transition to this map, and depend on being
5578     // deoptimized when the transition is replaced by a new version.
5579     kTransitionGroup,
5580     // Group of code that omit run-time prototype checks for prototypes
5581     // described by this map. The group is deoptimized whenever an object
5582     // described by this map changes shape (and transitions to a new map),
5583     // possibly invalidating the assumptions embedded in the code.
5584     kPrototypeCheckGroup,
5585     // Group of code that depends on elements not being added to objects with
5586     // this map.
5587     kElementsCantBeAddedGroup,
5588     // Group of code that depends on global property values in property cells
5589     // not being changed.
5590     kPropertyCellChangedGroup,
5591     // Group of code that omit run-time type checks for the field(s) introduced
5592     // by this map.
5593     kFieldTypeGroup,
5594     // Group of code that omit run-time type checks for initial maps of
5595     // constructors.
5596     kInitialMapChangedGroup,
5597     // Group of code that depends on tenuring information in AllocationSites
5598     // not being changed.
5599     kAllocationSiteTenuringChangedGroup,
5600     // Group of code that depends on element transition information in
5601     // AllocationSites not being changed.
5602     kAllocationSiteTransitionChangedGroup
5603   };
5604
5605   static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5606
5607   // Array for holding the index of the first code object of each group.
5608   // The last element stores the total number of code objects.
5609   class GroupStartIndexes {
5610    public:
5611     explicit GroupStartIndexes(DependentCode* entries);
5612     void Recompute(DependentCode* entries);
5613     int at(int i) { return start_indexes_[i]; }
5614     int number_of_entries() { return start_indexes_[kGroupCount]; }
5615    private:
5616     int start_indexes_[kGroupCount + 1];
5617   };
5618
5619   bool Contains(DependencyGroup group, WeakCell* code_cell);
5620
5621   static Handle<DependentCode> InsertCompilationInfo(
5622       Handle<DependentCode> entries, DependencyGroup group,
5623       Handle<Foreign> info);
5624
5625   static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5626                                               DependencyGroup group,
5627                                               Handle<WeakCell> code_cell);
5628
5629   void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5630                             WeakCell* code_cell);
5631
5632   void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5633                              Foreign* info);
5634
5635   void DeoptimizeDependentCodeGroup(Isolate* isolate,
5636                                     DependentCode::DependencyGroup group);
5637
5638   bool MarkCodeForDeoptimization(Isolate* isolate,
5639                                  DependentCode::DependencyGroup group);
5640
5641   // The following low-level accessors should only be used by this class
5642   // and the mark compact collector.
5643   inline int number_of_entries(DependencyGroup group);
5644   inline void set_number_of_entries(DependencyGroup group, int value);
5645   inline Object* object_at(int i);
5646   inline void set_object_at(int i, Object* object);
5647   inline void clear_at(int i);
5648   inline void copy(int from, int to);
5649   DECLARE_CAST(DependentCode)
5650
5651   static DependentCode* ForObject(Handle<HeapObject> object,
5652                                   DependencyGroup group);
5653
5654   static const char* DependencyGroupName(DependencyGroup group);
5655   static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5656
5657  private:
5658   static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5659                                       DependencyGroup group,
5660                                       Handle<Object> object);
5661   static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5662   // Make a room at the end of the given group by moving out the first
5663   // code objects of the subsequent groups.
5664   inline void ExtendGroup(DependencyGroup group);
5665   // Compact by removing cleared weak cells and return true if there was
5666   // any cleared weak cell.
5667   bool Compact();
5668   static int Grow(int number_of_entries) {
5669     if (number_of_entries < 5) return number_of_entries + 1;
5670     return number_of_entries * 5 / 4;
5671   }
5672   static const int kCodesStartIndex = kGroupCount;
5673 };
5674
5675
5676 // All heap objects have a Map that describes their structure.
5677 //  A Map contains information about:
5678 //  - Size information about the object
5679 //  - How to iterate over an object (for garbage collection)
5680 class Map: public HeapObject {
5681  public:
5682   // Instance size.
5683   // Size in bytes or kVariableSizeSentinel if instances do not have
5684   // a fixed size.
5685   inline int instance_size();
5686   inline void set_instance_size(int value);
5687
5688   // Count of properties allocated in the object.
5689   inline int inobject_properties();
5690   inline void set_inobject_properties(int value);
5691
5692   // Count of property fields pre-allocated in the object when first allocated.
5693   inline int pre_allocated_property_fields();
5694   inline void set_pre_allocated_property_fields(int value);
5695
5696   // Instance type.
5697   inline InstanceType instance_type();
5698   inline void set_instance_type(InstanceType value);
5699
5700   // Tells how many unused property fields are available in the
5701   // instance (only used for JSObject in fast mode).
5702   inline int unused_property_fields();
5703   inline void set_unused_property_fields(int value);
5704
5705   // Bit field.
5706   inline byte bit_field();
5707   inline void set_bit_field(byte value);
5708
5709   // Bit field 2.
5710   inline byte bit_field2();
5711   inline void set_bit_field2(byte value);
5712
5713   // Bit field 3.
5714   inline uint32_t bit_field3();
5715   inline void set_bit_field3(uint32_t bits);
5716
5717   class EnumLengthBits:             public BitField<int,
5718       0, kDescriptorIndexBitCount> {};  // NOLINT
5719   class NumberOfOwnDescriptorsBits: public BitField<int,
5720       kDescriptorIndexBitCount, kDescriptorIndexBitCount> {};  // NOLINT
5721   STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5722   class DictionaryMap : public BitField<bool, 20, 1> {};
5723   class OwnsDescriptors : public BitField<bool, 21, 1> {};
5724   class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5725   class Deprecated : public BitField<bool, 23, 1> {};
5726   class IsUnstable : public BitField<bool, 24, 1> {};
5727   class IsMigrationTarget : public BitField<bool, 25, 1> {};
5728   // Bits 26 and 27 are free.
5729
5730   // Keep this bit field at the very end for better code in
5731   // Builtins::kJSConstructStubGeneric stub.
5732   // This counter is used for in-object slack tracking and for map aging.
5733   // The in-object slack tracking is considered enabled when the counter is
5734   // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5735   class Counter : public BitField<int, 28, 4> {};
5736   static const int kSlackTrackingCounterStart = 14;
5737   static const int kSlackTrackingCounterEnd = 8;
5738   static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5739   static const int kRetainingCounterEnd = 0;
5740
5741   // Tells whether the object in the prototype property will be used
5742   // for instances created from this function.  If the prototype
5743   // property is set to a value that is not a JSObject, the prototype
5744   // property will not be used to create instances of the function.
5745   // See ECMA-262, 13.2.2.
5746   inline void set_non_instance_prototype(bool value);
5747   inline bool has_non_instance_prototype();
5748
5749   // Tells whether function has special prototype property. If not, prototype
5750   // property will not be created when accessed (will return undefined),
5751   // and construction from this function will not be allowed.
5752   inline void set_function_with_prototype(bool value);
5753   inline bool function_with_prototype();
5754
5755   // Tells whether the instance with this map should be ignored by the
5756   // Object.getPrototypeOf() function and the __proto__ accessor.
5757   inline void set_is_hidden_prototype() {
5758     set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5759   }
5760
5761   inline bool is_hidden_prototype() {
5762     return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5763   }
5764
5765   // Records and queries whether the instance has a named interceptor.
5766   inline void set_has_named_interceptor() {
5767     set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5768   }
5769
5770   inline bool has_named_interceptor() {
5771     return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5772   }
5773
5774   // Records and queries whether the instance has an indexed interceptor.
5775   inline void set_has_indexed_interceptor() {
5776     set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5777   }
5778
5779   inline bool has_indexed_interceptor() {
5780     return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5781   }
5782
5783   // Tells whether the instance is undetectable.
5784   // An undetectable object is a special class of JSObject: 'typeof' operator
5785   // returns undefined, ToBoolean returns false. Otherwise it behaves like
5786   // a normal JS object.  It is useful for implementing undetectable
5787   // document.all in Firefox & Safari.
5788   // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5789   inline void set_is_undetectable() {
5790     set_bit_field(bit_field() | (1 << kIsUndetectable));
5791   }
5792
5793   inline bool is_undetectable() {
5794     return ((1 << kIsUndetectable) & bit_field()) != 0;
5795   }
5796
5797   // Tells whether the instance has a call-as-function handler.
5798   inline void set_is_observed() {
5799     set_bit_field(bit_field() | (1 << kIsObserved));
5800   }
5801
5802   inline bool is_observed() {
5803     return ((1 << kIsObserved) & bit_field()) != 0;
5804   }
5805
5806   inline void set_is_extensible(bool value);
5807   inline bool is_extensible();
5808   inline void set_is_prototype_map(bool value);
5809   inline bool is_prototype_map();
5810
5811   inline void set_elements_kind(ElementsKind elements_kind) {
5812     DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5813     DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5814     set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5815     DCHECK(this->elements_kind() == elements_kind);
5816   }
5817
5818   inline ElementsKind elements_kind() {
5819     return Map::ElementsKindBits::decode(bit_field2());
5820   }
5821
5822   // Tells whether the instance has fast elements that are only Smis.
5823   inline bool has_fast_smi_elements() {
5824     return IsFastSmiElementsKind(elements_kind());
5825   }
5826
5827   // Tells whether the instance has fast elements.
5828   inline bool has_fast_object_elements() {
5829     return IsFastObjectElementsKind(elements_kind());
5830   }
5831
5832   inline bool has_fast_smi_or_object_elements() {
5833     return IsFastSmiOrObjectElementsKind(elements_kind());
5834   }
5835
5836   inline bool has_fast_double_elements() {
5837     return IsFastDoubleElementsKind(elements_kind());
5838   }
5839
5840   inline bool has_fast_elements() {
5841     return IsFastElementsKind(elements_kind());
5842   }
5843
5844   inline bool has_sloppy_arguments_elements() {
5845     return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5846   }
5847
5848   inline bool has_external_array_elements() {
5849     return IsExternalArrayElementsKind(elements_kind());
5850   }
5851
5852   inline bool has_fixed_typed_array_elements() {
5853     return IsFixedTypedArrayElementsKind(elements_kind());
5854   }
5855
5856   inline bool has_dictionary_elements() {
5857     return IsDictionaryElementsKind(elements_kind());
5858   }
5859
5860   inline bool has_slow_elements_kind() {
5861     return elements_kind() == DICTIONARY_ELEMENTS
5862         || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5863   }
5864
5865   static bool IsValidElementsTransition(ElementsKind from_kind,
5866                                         ElementsKind to_kind);
5867
5868   // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5869   // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5870   bool DictionaryElementsInPrototypeChainOnly();
5871
5872   inline bool HasTransitionArray() const;
5873   inline bool HasElementsTransition();
5874   inline Map* elements_transition_map();
5875
5876   inline Map* GetTransition(int transition_index);
5877   inline int SearchSpecialTransition(Symbol* name);
5878   inline int SearchTransition(PropertyKind kind, Name* name,
5879                               PropertyAttributes attributes);
5880   inline FixedArrayBase* GetInitialElements();
5881
5882   DECL_ACCESSORS(transitions, TransitionArray)
5883
5884   static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
5885   static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
5886
5887   // Try to follow an existing transition to a field with attributes NONE. The
5888   // return value indicates whether the transition was successful.
5889   static inline Handle<Map> FindTransitionToField(Handle<Map> map,
5890                                                   Handle<Name> key);
5891
5892   Map* FindRootMap();
5893   Map* FindFieldOwner(int descriptor);
5894
5895   inline int GetInObjectPropertyOffset(int index);
5896
5897   int NumberOfFields();
5898
5899   // TODO(ishell): candidate with JSObject::MigrateToMap().
5900   bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5901                               int target_inobject, int target_unused,
5902                               int* old_number_of_fields);
5903   // TODO(ishell): moveit!
5904   static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5905   MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5906       Handle<HeapType> type1,
5907       Handle<HeapType> type2,
5908       Isolate* isolate);
5909   static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5910                                   Representation new_representation,
5911                                   Handle<HeapType> new_field_type);
5912   static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5913                                          PropertyKind new_kind,
5914                                          PropertyAttributes new_attributes,
5915                                          Representation new_representation,
5916                                          Handle<HeapType> new_field_type,
5917                                          StoreMode store_mode);
5918   static Handle<Map> CopyGeneralizeAllRepresentations(
5919       Handle<Map> map, int modify_index, StoreMode store_mode,
5920       PropertyKind kind, PropertyAttributes attributes, const char* reason);
5921
5922   static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5923                                             int descriptor_number,
5924                                             Handle<Object> value);
5925
5926   static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5927                                const char* reason);
5928
5929   // Returns the constructor name (the name (possibly, inferred name) of the
5930   // function that was used to instantiate the object).
5931   String* constructor_name();
5932
5933   // Tells whether the map is used for JSObjects in dictionary mode (ie
5934   // normalized objects, ie objects for which HasFastProperties returns false).
5935   // A map can never be used for both dictionary mode and fast mode JSObjects.
5936   // False by default and for HeapObjects that are not JSObjects.
5937   inline void set_dictionary_map(bool value);
5938   inline bool is_dictionary_map();
5939
5940   // Tells whether the instance needs security checks when accessing its
5941   // properties.
5942   inline void set_is_access_check_needed(bool access_check_needed);
5943   inline bool is_access_check_needed();
5944
5945   // Returns true if map has a non-empty stub code cache.
5946   inline bool has_code_cache();
5947
5948   // [prototype]: implicit prototype object.
5949   DECL_ACCESSORS(prototype, Object)
5950   // TODO(jkummerow): make set_prototype private.
5951   void SetPrototype(Handle<Object> prototype,
5952                     PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5953   bool ShouldRegisterAsPrototypeUser(Handle<JSObject> prototype);
5954   bool CanUseOptimizationsBasedOnPrototypeRegistry();
5955
5956   // [constructor]: points back to the function responsible for this map.
5957   DECL_ACCESSORS(constructor, Object)
5958
5959   // [instance descriptors]: describes the object.
5960   DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5961
5962   // [layout descriptor]: describes the object layout.
5963   DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5964   // |layout descriptor| accessor which can be used from GC.
5965   inline LayoutDescriptor* layout_descriptor_gc_safe();
5966   inline bool HasFastPointerLayout() const;
5967
5968   // |layout descriptor| accessor that is safe to call even when
5969   // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5970   // |layout_descriptor| field at all).
5971   inline LayoutDescriptor* GetLayoutDescriptor();
5972
5973   inline void UpdateDescriptors(DescriptorArray* descriptors,
5974                                 LayoutDescriptor* layout_descriptor);
5975   inline void InitializeDescriptors(DescriptorArray* descriptors,
5976                                     LayoutDescriptor* layout_descriptor);
5977
5978   // [stub cache]: contains stubs compiled for this map.
5979   DECL_ACCESSORS(code_cache, Object)
5980
5981   // [dependent code]: list of optimized codes that weakly embed this map.
5982   DECL_ACCESSORS(dependent_code, DependentCode)
5983
5984   // [back pointer]: points back to the parent map from which a transition
5985   // leads to this map. The field overlaps with prototype transitions and the
5986   // back pointer will be moved into the prototype transitions array if
5987   // required.
5988   inline Object* GetBackPointer();
5989   inline void SetBackPointer(Object* value,
5990                              WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5991   inline void init_back_pointer(Object* undefined);
5992
5993   // [prototype transitions]: cache of prototype transitions.
5994   // Prototype transition is a transition that happens
5995   // when we change object's prototype to a new one.
5996   // Cache format:
5997   //    0: finger - index of the first free cell in the cache
5998   //    1 + i: target map
5999   inline FixedArray* GetPrototypeTransitions();
6000   inline bool HasPrototypeTransitions();
6001
6002   static const int kProtoTransitionNumberOfEntriesOffset = 0;
6003   static const int kProtoTransitionHeaderSize = 1;
6004
6005   inline int NumberOfProtoTransitions() {
6006     FixedArray* cache = GetPrototypeTransitions();
6007     if (cache->length() == 0) return 0;
6008     return
6009         Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6010   }
6011
6012   inline void SetNumberOfProtoTransitions(int value) {
6013     FixedArray* cache = GetPrototypeTransitions();
6014     DCHECK(cache->length() != 0);
6015     cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6016   }
6017
6018   inline PropertyDetails GetLastDescriptorDetails();
6019
6020   // The size of transition arrays are limited so they do not end up in large
6021   // object space. Otherwise ClearNonLiveTransitions would leak memory while
6022   // applying in-place right trimming.
6023   inline bool CanHaveMoreTransitions();
6024
6025   int LastAdded() {
6026     int number_of_own_descriptors = NumberOfOwnDescriptors();
6027     DCHECK(number_of_own_descriptors > 0);
6028     return number_of_own_descriptors - 1;
6029   }
6030
6031   int NumberOfOwnDescriptors() {
6032     return NumberOfOwnDescriptorsBits::decode(bit_field3());
6033   }
6034
6035   void SetNumberOfOwnDescriptors(int number) {
6036     DCHECK(number <= instance_descriptors()->number_of_descriptors());
6037     set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6038   }
6039
6040   inline Cell* RetrieveDescriptorsPointer();
6041
6042   int EnumLength() {
6043     return EnumLengthBits::decode(bit_field3());
6044   }
6045
6046   void SetEnumLength(int length) {
6047     if (length != kInvalidEnumCacheSentinel) {
6048       DCHECK(length >= 0);
6049       DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
6050       DCHECK(length <= NumberOfOwnDescriptors());
6051     }
6052     set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6053   }
6054
6055   inline bool owns_descriptors();
6056   inline void set_owns_descriptors(bool owns_descriptors);
6057   inline bool has_instance_call_handler();
6058   inline void set_has_instance_call_handler();
6059   inline void mark_unstable();
6060   inline bool is_stable();
6061   inline void set_migration_target(bool value);
6062   inline bool is_migration_target();
6063   inline void set_counter(int value);
6064   inline int counter();
6065   inline void deprecate();
6066   inline bool is_deprecated();
6067   inline bool CanBeDeprecated();
6068   // Returns a non-deprecated version of the input. If the input was not
6069   // deprecated, it is directly returned. Otherwise, the non-deprecated version
6070   // is found by re-transitioning from the root of the transition tree using the
6071   // descriptor array of the map. Returns NULL if no updated map is found.
6072   // This method also applies any pending migrations along the prototype chain.
6073   static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
6074   // Same as above, but does not touch the prototype chain.
6075   static MaybeHandle<Map> TryUpdateInternal(Handle<Map> map)
6076       WARN_UNUSED_RESULT;
6077
6078   // Returns a non-deprecated version of the input. This method may deprecate
6079   // existing maps along the way if encodings conflict. Not for use while
6080   // gathering type feedback. Use TryUpdate in those cases instead.
6081   static Handle<Map> Update(Handle<Map> map);
6082
6083   static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6084   static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
6085                                           Descriptor* descriptor,
6086                                           TransitionFlag flag);
6087
6088   MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
6089       Handle<Map> map,
6090       Handle<Name> name,
6091       Handle<HeapType> type,
6092       PropertyAttributes attributes,
6093       Representation representation,
6094       TransitionFlag flag);
6095
6096   MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
6097       Handle<Map> map,
6098       Handle<Name> name,
6099       Handle<Object> constant,
6100       PropertyAttributes attributes,
6101       TransitionFlag flag);
6102
6103   // Returns a new map with all transitions dropped from the given map and
6104   // the ElementsKind set.
6105   static Handle<Map> TransitionElementsTo(Handle<Map> map,
6106                                           ElementsKind to_kind);
6107
6108   static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6109
6110   static Handle<Map> CopyAsElementsKind(Handle<Map> map,
6111                                         ElementsKind kind,
6112                                         TransitionFlag flag);
6113
6114   static Handle<Map> CopyForObserved(Handle<Map> map);
6115
6116   static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
6117                                               PropertyAttributes attrs_to_add,
6118                                               Handle<Symbol> transition_marker,
6119                                               const char* reason);
6120   // Maximal number of fast properties. Used to restrict the number of map
6121   // transitions to avoid an explosion in the number of maps for objects used as
6122   // dictionaries.
6123   inline bool TooManyFastProperties(StoreFromKeyed store_mode);
6124   static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6125                                               Handle<Name> name,
6126                                               Handle<Object> value,
6127                                               PropertyAttributes attributes,
6128                                               StoreFromKeyed store_mode);
6129   static Handle<Map> TransitionToAccessorProperty(
6130       Handle<Map> map, Handle<Name> name, AccessorComponent component,
6131       Handle<Object> accessor, PropertyAttributes attributes);
6132   static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
6133                                                  int descriptor,
6134                                                  PropertyKind kind,
6135                                                  PropertyAttributes attributes);
6136
6137   inline void AppendDescriptor(Descriptor* desc);
6138
6139   // Returns a copy of the map, prepared for inserting into the transition
6140   // tree (if the |map| owns descriptors then the new one will share
6141   // descriptors with |map|).
6142   static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
6143
6144   // Returns a copy of the map, with all transitions dropped from the
6145   // instance descriptors.
6146   static Handle<Map> Copy(Handle<Map> map, const char* reason);
6147   static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6148
6149   // Returns the next free property index (only valid for FAST MODE).
6150   int NextFreePropertyIndex();
6151
6152   // Returns the number of properties described in instance_descriptors
6153   // filtering out properties with the specified attributes.
6154   int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6155                                   PropertyAttributes filter = NONE);
6156
6157   // Returns the number of slots allocated for the initial properties
6158   // backing storage for instances of this map.
6159   int InitialPropertiesLength() {
6160     return pre_allocated_property_fields() + unused_property_fields() -
6161         inobject_properties();
6162   }
6163
6164   DECLARE_CAST(Map)
6165
6166   // Code cache operations.
6167
6168   // Clears the code cache.
6169   inline void ClearCodeCache(Heap* heap);
6170
6171   // Update code cache.
6172   static void UpdateCodeCache(Handle<Map> map,
6173                               Handle<Name> name,
6174                               Handle<Code> code);
6175
6176   // Extend the descriptor array of the map with the list of descriptors.
6177   // In case of duplicates, the latest descriptor is used.
6178   static void AppendCallbackDescriptors(Handle<Map> map,
6179                                         Handle<Object> descriptors);
6180
6181   static inline int SlackForArraySize(int old_size, int size_limit);
6182
6183   static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6184
6185   // Returns the found code or undefined if absent.
6186   Object* FindInCodeCache(Name* name, Code::Flags flags);
6187
6188   // Returns the non-negative index of the code object if it is in the
6189   // cache and -1 otherwise.
6190   int IndexInCodeCache(Object* name, Code* code);
6191
6192   // Removes a code object from the code cache at the given index.
6193   void RemoveFromCodeCache(Name* name, Code* code, int index);
6194
6195   // Set all map transitions from this map to dead maps to null.  Also clear
6196   // back pointers in transition targets so that we do not process this map
6197   // again while following back pointers.
6198   void ClearNonLiveTransitions(Heap* heap);
6199
6200   // Computes a hash value for this map, to be used in HashTables and such.
6201   int Hash();
6202
6203   // Returns the map that this map transitions to if its elements_kind
6204   // is changed to |elements_kind|, or NULL if no such map is cached yet.
6205   // |safe_to_add_transitions| is set to false if adding transitions is not
6206   // allowed.
6207   Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6208
6209   // Returns the transitioned map for this map with the most generic
6210   // elements_kind that's found in |candidates|, or null handle if no match is
6211   // found at all.
6212   Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6213
6214   bool CanTransition() {
6215     // Only JSObject and subtypes have map transitions and back pointers.
6216     STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6217     return instance_type() >= FIRST_JS_OBJECT_TYPE;
6218   }
6219
6220   bool IsJSObjectMap() {
6221     return instance_type() >= FIRST_JS_OBJECT_TYPE;
6222   }
6223   bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6224   bool IsJSProxyMap() {
6225     InstanceType type = instance_type();
6226     return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6227   }
6228   bool IsJSGlobalProxyMap() {
6229     return instance_type() == JS_GLOBAL_PROXY_TYPE;
6230   }
6231   bool IsJSGlobalObjectMap() {
6232     return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6233   }
6234   bool IsGlobalObjectMap() {
6235     const InstanceType type = instance_type();
6236     return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6237   }
6238
6239   inline bool CanOmitMapChecks();
6240
6241   static void AddDependentCompilationInfo(Handle<Map> map,
6242                                           DependentCode::DependencyGroup group,
6243                                           CompilationInfo* info);
6244
6245   static void AddDependentCode(Handle<Map> map,
6246                                DependentCode::DependencyGroup group,
6247                                Handle<Code> code);
6248
6249   bool IsMapInArrayPrototypeChain();
6250
6251   static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6252
6253   // Dispatched behavior.
6254   DECLARE_PRINTER(Map)
6255   DECLARE_VERIFIER(Map)
6256
6257 #ifdef VERIFY_HEAP
6258   void DictionaryMapVerify();
6259   void VerifyOmittedMapChecks();
6260 #endif
6261
6262   inline int visitor_id();
6263   inline void set_visitor_id(int visitor_id);
6264
6265   typedef void (*TraverseCallback)(Map* map, void* data);
6266
6267   void TraverseTransitionTree(TraverseCallback callback, void* data);
6268
6269   // When you set the prototype of an object using the __proto__ accessor you
6270   // need a new map for the object (the prototype is stored in the map).  In
6271   // order not to multiply maps unnecessarily we store these as transitions in
6272   // the original map.  That way we can transition to the same map if the same
6273   // prototype is set, rather than creating a new map every time.  The
6274   // transitions are in the form of a map where the keys are prototype objects
6275   // and the values are the maps they transition to.
6276   static const int kMaxCachedPrototypeTransitions = 256;
6277   static Handle<Map> TransitionToPrototype(Handle<Map> map,
6278                                            Handle<Object> prototype,
6279                                            PrototypeOptimizationMode mode);
6280
6281   static const int kMaxPreAllocatedPropertyFields = 255;
6282
6283   // Layout description.
6284   static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6285   static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6286   static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6287   static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6288   static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6289   // Storage for the transition array is overloaded to directly contain a back
6290   // pointer if unused. When the map has transitions, the back pointer is
6291   // transferred to the transition array and accessed through an extra
6292   // indirection.
6293   static const int kTransitionsOrBackPointerOffset =
6294       kConstructorOffset + kPointerSize;
6295   static const int kDescriptorsOffset =
6296       kTransitionsOrBackPointerOffset + kPointerSize;
6297 #if V8_DOUBLE_FIELDS_UNBOXING
6298   static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6299   static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6300 #else
6301   static const int kLayoutDecriptorOffset = 1;  // Must not be ever accessed.
6302   static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6303 #endif
6304   static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6305   static const int kSize = kDependentCodeOffset + kPointerSize;
6306
6307   // Layout of pointer fields. Heap iteration code relies on them
6308   // being continuously allocated.
6309   static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6310   static const int kPointerFieldsEndOffset = kSize;
6311
6312   // Byte offsets within kInstanceSizesOffset.
6313   static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6314   static const int kInObjectPropertiesByte = 1;
6315   static const int kInObjectPropertiesOffset =
6316       kInstanceSizesOffset + kInObjectPropertiesByte;
6317   static const int kPreAllocatedPropertyFieldsByte = 2;
6318   static const int kPreAllocatedPropertyFieldsOffset =
6319       kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6320   static const int kVisitorIdByte = 3;
6321   static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6322
6323   // Byte offsets within kInstanceAttributesOffset attributes.
6324 #if V8_TARGET_LITTLE_ENDIAN
6325   // Order instance type and bit field together such that they can be loaded
6326   // together as a 16-bit word with instance type in the lower 8 bits regardless
6327   // of endianess. Also provide endian-independent offset to that 16-bit word.
6328   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6329   static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6330 #else
6331   static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6332   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6333 #endif
6334   static const int kInstanceTypeAndBitFieldOffset =
6335       kInstanceAttributesOffset + 0;
6336   static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6337   static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6338
6339   STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6340                 Internals::kMapInstanceTypeAndBitFieldOffset);
6341
6342   // Bit positions for bit field.
6343   static const int kHasNonInstancePrototype = 0;
6344   static const int kIsHiddenPrototype = 1;
6345   static const int kHasNamedInterceptor = 2;
6346   static const int kHasIndexedInterceptor = 3;
6347   static const int kIsUndetectable = 4;
6348   static const int kIsObserved = 5;
6349   static const int kIsAccessCheckNeeded = 6;
6350   class FunctionWithPrototype: public BitField<bool, 7,  1> {};
6351
6352   // Bit positions for bit field 2
6353   static const int kIsExtensible = 0;
6354   static const int kStringWrapperSafeForDefaultValueOf = 1;
6355   class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6356   class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6357
6358   // Derived values from bit field 2
6359   static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6360       (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6361   static const int8_t kMaximumBitField2FastSmiElementValue =
6362       static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6363                           Map::ElementsKindBits::kShift) - 1;
6364   static const int8_t kMaximumBitField2FastHoleyElementValue =
6365       static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6366                           Map::ElementsKindBits::kShift) - 1;
6367   static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6368       static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6369                           Map::ElementsKindBits::kShift) - 1;
6370
6371   typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6372                               kPointerFieldsEndOffset,
6373                               kSize> BodyDescriptor;
6374
6375   // Compares this map to another to see if they describe equivalent objects.
6376   // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6377   // it had exactly zero inobject properties.
6378   // The "shared" flags of both this map and |other| are ignored.
6379   bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6380
6381   // Returns true if given field is unboxed double.
6382   inline bool IsUnboxedDoubleField(FieldIndex index);
6383
6384 #if TRACE_MAPS
6385   static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6386   static void TraceAllTransitions(Map* map);
6387 #endif
6388
6389   static inline Handle<Map> CopyInstallDescriptorsForTesting(
6390       Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6391       Handle<LayoutDescriptor> layout_descriptor);
6392
6393  private:
6394   static void ConnectElementsTransition(Handle<Map> parent, Handle<Map> child);
6395   static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6396                                 Handle<Name> name, SimpleTransitionFlag flag);
6397
6398   bool EquivalentToForTransition(Map* other);
6399   static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6400   static Handle<Map> ShareDescriptor(Handle<Map> map,
6401                                      Handle<DescriptorArray> descriptors,
6402                                      Descriptor* descriptor);
6403   static Handle<Map> CopyInstallDescriptors(
6404       Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6405       Handle<LayoutDescriptor> layout_descriptor);
6406   static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6407                                        Descriptor* descriptor,
6408                                        TransitionFlag flag);
6409   static Handle<Map> CopyReplaceDescriptors(
6410       Handle<Map> map, Handle<DescriptorArray> descriptors,
6411       Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6412       MaybeHandle<Name> maybe_name, const char* reason,
6413       SimpleTransitionFlag simple_flag);
6414
6415   static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6416                                            Handle<DescriptorArray> descriptors,
6417                                            Descriptor* descriptor,
6418                                            int index,
6419                                            TransitionFlag flag);
6420   static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6421       Handle<Map> map, int descriptor, PropertyKind kind,
6422       PropertyAttributes attributes, const char** reason);
6423
6424   static Handle<Map> CopyNormalized(Handle<Map> map,
6425                                     PropertyNormalizationMode mode);
6426
6427   // Fires when the layout of an object with a leaf map changes.
6428   // This includes adding transitions to the leaf map or changing
6429   // the descriptor array.
6430   inline void NotifyLeafMapLayoutChange();
6431
6432   static Handle<Map> TransitionElementsToSlow(Handle<Map> object,
6433                                               ElementsKind to_kind);
6434
6435   // Zaps the contents of backing data structures. Note that the
6436   // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6437   // holding weak references when incremental marking is used, because it also
6438   // iterates over objects that are otherwise unreachable.
6439   // In general we only want to call these functions in release mode when
6440   // heap verification is turned on.
6441   void ZapPrototypeTransitions();
6442   void ZapTransitions();
6443
6444   void DeprecateTransitionTree();
6445   bool DeprecateTarget(PropertyKind kind, Name* key,
6446                        PropertyAttributes attributes,
6447                        DescriptorArray* new_descriptors,
6448                        LayoutDescriptor* new_layout_descriptor);
6449
6450   Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6451
6452   void UpdateFieldType(int descriptor_number, Handle<Name> name,
6453                        Representation new_representation,
6454                        Handle<HeapType> new_type);
6455
6456   void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6457                             PropertyAttributes attributes);
6458   void PrintGeneralization(FILE* file,
6459                            const char* reason,
6460                            int modify_index,
6461                            int split,
6462                            int descriptors,
6463                            bool constant_to_field,
6464                            Representation old_representation,
6465                            Representation new_representation,
6466                            HeapType* old_field_type,
6467                            HeapType* new_field_type);
6468
6469   static inline void SetPrototypeTransitions(
6470       Handle<Map> map,
6471       Handle<FixedArray> prototype_transitions);
6472
6473   static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6474                                             Handle<Object> prototype);
6475   static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6476                                             Handle<Object> prototype,
6477                                             Handle<Map> target_map);
6478
6479   static const int kFastPropertiesSoftLimit = 12;
6480   static const int kMaxFastProperties = 128;
6481
6482   DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6483 };
6484
6485
6486 // An abstract superclass, a marker class really, for simple structure classes.
6487 // It doesn't carry much functionality but allows struct classes to be
6488 // identified in the type system.
6489 class Struct: public HeapObject {
6490  public:
6491   inline void InitializeBody(int object_size);
6492   DECLARE_CAST(Struct)
6493 };
6494
6495
6496 // A simple one-element struct, useful where smis need to be boxed.
6497 class Box : public Struct {
6498  public:
6499   // [value]: the boxed contents.
6500   DECL_ACCESSORS(value, Object)
6501
6502   DECLARE_CAST(Box)
6503
6504   // Dispatched behavior.
6505   DECLARE_PRINTER(Box)
6506   DECLARE_VERIFIER(Box)
6507
6508   static const int kValueOffset = HeapObject::kHeaderSize;
6509   static const int kSize = kValueOffset + kPointerSize;
6510
6511  private:
6512   DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6513 };
6514
6515
6516 // Script describes a script which has been added to the VM.
6517 class Script: public Struct {
6518  public:
6519   // Script types.
6520   enum Type {
6521     TYPE_NATIVE = 0,
6522     TYPE_EXTENSION = 1,
6523     TYPE_NORMAL = 2
6524   };
6525
6526   // Script compilation types.
6527   enum CompilationType {
6528     COMPILATION_TYPE_HOST = 0,
6529     COMPILATION_TYPE_EVAL = 1
6530   };
6531
6532   // Script compilation state.
6533   enum CompilationState {
6534     COMPILATION_STATE_INITIAL = 0,
6535     COMPILATION_STATE_COMPILED = 1
6536   };
6537
6538   // [source]: the script source.
6539   DECL_ACCESSORS(source, Object)
6540
6541   // [name]: the script name.
6542   DECL_ACCESSORS(name, Object)
6543
6544   // [id]: the script id.
6545   DECL_ACCESSORS(id, Smi)
6546
6547   // [line_offset]: script line offset in resource from where it was extracted.
6548   DECL_ACCESSORS(line_offset, Smi)
6549
6550   // [column_offset]: script column offset in resource from where it was
6551   // extracted.
6552   DECL_ACCESSORS(column_offset, Smi)
6553
6554   // [context_data]: context data for the context this script was compiled in.
6555   DECL_ACCESSORS(context_data, Object)
6556
6557   // [wrapper]: the wrapper cache.  This is either undefined or a WeakCell.
6558   DECL_ACCESSORS(wrapper, HeapObject)
6559
6560   // [type]: the script type.
6561   DECL_ACCESSORS(type, Smi)
6562
6563   // [line_ends]: FixedArray of line ends positions.
6564   DECL_ACCESSORS(line_ends, Object)
6565
6566   // [eval_from_shared]: for eval scripts the shared funcion info for the
6567   // function from which eval was called.
6568   DECL_ACCESSORS(eval_from_shared, Object)
6569
6570   // [eval_from_instructions_offset]: the instruction offset in the code for the
6571   // function from which eval was called where eval was called.
6572   DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6573
6574   // [flags]: Holds an exciting bitfield.
6575   DECL_ACCESSORS(flags, Smi)
6576
6577   // [source_url]: sourceURL from magic comment
6578   DECL_ACCESSORS(source_url, Object)
6579
6580   // [source_url]: sourceMappingURL magic comment
6581   DECL_ACCESSORS(source_mapping_url, Object)
6582
6583   // [compilation_type]: how the the script was compiled. Encoded in the
6584   // 'flags' field.
6585   inline CompilationType compilation_type();
6586   inline void set_compilation_type(CompilationType type);
6587
6588   // [compilation_state]: determines whether the script has already been
6589   // compiled. Encoded in the 'flags' field.
6590   inline CompilationState compilation_state();
6591   inline void set_compilation_state(CompilationState state);
6592
6593   // [is_embedder_debug_script]: An opaque boolean set by the embedder via
6594   // ScriptOrigin, and used by the embedder to make decisions about the
6595   // script's origin. V8 just passes this through. Encoded in
6596   // the 'flags' field.
6597   DECL_BOOLEAN_ACCESSORS(is_embedder_debug_script)
6598
6599   // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6600   // ScriptOrigin, and used by the embedder to make decisions about the
6601   // script's level of privilege. V8 just passes this through. Encoded in
6602   // the 'flags' field.
6603   DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6604
6605   DECLARE_CAST(Script)
6606
6607   // If script source is an external string, check that the underlying
6608   // resource is accessible. Otherwise, always return true.
6609   inline bool HasValidSource();
6610
6611   // Convert code position into column number.
6612   static int GetColumnNumber(Handle<Script> script, int code_pos);
6613
6614   // Convert code position into (zero-based) line number.
6615   // The non-handlified version does not allocate, but may be much slower.
6616   static int GetLineNumber(Handle<Script> script, int code_pos);
6617   int GetLineNumber(int code_pos);
6618
6619   static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6620
6621   // Init line_ends array with code positions of line ends inside script source.
6622   static void InitLineEnds(Handle<Script> script);
6623
6624   // Get the JS object wrapping the given script; create it if none exists.
6625   static Handle<JSObject> GetWrapper(Handle<Script> script);
6626
6627   // Dispatched behavior.
6628   DECLARE_PRINTER(Script)
6629   DECLARE_VERIFIER(Script)
6630
6631   static const int kSourceOffset = HeapObject::kHeaderSize;
6632   static const int kNameOffset = kSourceOffset + kPointerSize;
6633   static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6634   static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6635   static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6636   static const int kWrapperOffset = kContextOffset + kPointerSize;
6637   static const int kTypeOffset = kWrapperOffset + kPointerSize;
6638   static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6639   static const int kIdOffset = kLineEndsOffset + kPointerSize;
6640   static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6641   static const int kEvalFrominstructionsOffsetOffset =
6642       kEvalFromSharedOffset + kPointerSize;
6643   static const int kFlagsOffset =
6644       kEvalFrominstructionsOffsetOffset + kPointerSize;
6645   static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6646   static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6647   static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6648
6649  private:
6650   int GetLineNumberWithArray(int code_pos);
6651
6652   // Bit positions in the flags field.
6653   static const int kCompilationTypeBit = 0;
6654   static const int kCompilationStateBit = 1;
6655   static const int kIsEmbedderDebugScriptBit = 2;
6656   static const int kIsSharedCrossOriginBit = 3;
6657
6658   DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6659 };
6660
6661
6662 // List of builtin functions we want to identify to improve code
6663 // generation.
6664 //
6665 // Each entry has a name of a global object property holding an object
6666 // optionally followed by ".prototype", a name of a builtin function
6667 // on the object (the one the id is set for), and a label.
6668 //
6669 // Installation of ids for the selected builtin functions is handled
6670 // by the bootstrapper.
6671 #define FUNCTIONS_WITH_ID_LIST(V)                   \
6672   V(Array.prototype, indexOf, ArrayIndexOf)         \
6673   V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6674   V(Array.prototype, push, ArrayPush)               \
6675   V(Array.prototype, pop, ArrayPop)                 \
6676   V(Array.prototype, shift, ArrayShift)             \
6677   V(Function.prototype, apply, FunctionApply)       \
6678   V(Function.prototype, call, FunctionCall)         \
6679   V(String.prototype, charCodeAt, StringCharCodeAt) \
6680   V(String.prototype, charAt, StringCharAt)         \
6681   V(String, fromCharCode, StringFromCharCode)       \
6682   V(Math, random, MathRandom)                       \
6683   V(Math, floor, MathFloor)                         \
6684   V(Math, round, MathRound)                         \
6685   V(Math, ceil, MathCeil)                           \
6686   V(Math, abs, MathAbs)                             \
6687   V(Math, log, MathLog)                             \
6688   V(Math, exp, MathExp)                             \
6689   V(Math, sqrt, MathSqrt)                           \
6690   V(Math, pow, MathPow)                             \
6691   V(Math, max, MathMax)                             \
6692   V(Math, min, MathMin)                             \
6693   V(Math, cos, MathCos)                             \
6694   V(Math, sin, MathSin)                             \
6695   V(Math, tan, MathTan)                             \
6696   V(Math, acos, MathAcos)                           \
6697   V(Math, asin, MathAsin)                           \
6698   V(Math, atan, MathAtan)                           \
6699   V(Math, atan2, MathAtan2)                         \
6700   V(Math, imul, MathImul)                           \
6701   V(Math, clz32, MathClz32)                         \
6702   V(Math, fround, MathFround)
6703
6704 enum BuiltinFunctionId {
6705   kArrayCode,
6706 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name)    \
6707   k##name,
6708   FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6709 #undef DECLARE_FUNCTION_ID
6710   // Fake id for a special case of Math.pow. Note, it continues the
6711   // list of math functions.
6712   kMathPowHalf
6713 };
6714
6715
6716 // SharedFunctionInfo describes the JSFunction information that can be
6717 // shared by multiple instances of the function.
6718 class SharedFunctionInfo: public HeapObject {
6719  public:
6720   // [name]: Function name.
6721   DECL_ACCESSORS(name, Object)
6722
6723   // [code]: Function code.
6724   DECL_ACCESSORS(code, Code)
6725   inline void ReplaceCode(Code* code);
6726
6727   // [optimized_code_map]: Map from native context to optimized code
6728   // and a shared literals array or Smi(0) if none.
6729   DECL_ACCESSORS(optimized_code_map, Object)
6730
6731   // Returns index i of the entry with the specified context and OSR entry.
6732   // At position i - 1 is the context, position i the code, and i + 1 the
6733   // literals array.  Returns -1 when no matching entry is found.
6734   int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6735
6736   // Installs optimized code from the code map on the given closure. The
6737   // index has to be consistent with a search result as defined above.
6738   FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6739
6740   Code* GetCodeFromOptimizedCodeMap(int index);
6741
6742   // Clear optimized code map.
6743   void ClearOptimizedCodeMap();
6744
6745   // Removed a specific optimized code object from the optimized code map.
6746   void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6747
6748   // Unconditionally clear the type feedback vector (including vector ICs).
6749   void ClearTypeFeedbackInfo();
6750
6751   // Clear the type feedback vector with a more subtle policy at GC time.
6752   void ClearTypeFeedbackInfoAtGCTime();
6753
6754   // Trims the optimized code map after entries have been removed.
6755   void TrimOptimizedCodeMap(int shrink_by);
6756
6757   // Initialize a SharedFunctionInfo from a parsed function literal.
6758   static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6759                                       FunctionLiteral* lit);
6760
6761   // Add a new entry to the optimized code map.
6762   static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6763                                     Handle<Context> native_context,
6764                                     Handle<Code> code,
6765                                     Handle<FixedArray> literals,
6766                                     BailoutId osr_ast_id);
6767
6768   // Layout description of the optimized code map.
6769   static const int kNextMapIndex = 0;
6770   static const int kEntriesStart = 1;
6771   static const int kContextOffset = 0;
6772   static const int kCachedCodeOffset = 1;
6773   static const int kLiteralsOffset = 2;
6774   static const int kOsrAstIdOffset = 3;
6775   static const int kEntryLength = 4;
6776   static const int kInitialLength = kEntriesStart + kEntryLength;
6777
6778   // [scope_info]: Scope info.
6779   DECL_ACCESSORS(scope_info, ScopeInfo)
6780
6781   // [construct stub]: Code stub for constructing instances of this function.
6782   DECL_ACCESSORS(construct_stub, Code)
6783
6784   // Returns if this function has been compiled to native code yet.
6785   inline bool is_compiled();
6786
6787   // [length]: The function length - usually the number of declared parameters.
6788   // Use up to 2^30 parameters.
6789   inline int length() const;
6790   inline void set_length(int value);
6791
6792   // [internal formal parameter count]: The declared number of parameters.
6793   // For subclass constructors, also includes new.target.
6794   // The size of function's frame is internal_formal_parameter_count + 1.
6795   inline int internal_formal_parameter_count() const;
6796   inline void set_internal_formal_parameter_count(int value);
6797
6798   // Set the formal parameter count so the function code will be
6799   // called without using argument adaptor frames.
6800   inline void DontAdaptArguments();
6801
6802   // [expected_nof_properties]: Expected number of properties for the function.
6803   inline int expected_nof_properties() const;
6804   inline void set_expected_nof_properties(int value);
6805
6806   // [feedback_vector] - accumulates ast node feedback from full-codegen and
6807   // (increasingly) from crankshafted code where sufficient feedback isn't
6808   // available.
6809   DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6810
6811 #if TRACE_MAPS
6812   // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6813   // even if the GC moves this SharedFunctionInfo.
6814   inline int unique_id() const;
6815   inline void set_unique_id(int value);
6816 #endif
6817
6818   // [instance class name]: class name for instances.
6819   DECL_ACCESSORS(instance_class_name, Object)
6820
6821   // [function data]: This field holds some additional data for function.
6822   // Currently it either has FunctionTemplateInfo to make benefit the API
6823   // or Smi identifying a builtin function.
6824   // In the long run we don't want all functions to have this field but
6825   // we can fix that when we have a better model for storing hidden data
6826   // on objects.
6827   DECL_ACCESSORS(function_data, Object)
6828
6829   inline bool IsApiFunction();
6830   inline FunctionTemplateInfo* get_api_func_data();
6831   inline bool HasBuiltinFunctionId();
6832   inline BuiltinFunctionId builtin_function_id();
6833
6834   // [script info]: Script from which the function originates.
6835   DECL_ACCESSORS(script, Object)
6836
6837   // [num_literals]: Number of literals used by this function.
6838   inline int num_literals() const;
6839   inline void set_num_literals(int value);
6840
6841   // [start_position_and_type]: Field used to store both the source code
6842   // position, whether or not the function is a function expression,
6843   // and whether or not the function is a toplevel function. The two
6844   // least significants bit indicates whether the function is an
6845   // expression and the rest contains the source code position.
6846   inline int start_position_and_type() const;
6847   inline void set_start_position_and_type(int value);
6848
6849   // [debug info]: Debug information.
6850   DECL_ACCESSORS(debug_info, Object)
6851
6852   // [inferred name]: Name inferred from variable or property
6853   // assignment of this function. Used to facilitate debugging and
6854   // profiling of JavaScript code written in OO style, where almost
6855   // all functions are anonymous but are assigned to object
6856   // properties.
6857   DECL_ACCESSORS(inferred_name, String)
6858
6859   // The function's name if it is non-empty, otherwise the inferred name.
6860   String* DebugName();
6861
6862   // Position of the 'function' token in the script source.
6863   inline int function_token_position() const;
6864   inline void set_function_token_position(int function_token_position);
6865
6866   // Position of this function in the script source.
6867   inline int start_position() const;
6868   inline void set_start_position(int start_position);
6869
6870   // End position of this function in the script source.
6871   inline int end_position() const;
6872   inline void set_end_position(int end_position);
6873
6874   // Is this function a function expression in the source code.
6875   DECL_BOOLEAN_ACCESSORS(is_expression)
6876
6877   // Is this function a top-level function (scripts, evals).
6878   DECL_BOOLEAN_ACCESSORS(is_toplevel)
6879
6880   // Bit field containing various information collected by the compiler to
6881   // drive optimization.
6882   inline int compiler_hints() const;
6883   inline void set_compiler_hints(int value);
6884
6885   inline int ast_node_count() const;
6886   inline void set_ast_node_count(int count);
6887
6888   inline int profiler_ticks() const;
6889   inline void set_profiler_ticks(int ticks);
6890
6891   // Inline cache age is used to infer whether the function survived a context
6892   // disposal or not. In the former case we reset the opt_count.
6893   inline int ic_age();
6894   inline void set_ic_age(int age);
6895
6896   // Indicates if this function can be lazy compiled.
6897   // This is used to determine if we can safely flush code from a function
6898   // when doing GC if we expect that the function will no longer be used.
6899   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6900
6901   // Indicates if this function can be lazy compiled without a context.
6902   // This is used to determine if we can force compilation without reaching
6903   // the function through program execution but through other means (e.g. heap
6904   // iteration by the debugger).
6905   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6906
6907   // Indicates whether optimizations have been disabled for this
6908   // shared function info. If a function is repeatedly optimized or if
6909   // we cannot optimize the function we disable optimization to avoid
6910   // spending time attempting to optimize it again.
6911   DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6912
6913   // Indicates the language mode.
6914   inline LanguageMode language_mode();
6915   inline void set_language_mode(LanguageMode language_mode);
6916
6917   // False if the function definitely does not allocate an arguments object.
6918   DECL_BOOLEAN_ACCESSORS(uses_arguments)
6919
6920   // Indicates that this function uses a super property.
6921   // This is needed to set up the [[HomeObject]] on the function instance.
6922   DECL_BOOLEAN_ACCESSORS(uses_super_property)
6923
6924   // True if the function has any duplicated parameter names.
6925   DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6926
6927   // Indicates whether the function is a native function.
6928   // These needs special treatment in .call and .apply since
6929   // null passed as the receiver should not be translated to the
6930   // global object.
6931   DECL_BOOLEAN_ACCESSORS(native)
6932
6933   // Indicate that this builtin needs to be inlined in crankshaft.
6934   DECL_BOOLEAN_ACCESSORS(inline_builtin)
6935
6936   // Indicates that the function was created by the Function function.
6937   // Though it's anonymous, toString should treat it as if it had the name
6938   // "anonymous".  We don't set the name itself so that the system does not
6939   // see a binding for it.
6940   DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6941
6942   // Indicates whether the function is a bound function created using
6943   // the bind function.
6944   DECL_BOOLEAN_ACCESSORS(bound)
6945
6946   // Indicates that the function is anonymous (the name field can be set
6947   // through the API, which does not change this flag).
6948   DECL_BOOLEAN_ACCESSORS(is_anonymous)
6949
6950   // Is this a function or top-level/eval code.
6951   DECL_BOOLEAN_ACCESSORS(is_function)
6952
6953   // Indicates that code for this function cannot be cached.
6954   DECL_BOOLEAN_ACCESSORS(dont_cache)
6955
6956   // Indicates that code for this function cannot be flushed.
6957   DECL_BOOLEAN_ACCESSORS(dont_flush)
6958
6959   // Indicates that this function is a generator.
6960   DECL_BOOLEAN_ACCESSORS(is_generator)
6961
6962   // Indicates that this function is an arrow function.
6963   DECL_BOOLEAN_ACCESSORS(is_arrow)
6964
6965   // Indicates that this function is a concise method.
6966   DECL_BOOLEAN_ACCESSORS(is_concise_method)
6967
6968   // Indicates that this function is an accessor (getter or setter).
6969   DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6970
6971   // Indicates that this function is a default constructor.
6972   DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6973
6974   // Indicates that this function is an asm function.
6975   DECL_BOOLEAN_ACCESSORS(asm_function)
6976
6977   // Indicates that the the shared function info is deserialized from cache.
6978   DECL_BOOLEAN_ACCESSORS(deserialized)
6979
6980   inline FunctionKind kind();
6981   inline void set_kind(FunctionKind kind);
6982
6983   // Indicates whether or not the code in the shared function support
6984   // deoptimization.
6985   inline bool has_deoptimization_support();
6986
6987   // Enable deoptimization support through recompiled code.
6988   void EnableDeoptimizationSupport(Code* recompiled);
6989
6990   // Disable (further) attempted optimization of all functions sharing this
6991   // shared function info.
6992   void DisableOptimization(BailoutReason reason);
6993
6994   inline BailoutReason disable_optimization_reason();
6995
6996   // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6997   // code, returns whether it asserted (i.e., always true if assertions are
6998   // disabled).
6999   bool VerifyBailoutId(BailoutId id);
7000
7001   // [source code]: Source code for the function.
7002   bool HasSourceCode() const;
7003   Handle<Object> GetSourceCode();
7004
7005   // Number of times the function was optimized.
7006   inline int opt_count();
7007   inline void set_opt_count(int opt_count);
7008
7009   // Number of times the function was deoptimized.
7010   inline void set_deopt_count(int value);
7011   inline int deopt_count();
7012   inline void increment_deopt_count();
7013
7014   // Number of time we tried to re-enable optimization after it
7015   // was disabled due to high number of deoptimizations.
7016   inline void set_opt_reenable_tries(int value);
7017   inline int opt_reenable_tries();
7018
7019   inline void TryReenableOptimization();
7020
7021   // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7022   inline void set_counters(int value);
7023   inline int counters() const;
7024
7025   // Stores opt_count and bailout_reason as bit-fields.
7026   inline void set_opt_count_and_bailout_reason(int value);
7027   inline int opt_count_and_bailout_reason() const;
7028
7029   void set_disable_optimization_reason(BailoutReason reason) {
7030     set_opt_count_and_bailout_reason(
7031         DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7032                                                reason));
7033   }
7034
7035   // Check whether or not this function is inlineable.
7036   bool IsInlineable();
7037
7038   // Source size of this function.
7039   int SourceSize();
7040
7041   // Calculate the instance size.
7042   int CalculateInstanceSize();
7043
7044   // Calculate the number of in-object properties.
7045   int CalculateInObjectProperties();
7046
7047   inline bool is_simple_parameter_list();
7048
7049   // Dispatched behavior.
7050   DECLARE_PRINTER(SharedFunctionInfo)
7051   DECLARE_VERIFIER(SharedFunctionInfo)
7052
7053   void ResetForNewContext(int new_ic_age);
7054
7055   DECLARE_CAST(SharedFunctionInfo)
7056
7057   // Constants.
7058   static const int kDontAdaptArgumentsSentinel = -1;
7059
7060   // Layout description.
7061   // Pointer fields.
7062   static const int kNameOffset = HeapObject::kHeaderSize;
7063   static const int kCodeOffset = kNameOffset + kPointerSize;
7064   static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7065   static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7066   static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7067   static const int kInstanceClassNameOffset =
7068       kConstructStubOffset + kPointerSize;
7069   static const int kFunctionDataOffset =
7070       kInstanceClassNameOffset + kPointerSize;
7071   static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7072   static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7073   static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7074   static const int kFeedbackVectorOffset =
7075       kInferredNameOffset + kPointerSize;
7076 #if TRACE_MAPS
7077   static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
7078   static const int kLastPointerFieldOffset = kUniqueIdOffset;
7079 #else
7080   // Just to not break the postmortrem support with conditional offsets
7081   static const int kUniqueIdOffset = kFeedbackVectorOffset;
7082   static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
7083 #endif
7084
7085 #if V8_HOST_ARCH_32_BIT
7086   // Smi fields.
7087   static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
7088   static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7089   static const int kExpectedNofPropertiesOffset =
7090       kFormalParameterCountOffset + kPointerSize;
7091   static const int kNumLiteralsOffset =
7092       kExpectedNofPropertiesOffset + kPointerSize;
7093   static const int kStartPositionAndTypeOffset =
7094       kNumLiteralsOffset + kPointerSize;
7095   static const int kEndPositionOffset =
7096       kStartPositionAndTypeOffset + kPointerSize;
7097   static const int kFunctionTokenPositionOffset =
7098       kEndPositionOffset + kPointerSize;
7099   static const int kCompilerHintsOffset =
7100       kFunctionTokenPositionOffset + kPointerSize;
7101   static const int kOptCountAndBailoutReasonOffset =
7102       kCompilerHintsOffset + kPointerSize;
7103   static const int kCountersOffset =
7104       kOptCountAndBailoutReasonOffset + kPointerSize;
7105   static const int kAstNodeCountOffset =
7106       kCountersOffset + kPointerSize;
7107   static const int kProfilerTicksOffset =
7108       kAstNodeCountOffset + kPointerSize;
7109
7110   // Total size.
7111   static const int kSize = kProfilerTicksOffset + kPointerSize;
7112 #else
7113   // The only reason to use smi fields instead of int fields
7114   // is to allow iteration without maps decoding during
7115   // garbage collections.
7116   // To avoid wasting space on 64-bit architectures we use
7117   // the following trick: we group integer fields into pairs
7118 // The least significant integer in each pair is shifted left by 1.
7119 // By doing this we guarantee that LSB of each kPointerSize aligned
7120 // word is not set and thus this word cannot be treated as pointer
7121 // to HeapObject during old space traversal.
7122 #if V8_TARGET_LITTLE_ENDIAN
7123   static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
7124   static const int kFormalParameterCountOffset =
7125       kLengthOffset + kIntSize;
7126
7127   static const int kExpectedNofPropertiesOffset =
7128       kFormalParameterCountOffset + kIntSize;
7129   static const int kNumLiteralsOffset =
7130       kExpectedNofPropertiesOffset + kIntSize;
7131
7132   static const int kEndPositionOffset =
7133       kNumLiteralsOffset + kIntSize;
7134   static const int kStartPositionAndTypeOffset =
7135       kEndPositionOffset + kIntSize;
7136
7137   static const int kFunctionTokenPositionOffset =
7138       kStartPositionAndTypeOffset + kIntSize;
7139   static const int kCompilerHintsOffset =
7140       kFunctionTokenPositionOffset + kIntSize;
7141
7142   static const int kOptCountAndBailoutReasonOffset =
7143       kCompilerHintsOffset + kIntSize;
7144   static const int kCountersOffset =
7145       kOptCountAndBailoutReasonOffset + kIntSize;
7146
7147   static const int kAstNodeCountOffset =
7148       kCountersOffset + kIntSize;
7149   static const int kProfilerTicksOffset =
7150       kAstNodeCountOffset + kIntSize;
7151
7152   // Total size.
7153   static const int kSize = kProfilerTicksOffset + kIntSize;
7154
7155 #elif V8_TARGET_BIG_ENDIAN
7156   static const int kFormalParameterCountOffset =
7157       kLastPointerFieldOffset + kPointerSize;
7158   static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7159
7160   static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7161   static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7162
7163   static const int kStartPositionAndTypeOffset =
7164       kExpectedNofPropertiesOffset + kIntSize;
7165   static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7166
7167   static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7168   static const int kFunctionTokenPositionOffset =
7169       kCompilerHintsOffset + kIntSize;
7170
7171   static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7172   static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7173
7174   static const int kProfilerTicksOffset =
7175       kOptCountAndBailoutReasonOffset + kIntSize;
7176   static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7177
7178   // Total size.
7179   static const int kSize = kAstNodeCountOffset + kIntSize;
7180
7181 #else
7182 #error Unknown byte ordering
7183 #endif  // Big endian
7184 #endif  // 64-bit
7185
7186
7187   static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7188
7189   typedef FixedBodyDescriptor<kNameOffset,
7190                               kLastPointerFieldOffset + kPointerSize,
7191                               kSize> BodyDescriptor;
7192
7193   // Bit positions in start_position_and_type.
7194   // The source code start position is in the 30 most significant bits of
7195   // the start_position_and_type field.
7196   static const int kIsExpressionBit    = 0;
7197   static const int kIsTopLevelBit      = 1;
7198   static const int kStartPositionShift = 2;
7199   static const int kStartPositionMask  = ~((1 << kStartPositionShift) - 1);
7200
7201   // Bit positions in compiler_hints.
7202   enum CompilerHints {
7203     kAllowLazyCompilation,
7204     kAllowLazyCompilationWithoutContext,
7205     kOptimizationDisabled,
7206     kStrictModeFunction,
7207     kStrongModeFunction,
7208     kUsesArguments,
7209     kUsesSuperProperty,
7210     kHasDuplicateParameters,
7211     kNative,
7212     kInlineBuiltin,
7213     kBoundFunction,
7214     kIsAnonymous,
7215     kNameShouldPrintAsAnonymous,
7216     kIsFunction,
7217     kDontCache,
7218     kDontFlush,
7219     kIsArrow,
7220     kIsGenerator,
7221     kIsConciseMethod,
7222     kIsAccessorFunction,
7223     kIsDefaultConstructor,
7224     kIsBaseConstructor,
7225     kIsSubclassConstructor,
7226     kIsAsmFunction,
7227     kDeserialized,
7228     kCompilerHintsCount  // Pseudo entry
7229   };
7230   // Add hints for other modes when they're added.
7231   STATIC_ASSERT(LANGUAGE_END == 3);
7232
7233   class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 7> {};
7234
7235   class DeoptCountBits : public BitField<int, 0, 4> {};
7236   class OptReenableTriesBits : public BitField<int, 4, 18> {};
7237   class ICAgeBits : public BitField<int, 22, 8> {};
7238
7239   class OptCountBits : public BitField<int, 0, 22> {};
7240   class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7241
7242  private:
7243 #if V8_HOST_ARCH_32_BIT
7244   // On 32 bit platforms, compiler hints is a smi.
7245   static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7246   static const int kCompilerHintsSize = kPointerSize;
7247 #else
7248   // On 64 bit platforms, compiler hints is not a smi, see comment above.
7249   static const int kCompilerHintsSmiTagSize = 0;
7250   static const int kCompilerHintsSize = kIntSize;
7251 #endif
7252
7253   STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7254                 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7255
7256  public:
7257   // Constants for optimizing codegen for strict mode function and
7258   // native tests.
7259   // Allows to use byte-width instructions.
7260   static const int kStrictModeBitWithinByte =
7261       (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7262
7263   static const int kNativeBitWithinByte =
7264       (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7265
7266 #if defined(V8_TARGET_LITTLE_ENDIAN)
7267   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7268       (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7269   static const int kNativeByteOffset = kCompilerHintsOffset +
7270       (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7271 #elif defined(V8_TARGET_BIG_ENDIAN)
7272   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7273       (kCompilerHintsSize - 1) -
7274       ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7275   static const int kNativeByteOffset = kCompilerHintsOffset +
7276       (kCompilerHintsSize - 1) -
7277       ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7278 #else
7279 #error Unknown byte ordering
7280 #endif
7281
7282  private:
7283   DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7284 };
7285
7286
7287 // Printing support.
7288 struct SourceCodeOf {
7289   explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7290       : value(v), max_length(max) {}
7291   const SharedFunctionInfo* value;
7292   int max_length;
7293 };
7294
7295
7296 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7297
7298
7299 class JSGeneratorObject: public JSObject {
7300  public:
7301   // [function]: The function corresponding to this generator object.
7302   DECL_ACCESSORS(function, JSFunction)
7303
7304   // [context]: The context of the suspended computation.
7305   DECL_ACCESSORS(context, Context)
7306
7307   // [receiver]: The receiver of the suspended computation.
7308   DECL_ACCESSORS(receiver, Object)
7309
7310   // [continuation]: Offset into code of continuation.
7311   //
7312   // A positive offset indicates a suspended generator.  The special
7313   // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7314   // cannot be resumed.
7315   inline int continuation() const;
7316   inline void set_continuation(int continuation);
7317   inline bool is_closed();
7318   inline bool is_executing();
7319   inline bool is_suspended();
7320
7321   // [operand_stack]: Saved operand stack.
7322   DECL_ACCESSORS(operand_stack, FixedArray)
7323
7324   // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7325   // if the captured activation had no stack handler.
7326   inline int stack_handler_index() const;
7327   inline void set_stack_handler_index(int stack_handler_index);
7328
7329   DECLARE_CAST(JSGeneratorObject)
7330
7331   // Dispatched behavior.
7332   DECLARE_PRINTER(JSGeneratorObject)
7333   DECLARE_VERIFIER(JSGeneratorObject)
7334
7335   // Magic sentinel values for the continuation.
7336   static const int kGeneratorExecuting = -1;
7337   static const int kGeneratorClosed = 0;
7338
7339   // Layout description.
7340   static const int kFunctionOffset = JSObject::kHeaderSize;
7341   static const int kContextOffset = kFunctionOffset + kPointerSize;
7342   static const int kReceiverOffset = kContextOffset + kPointerSize;
7343   static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7344   static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7345   static const int kStackHandlerIndexOffset =
7346       kOperandStackOffset + kPointerSize;
7347   static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7348
7349   // Resume mode, for use by runtime functions.
7350   enum ResumeMode { NEXT, THROW };
7351
7352   // Yielding from a generator returns an object with the following inobject
7353   // properties.  See Context::iterator_result_map() for the map.
7354   static const int kResultValuePropertyIndex = 0;
7355   static const int kResultDonePropertyIndex = 1;
7356   static const int kResultPropertyCount = 2;
7357
7358   static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7359   static const int kResultDonePropertyOffset =
7360       kResultValuePropertyOffset + kPointerSize;
7361   static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7362
7363  private:
7364   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7365 };
7366
7367
7368 // Representation for module instance objects.
7369 class JSModule: public JSObject {
7370  public:
7371   // [context]: the context holding the module's locals, or undefined if none.
7372   DECL_ACCESSORS(context, Object)
7373
7374   // [scope_info]: Scope info.
7375   DECL_ACCESSORS(scope_info, ScopeInfo)
7376
7377   DECLARE_CAST(JSModule)
7378
7379   // Dispatched behavior.
7380   DECLARE_PRINTER(JSModule)
7381   DECLARE_VERIFIER(JSModule)
7382
7383   // Layout description.
7384   static const int kContextOffset = JSObject::kHeaderSize;
7385   static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7386   static const int kSize = kScopeInfoOffset + kPointerSize;
7387
7388  private:
7389   DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7390 };
7391
7392
7393 // JSFunction describes JavaScript functions.
7394 class JSFunction: public JSObject {
7395  public:
7396   // [prototype_or_initial_map]:
7397   DECL_ACCESSORS(prototype_or_initial_map, Object)
7398
7399   // [shared]: The information about the function that
7400   // can be shared by instances.
7401   DECL_ACCESSORS(shared, SharedFunctionInfo)
7402
7403   // [context]: The context for this function.
7404   inline Context* context();
7405   inline void set_context(Object* context);
7406   inline JSObject* global_proxy();
7407
7408   // [code]: The generated code object for this function.  Executed
7409   // when the function is invoked, e.g. foo() or new foo(). See
7410   // [[Call]] and [[Construct]] description in ECMA-262, section
7411   // 8.6.2, page 27.
7412   inline Code* code();
7413   inline void set_code(Code* code);
7414   inline void set_code_no_write_barrier(Code* code);
7415   inline void ReplaceCode(Code* code);
7416
7417   // Tells whether this function is builtin.
7418   inline bool IsBuiltin();
7419
7420   // Tells whether this function is defined in a native script.
7421   inline bool IsFromNativeScript();
7422
7423   // Tells whether this function is defined in an extension script.
7424   inline bool IsFromExtensionScript();
7425
7426   // Tells whether or not the function needs arguments adaption.
7427   inline bool NeedsArgumentsAdaption();
7428
7429   // Tells whether or not this function has been optimized.
7430   inline bool IsOptimized();
7431
7432   // Tells whether or not this function can be optimized.
7433   inline bool IsOptimizable();
7434
7435   // Mark this function for lazy recompilation. The function will be
7436   // recompiled the next time it is executed.
7437   void MarkForOptimization();
7438   void AttemptConcurrentOptimization();
7439
7440   // Tells whether or not the function is already marked for lazy
7441   // recompilation.
7442   inline bool IsMarkedForOptimization();
7443   inline bool IsMarkedForConcurrentOptimization();
7444
7445   // Tells whether or not the function is on the concurrent recompilation queue.
7446   inline bool IsInOptimizationQueue();
7447
7448   // Inobject slack tracking is the way to reclaim unused inobject space.
7449   //
7450   // The instance size is initially determined by adding some slack to
7451   // expected_nof_properties (to allow for a few extra properties added
7452   // after the constructor). There is no guarantee that the extra space
7453   // will not be wasted.
7454   //
7455   // Here is the algorithm to reclaim the unused inobject space:
7456   // - Detect the first constructor call for this JSFunction.
7457   //   When it happens enter the "in progress" state: initialize construction
7458   //   counter in the initial_map.
7459   // - While the tracking is in progress create objects filled with
7460   //   one_pointer_filler_map instead of undefined_value. This way they can be
7461   //   resized quickly and safely.
7462   // - Once enough objects have been created  compute the 'slack'
7463   //   (traverse the map transition tree starting from the
7464   //   initial_map and find the lowest value of unused_property_fields).
7465   // - Traverse the transition tree again and decrease the instance size
7466   //   of every map. Existing objects will resize automatically (they are
7467   //   filled with one_pointer_filler_map). All further allocations will
7468   //   use the adjusted instance size.
7469   // - SharedFunctionInfo's expected_nof_properties left unmodified since
7470   //   allocations made using different closures could actually create different
7471   //   kind of objects (see prototype inheritance pattern).
7472   //
7473   //  Important: inobject slack tracking is not attempted during the snapshot
7474   //  creation.
7475
7476   // True if the initial_map is set and the object constructions countdown
7477   // counter is not zero.
7478   static const int kGenerousAllocationCount =
7479       Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7480   inline bool IsInobjectSlackTrackingInProgress();
7481
7482   // Starts the tracking.
7483   // Initializes object constructions countdown counter in the initial map.
7484   void StartInobjectSlackTracking();
7485
7486   // Completes the tracking.
7487   void CompleteInobjectSlackTracking();
7488
7489   // [literals_or_bindings]: Fixed array holding either
7490   // the materialized literals or the bindings of a bound function.
7491   //
7492   // If the function contains object, regexp or array literals, the
7493   // literals array prefix contains the object, regexp, and array
7494   // function to be used when creating these literals.  This is
7495   // necessary so that we do not dynamically lookup the object, regexp
7496   // or array functions.  Performing a dynamic lookup, we might end up
7497   // using the functions from a new context that we should not have
7498   // access to.
7499   //
7500   // On bound functions, the array is a (copy-on-write) fixed-array containing
7501   // the function that was bound, bound this-value and any bound
7502   // arguments. Bound functions never contain literals.
7503   DECL_ACCESSORS(literals_or_bindings, FixedArray)
7504
7505   inline FixedArray* literals();
7506   inline void set_literals(FixedArray* literals);
7507
7508   inline FixedArray* function_bindings();
7509   inline void set_function_bindings(FixedArray* bindings);
7510
7511   // The initial map for an object created by this constructor.
7512   inline Map* initial_map();
7513   static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7514                             Handle<Object> prototype);
7515   inline bool has_initial_map();
7516   static void EnsureHasInitialMap(Handle<JSFunction> function);
7517
7518   // Get and set the prototype property on a JSFunction. If the
7519   // function has an initial map the prototype is set on the initial
7520   // map. Otherwise, the prototype is put in the initial map field
7521   // until an initial map is needed.
7522   inline bool has_prototype();
7523   inline bool has_instance_prototype();
7524   inline Object* prototype();
7525   inline Object* instance_prototype();
7526   static void SetPrototype(Handle<JSFunction> function,
7527                            Handle<Object> value);
7528   static void SetInstancePrototype(Handle<JSFunction> function,
7529                                    Handle<Object> value);
7530
7531   // Creates a new closure for the fucntion with the same bindings,
7532   // bound values, and prototype. An equivalent of spec operations
7533   // ``CloneMethod`` and ``CloneBoundFunction``.
7534   static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7535
7536   // After prototype is removed, it will not be created when accessed, and
7537   // [[Construct]] from this function will not be allowed.
7538   bool RemovePrototype();
7539   inline bool should_have_prototype();
7540
7541   // Accessor for this function's initial map's [[class]]
7542   // property. This is primarily used by ECMA native functions.  This
7543   // method sets the class_name field of this function's initial map
7544   // to a given value. It creates an initial map if this function does
7545   // not have one. Note that this method does not copy the initial map
7546   // if it has one already, but simply replaces it with the new value.
7547   // Instances created afterwards will have a map whose [[class]] is
7548   // set to 'value', but there is no guarantees on instances created
7549   // before.
7550   void SetInstanceClassName(String* name);
7551
7552   // Returns if this function has been compiled to native code yet.
7553   inline bool is_compiled();
7554
7555   // Returns `false` if formal parameters include rest parameters, optional
7556   // parameters, or destructuring parameters.
7557   // TODO(caitp): make this a flag set during parsing
7558   inline bool is_simple_parameter_list();
7559
7560   // [next_function_link]: Links functions into various lists, e.g. the list
7561   // of optimized functions hanging off the native_context. The CodeFlusher
7562   // uses this link to chain together flushing candidates. Treated weakly
7563   // by the garbage collector.
7564   DECL_ACCESSORS(next_function_link, Object)
7565
7566   // Prints the name of the function using PrintF.
7567   void PrintName(FILE* out = stdout);
7568
7569   DECLARE_CAST(JSFunction)
7570
7571   // Iterates the objects, including code objects indirectly referenced
7572   // through pointers to the first instruction in the code object.
7573   void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7574
7575   // Dispatched behavior.
7576   DECLARE_PRINTER(JSFunction)
7577   DECLARE_VERIFIER(JSFunction)
7578
7579   // Returns the number of allocated literals.
7580   inline int NumberOfLiterals();
7581
7582   // Retrieve the native context from a function's literal array.
7583   static Context* NativeContextFromLiterals(FixedArray* literals);
7584
7585   // Used for flags such as --hydrogen-filter.
7586   bool PassesFilter(const char* raw_filter);
7587
7588   // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7589   // kSize) is weak and has special handling during garbage collection.
7590   static const int kCodeEntryOffset = JSObject::kHeaderSize;
7591   static const int kPrototypeOrInitialMapOffset =
7592       kCodeEntryOffset + kPointerSize;
7593   static const int kSharedFunctionInfoOffset =
7594       kPrototypeOrInitialMapOffset + kPointerSize;
7595   static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7596   static const int kLiteralsOffset = kContextOffset + kPointerSize;
7597   static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7598   static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7599   static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7600
7601   // Layout of the literals array.
7602   static const int kLiteralsPrefixSize = 1;
7603   static const int kLiteralNativeContextIndex = 0;
7604
7605   // Layout of the bound-function binding array.
7606   static const int kBoundFunctionIndex = 0;
7607   static const int kBoundThisIndex = 1;
7608   static const int kBoundArgumentsStartIndex = 2;
7609
7610  private:
7611   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7612 };
7613
7614
7615 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7616 // and the prototype is hidden. JSGlobalProxy always delegates
7617 // property accesses to its prototype if the prototype is not null.
7618 //
7619 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7620 //
7621 // Accessing a JSGlobalProxy requires security check.
7622
7623 class JSGlobalProxy : public JSObject {
7624  public:
7625   // [native_context]: the owner native context of this global proxy object.
7626   // It is null value if this object is not used by any context.
7627   DECL_ACCESSORS(native_context, Object)
7628
7629   // [hash]: The hash code property (undefined if not initialized yet).
7630   DECL_ACCESSORS(hash, Object)
7631
7632   DECLARE_CAST(JSGlobalProxy)
7633
7634   inline bool IsDetachedFrom(GlobalObject* global) const;
7635
7636   // Dispatched behavior.
7637   DECLARE_PRINTER(JSGlobalProxy)
7638   DECLARE_VERIFIER(JSGlobalProxy)
7639
7640   // Layout description.
7641   static const int kNativeContextOffset = JSObject::kHeaderSize;
7642   static const int kHashOffset = kNativeContextOffset + kPointerSize;
7643   static const int kSize = kHashOffset + kPointerSize;
7644
7645  private:
7646   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7647 };
7648
7649
7650 // Forward declaration.
7651 class JSBuiltinsObject;
7652
7653 // Common super class for JavaScript global objects and the special
7654 // builtins global objects.
7655 class GlobalObject: public JSObject {
7656  public:
7657   // [builtins]: the object holding the runtime routines written in JS.
7658   DECL_ACCESSORS(builtins, JSBuiltinsObject)
7659
7660   // [native context]: the natives corresponding to this global object.
7661   DECL_ACCESSORS(native_context, Context)
7662
7663   // [global proxy]: the global proxy object of the context
7664   DECL_ACCESSORS(global_proxy, JSObject)
7665
7666   DECLARE_CAST(GlobalObject)
7667
7668   static void InvalidatePropertyCell(Handle<GlobalObject> object,
7669                                      Handle<Name> name);
7670   // Ensure that the global object has a cell for the given property name.
7671   static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7672                                                  Handle<Name> name);
7673
7674   // Layout description.
7675   static const int kBuiltinsOffset = JSObject::kHeaderSize;
7676   static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7677   static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7678   static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7679
7680  private:
7681   DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7682 };
7683
7684
7685 // JavaScript global object.
7686 class JSGlobalObject: public GlobalObject {
7687  public:
7688   DECLARE_CAST(JSGlobalObject)
7689
7690   inline bool IsDetached();
7691
7692   // Dispatched behavior.
7693   DECLARE_PRINTER(JSGlobalObject)
7694   DECLARE_VERIFIER(JSGlobalObject)
7695
7696   // Layout description.
7697   static const int kSize = GlobalObject::kHeaderSize;
7698
7699  private:
7700   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7701 };
7702
7703
7704 // Builtins global object which holds the runtime routines written in
7705 // JavaScript.
7706 class JSBuiltinsObject: public GlobalObject {
7707  public:
7708   // Accessors for the runtime routines written in JavaScript.
7709   inline Object* javascript_builtin(Builtins::JavaScript id);
7710   inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7711
7712   // Accessors for code of the runtime routines written in JavaScript.
7713   inline Code* javascript_builtin_code(Builtins::JavaScript id);
7714   inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7715
7716   DECLARE_CAST(JSBuiltinsObject)
7717
7718   // Dispatched behavior.
7719   DECLARE_PRINTER(JSBuiltinsObject)
7720   DECLARE_VERIFIER(JSBuiltinsObject)
7721
7722   // Layout description.  The size of the builtins object includes
7723   // room for two pointers per runtime routine written in javascript
7724   // (function and code object).
7725   static const int kJSBuiltinsCount = Builtins::id_count;
7726   static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7727   static const int kJSBuiltinsCodeOffset =
7728       GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7729   static const int kSize =
7730       kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7731
7732   static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7733     return kJSBuiltinsOffset + id * kPointerSize;
7734   }
7735
7736   static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7737     return kJSBuiltinsCodeOffset + id * kPointerSize;
7738   }
7739
7740  private:
7741   DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7742 };
7743
7744
7745 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7746 class JSValue: public JSObject {
7747  public:
7748   // [value]: the object being wrapped.
7749   DECL_ACCESSORS(value, Object)
7750
7751   DECLARE_CAST(JSValue)
7752
7753   // Dispatched behavior.
7754   DECLARE_PRINTER(JSValue)
7755   DECLARE_VERIFIER(JSValue)
7756
7757   // Layout description.
7758   static const int kValueOffset = JSObject::kHeaderSize;
7759   static const int kSize = kValueOffset + kPointerSize;
7760
7761  private:
7762   DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7763 };
7764
7765
7766 class DateCache;
7767
7768 // Representation for JS date objects.
7769 class JSDate: public JSObject {
7770  public:
7771   // If one component is NaN, all of them are, indicating a NaN time value.
7772   // [value]: the time value.
7773   DECL_ACCESSORS(value, Object)
7774   // [year]: caches year. Either undefined, smi, or NaN.
7775   DECL_ACCESSORS(year, Object)
7776   // [month]: caches month. Either undefined, smi, or NaN.
7777   DECL_ACCESSORS(month, Object)
7778   // [day]: caches day. Either undefined, smi, or NaN.
7779   DECL_ACCESSORS(day, Object)
7780   // [weekday]: caches day of week. Either undefined, smi, or NaN.
7781   DECL_ACCESSORS(weekday, Object)
7782   // [hour]: caches hours. Either undefined, smi, or NaN.
7783   DECL_ACCESSORS(hour, Object)
7784   // [min]: caches minutes. Either undefined, smi, or NaN.
7785   DECL_ACCESSORS(min, Object)
7786   // [sec]: caches seconds. Either undefined, smi, or NaN.
7787   DECL_ACCESSORS(sec, Object)
7788   // [cache stamp]: sample of the date cache stamp at the
7789   // moment when chached fields were cached.
7790   DECL_ACCESSORS(cache_stamp, Object)
7791
7792   DECLARE_CAST(JSDate)
7793
7794   // Returns the date field with the specified index.
7795   // See FieldIndex for the list of date fields.
7796   static Object* GetField(Object* date, Smi* index);
7797
7798   void SetValue(Object* value, bool is_value_nan);
7799
7800
7801   // Dispatched behavior.
7802   DECLARE_PRINTER(JSDate)
7803   DECLARE_VERIFIER(JSDate)
7804
7805   // The order is important. It must be kept in sync with date macros
7806   // in macros.py.
7807   enum FieldIndex {
7808     kDateValue,
7809     kYear,
7810     kMonth,
7811     kDay,
7812     kWeekday,
7813     kHour,
7814     kMinute,
7815     kSecond,
7816     kFirstUncachedField,
7817     kMillisecond = kFirstUncachedField,
7818     kDays,
7819     kTimeInDay,
7820     kFirstUTCField,
7821     kYearUTC = kFirstUTCField,
7822     kMonthUTC,
7823     kDayUTC,
7824     kWeekdayUTC,
7825     kHourUTC,
7826     kMinuteUTC,
7827     kSecondUTC,
7828     kMillisecondUTC,
7829     kDaysUTC,
7830     kTimeInDayUTC,
7831     kTimezoneOffset
7832   };
7833
7834   // Layout description.
7835   static const int kValueOffset = JSObject::kHeaderSize;
7836   static const int kYearOffset = kValueOffset + kPointerSize;
7837   static const int kMonthOffset = kYearOffset + kPointerSize;
7838   static const int kDayOffset = kMonthOffset + kPointerSize;
7839   static const int kWeekdayOffset = kDayOffset + kPointerSize;
7840   static const int kHourOffset = kWeekdayOffset  + kPointerSize;
7841   static const int kMinOffset = kHourOffset + kPointerSize;
7842   static const int kSecOffset = kMinOffset + kPointerSize;
7843   static const int kCacheStampOffset = kSecOffset + kPointerSize;
7844   static const int kSize = kCacheStampOffset + kPointerSize;
7845
7846  private:
7847   inline Object* DoGetField(FieldIndex index);
7848
7849   Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7850
7851   // Computes and caches the cacheable fields of the date.
7852   inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7853
7854
7855   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7856 };
7857
7858
7859 // Representation of message objects used for error reporting through
7860 // the API. The messages are formatted in JavaScript so this object is
7861 // a real JavaScript object. The information used for formatting the
7862 // error messages are not directly accessible from JavaScript to
7863 // prevent leaking information to user code called during error
7864 // formatting.
7865 class JSMessageObject: public JSObject {
7866  public:
7867   // [type]: the type of error message.
7868   DECL_ACCESSORS(type, String)
7869
7870   // [arguments]: the arguments for formatting the error message.
7871   DECL_ACCESSORS(arguments, JSArray)
7872
7873   // [script]: the script from which the error message originated.
7874   DECL_ACCESSORS(script, Object)
7875
7876   // [stack_frames]: an array of stack frames for this error object.
7877   DECL_ACCESSORS(stack_frames, Object)
7878
7879   // [start_position]: the start position in the script for the error message.
7880   inline int start_position() const;
7881   inline void set_start_position(int value);
7882
7883   // [end_position]: the end position in the script for the error message.
7884   inline int end_position() const;
7885   inline void set_end_position(int value);
7886
7887   DECLARE_CAST(JSMessageObject)
7888
7889   // Dispatched behavior.
7890   DECLARE_PRINTER(JSMessageObject)
7891   DECLARE_VERIFIER(JSMessageObject)
7892
7893   // Layout description.
7894   static const int kTypeOffset = JSObject::kHeaderSize;
7895   static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7896   static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7897   static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7898   static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7899   static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7900   static const int kSize = kEndPositionOffset + kPointerSize;
7901
7902   typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7903                               kStackFramesOffset + kPointerSize,
7904                               kSize> BodyDescriptor;
7905 };
7906
7907
7908 // Regular expressions
7909 // The regular expression holds a single reference to a FixedArray in
7910 // the kDataOffset field.
7911 // The FixedArray contains the following data:
7912 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7913 // - reference to the original source string
7914 // - reference to the original flag string
7915 // If it is an atom regexp
7916 // - a reference to a literal string to search for
7917 // If it is an irregexp regexp:
7918 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7919 // used for tracking the last usage (used for code flushing).
7920 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7921 // used for tracking the last usage (used for code flushing)..
7922 // - max number of registers used by irregexp implementations.
7923 // - number of capture registers (output values) of the regexp.
7924 class JSRegExp: public JSObject {
7925  public:
7926   // Meaning of Type:
7927   // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7928   // ATOM: A simple string to match against using an indexOf operation.
7929   // IRREGEXP: Compiled with Irregexp.
7930   // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7931   enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7932   enum Flag {
7933     NONE = 0,
7934     GLOBAL = 1,
7935     IGNORE_CASE = 2,
7936     MULTILINE = 4,
7937     STICKY = 8,
7938     UNICODE_ESCAPES = 16
7939   };
7940
7941   class Flags {
7942    public:
7943     explicit Flags(uint32_t value) : value_(value) { }
7944     bool is_global() { return (value_ & GLOBAL) != 0; }
7945     bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7946     bool is_multiline() { return (value_ & MULTILINE) != 0; }
7947     bool is_sticky() { return (value_ & STICKY) != 0; }
7948     bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7949     uint32_t value() { return value_; }
7950    private:
7951     uint32_t value_;
7952   };
7953
7954   DECL_ACCESSORS(data, Object)
7955
7956   inline Type TypeTag();
7957   inline int CaptureCount();
7958   inline Flags GetFlags();
7959   inline String* Pattern();
7960   inline Object* DataAt(int index);
7961   // Set implementation data after the object has been prepared.
7962   inline void SetDataAt(int index, Object* value);
7963
7964   static int code_index(bool is_latin1) {
7965     if (is_latin1) {
7966       return kIrregexpLatin1CodeIndex;
7967     } else {
7968       return kIrregexpUC16CodeIndex;
7969     }
7970   }
7971
7972   static int saved_code_index(bool is_latin1) {
7973     if (is_latin1) {
7974       return kIrregexpLatin1CodeSavedIndex;
7975     } else {
7976       return kIrregexpUC16CodeSavedIndex;
7977     }
7978   }
7979
7980   DECLARE_CAST(JSRegExp)
7981
7982   // Dispatched behavior.
7983   DECLARE_VERIFIER(JSRegExp)
7984
7985   static const int kDataOffset = JSObject::kHeaderSize;
7986   static const int kSize = kDataOffset + kPointerSize;
7987
7988   // Indices in the data array.
7989   static const int kTagIndex = 0;
7990   static const int kSourceIndex = kTagIndex + 1;
7991   static const int kFlagsIndex = kSourceIndex + 1;
7992   static const int kDataIndex = kFlagsIndex + 1;
7993   // The data fields are used in different ways depending on the
7994   // value of the tag.
7995   // Atom regexps (literal strings).
7996   static const int kAtomPatternIndex = kDataIndex;
7997
7998   static const int kAtomDataSize = kAtomPatternIndex + 1;
7999
8000   // Irregexp compiled code or bytecode for Latin1. If compilation
8001   // fails, this fields hold an exception object that should be
8002   // thrown if the regexp is used again.
8003   static const int kIrregexpLatin1CodeIndex = kDataIndex;
8004   // Irregexp compiled code or bytecode for UC16.  If compilation
8005   // fails, this fields hold an exception object that should be
8006   // thrown if the regexp is used again.
8007   static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8008
8009   // Saved instance of Irregexp compiled code or bytecode for Latin1 that
8010   // is a potential candidate for flushing.
8011   static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
8012   // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8013   // a potential candidate for flushing.
8014   static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8015
8016   // Maximal number of registers used by either Latin1 or UC16.
8017   // Only used to check that there is enough stack space
8018   static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8019   // Number of captures in the compiled regexp.
8020   static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8021
8022   static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8023
8024   // Offsets directly into the data fixed array.
8025   static const int kDataTagOffset =
8026       FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8027   static const int kDataOneByteCodeOffset =
8028       FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
8029   static const int kDataUC16CodeOffset =
8030       FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8031   static const int kIrregexpCaptureCountOffset =
8032       FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8033
8034   // In-object fields.
8035   static const int kGlobalFieldIndex = 0;
8036   static const int kIgnoreCaseFieldIndex = 1;
8037   static const int kMultilineFieldIndex = 2;
8038   static const int kLastIndexFieldIndex = 3;
8039   static const int kInObjectFieldCount = 4;
8040
8041   // The uninitialized value for a regexp code object.
8042   static const int kUninitializedValue = -1;
8043
8044   // The compilation error value for the regexp code object. The real error
8045   // object is in the saved code field.
8046   static const int kCompilationErrorValue = -2;
8047
8048   // When we store the sweep generation at which we moved the code from the
8049   // code index to the saved code index we mask it of to be in the [0:255]
8050   // range.
8051   static const int kCodeAgeMask = 0xff;
8052 };
8053
8054
8055 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8056  public:
8057   static inline bool IsMatch(HashTableKey* key, Object* value) {
8058     return key->IsMatch(value);
8059   }
8060
8061   static inline uint32_t Hash(HashTableKey* key) {
8062     return key->Hash();
8063   }
8064
8065   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8066     return key->HashForObject(object);
8067   }
8068
8069   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8070
8071   static const int kPrefixSize = 0;
8072   static const int kEntrySize = 2;
8073 };
8074
8075
8076 // This cache is used in two different variants. For regexp caching, it simply
8077 // maps identifying info of the regexp to the cached regexp object. Scripts and
8078 // eval code only gets cached after a second probe for the code object. To do
8079 // so, on first "put" only a hash identifying the source is entered into the
8080 // cache, mapping it to a lifetime count of the hash. On each call to Age all
8081 // such lifetimes get reduced, and removed once they reach zero. If a second put
8082 // is called while such a hash is live in the cache, the hash gets replaced by
8083 // an actual cache entry. Age also removes stale live entries from the cache.
8084 // Such entries are identified by SharedFunctionInfos pointing to either the
8085 // recompilation stub, or to "old" code. This avoids memory leaks due to
8086 // premature caching of scripts and eval strings that are never needed later.
8087 class CompilationCacheTable: public HashTable<CompilationCacheTable,
8088                                               CompilationCacheShape,
8089                                               HashTableKey*> {
8090  public:
8091   // Find cached value for a string key, otherwise return null.
8092   Handle<Object> Lookup(
8093       Handle<String> src, Handle<Context> context, LanguageMode language_mode);
8094   Handle<Object> LookupEval(
8095       Handle<String> src, Handle<SharedFunctionInfo> shared,
8096       LanguageMode language_mode, int scope_position);
8097   Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
8098   static Handle<CompilationCacheTable> Put(
8099       Handle<CompilationCacheTable> cache, Handle<String> src,
8100       Handle<Context> context, LanguageMode language_mode,
8101       Handle<Object> value);
8102   static Handle<CompilationCacheTable> PutEval(
8103       Handle<CompilationCacheTable> cache, Handle<String> src,
8104       Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
8105       int scope_position);
8106   static Handle<CompilationCacheTable> PutRegExp(
8107       Handle<CompilationCacheTable> cache, Handle<String> src,
8108       JSRegExp::Flags flags, Handle<FixedArray> value);
8109   void Remove(Object* value);
8110   void Age();
8111   static const int kHashGenerations = 10;
8112
8113   DECLARE_CAST(CompilationCacheTable)
8114
8115  private:
8116   DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8117 };
8118
8119
8120 class CodeCache: public Struct {
8121  public:
8122   DECL_ACCESSORS(default_cache, FixedArray)
8123   DECL_ACCESSORS(normal_type_cache, Object)
8124   DECL_ACCESSORS(weak_cell_cache, Object)
8125
8126   // Add the code object to the cache.
8127   static void Update(
8128       Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8129
8130   // Lookup code object in the cache. Returns code object if found and undefined
8131   // if not.
8132   Object* Lookup(Name* name, Code::Flags flags);
8133
8134   // Get the internal index of a code object in the cache. Returns -1 if the
8135   // code object is not in that cache. This index can be used to later call
8136   // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8137   // RemoveByIndex.
8138   int GetIndex(Object* name, Code* code);
8139
8140   // Remove an object from the cache with the provided internal index.
8141   void RemoveByIndex(Object* name, Code* code, int index);
8142
8143   DECLARE_CAST(CodeCache)
8144
8145   // Dispatched behavior.
8146   DECLARE_PRINTER(CodeCache)
8147   DECLARE_VERIFIER(CodeCache)
8148
8149   static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8150   static const int kNormalTypeCacheOffset =
8151       kDefaultCacheOffset + kPointerSize;
8152   static const int kWeakCellCacheOffset = kNormalTypeCacheOffset + kPointerSize;
8153   static const int kSize = kWeakCellCacheOffset + kPointerSize;
8154
8155  private:
8156   static void UpdateDefaultCache(
8157       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8158   static void UpdateNormalTypeCache(
8159       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8160   Object* LookupDefaultCache(Name* name, Code::Flags flags);
8161   Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8162
8163   // Code cache layout of the default cache. Elements are alternating name and
8164   // code objects for non normal load/store/call IC's.
8165   static const int kCodeCacheEntrySize = 2;
8166   static const int kCodeCacheEntryNameOffset = 0;
8167   static const int kCodeCacheEntryCodeOffset = 1;
8168
8169   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8170 };
8171
8172
8173 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8174  public:
8175   static inline bool IsMatch(HashTableKey* key, Object* value) {
8176     return key->IsMatch(value);
8177   }
8178
8179   static inline uint32_t Hash(HashTableKey* key) {
8180     return key->Hash();
8181   }
8182
8183   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8184     return key->HashForObject(object);
8185   }
8186
8187   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8188
8189   static const int kPrefixSize = 0;
8190   static const int kEntrySize = 2;
8191 };
8192
8193
8194 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8195                                            CodeCacheHashTableShape,
8196                                            HashTableKey*> {
8197  public:
8198   Object* Lookup(Name* name, Code::Flags flags);
8199   static Handle<CodeCacheHashTable> Put(
8200       Handle<CodeCacheHashTable> table,
8201       Handle<Name> name,
8202       Handle<Code> code);
8203
8204   int GetIndex(Name* name, Code::Flags flags);
8205   void RemoveByIndex(int index);
8206
8207   DECLARE_CAST(CodeCacheHashTable)
8208
8209   // Initial size of the fixed array backing the hash table.
8210   static const int kInitialSize = 64;
8211
8212  private:
8213   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8214 };
8215
8216
8217 class PolymorphicCodeCache: public Struct {
8218  public:
8219   DECL_ACCESSORS(cache, Object)
8220
8221   static void Update(Handle<PolymorphicCodeCache> cache,
8222                      MapHandleList* maps,
8223                      Code::Flags flags,
8224                      Handle<Code> code);
8225
8226
8227   // Returns an undefined value if the entry is not found.
8228   Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8229
8230   DECLARE_CAST(PolymorphicCodeCache)
8231
8232   // Dispatched behavior.
8233   DECLARE_PRINTER(PolymorphicCodeCache)
8234   DECLARE_VERIFIER(PolymorphicCodeCache)
8235
8236   static const int kCacheOffset = HeapObject::kHeaderSize;
8237   static const int kSize = kCacheOffset + kPointerSize;
8238
8239  private:
8240   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8241 };
8242
8243
8244 class PolymorphicCodeCacheHashTable
8245     : public HashTable<PolymorphicCodeCacheHashTable,
8246                        CodeCacheHashTableShape,
8247                        HashTableKey*> {
8248  public:
8249   Object* Lookup(MapHandleList* maps, int code_kind);
8250
8251   static Handle<PolymorphicCodeCacheHashTable> Put(
8252       Handle<PolymorphicCodeCacheHashTable> hash_table,
8253       MapHandleList* maps,
8254       int code_kind,
8255       Handle<Code> code);
8256
8257   DECLARE_CAST(PolymorphicCodeCacheHashTable)
8258
8259   static const int kInitialSize = 64;
8260  private:
8261   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8262 };
8263
8264
8265 class TypeFeedbackInfo: public Struct {
8266  public:
8267   inline int ic_total_count();
8268   inline void set_ic_total_count(int count);
8269
8270   inline int ic_with_type_info_count();
8271   inline void change_ic_with_type_info_count(int delta);
8272
8273   inline int ic_generic_count();
8274   inline void change_ic_generic_count(int delta);
8275
8276   inline void initialize_storage();
8277
8278   inline void change_own_type_change_checksum();
8279   inline int own_type_change_checksum();
8280
8281   inline void set_inlined_type_change_checksum(int checksum);
8282   inline bool matches_inlined_type_change_checksum(int checksum);
8283
8284   DECLARE_CAST(TypeFeedbackInfo)
8285
8286   // Dispatched behavior.
8287   DECLARE_PRINTER(TypeFeedbackInfo)
8288   DECLARE_VERIFIER(TypeFeedbackInfo)
8289
8290   static const int kStorage1Offset = HeapObject::kHeaderSize;
8291   static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8292   static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8293   static const int kSize = kStorage3Offset + kPointerSize;
8294
8295  private:
8296   static const int kTypeChangeChecksumBits = 7;
8297
8298   class ICTotalCountField: public BitField<int, 0,
8299       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8300   class OwnTypeChangeChecksum: public BitField<int,
8301       kSmiValueSize - kTypeChangeChecksumBits,
8302       kTypeChangeChecksumBits> {};  // NOLINT
8303   class ICsWithTypeInfoCountField: public BitField<int, 0,
8304       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8305   class InlinedTypeChangeChecksum: public BitField<int,
8306       kSmiValueSize - kTypeChangeChecksumBits,
8307       kTypeChangeChecksumBits> {};  // NOLINT
8308
8309   DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8310 };
8311
8312
8313 enum AllocationSiteMode {
8314   DONT_TRACK_ALLOCATION_SITE,
8315   TRACK_ALLOCATION_SITE,
8316   LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8317 };
8318
8319
8320 class AllocationSite: public Struct {
8321  public:
8322   static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8323   static const double kPretenureRatio;
8324   static const int kPretenureMinimumCreated = 100;
8325
8326   // Values for pretenure decision field.
8327   enum PretenureDecision {
8328     kUndecided = 0,
8329     kDontTenure = 1,
8330     kMaybeTenure = 2,
8331     kTenure = 3,
8332     kZombie = 4,
8333     kLastPretenureDecisionValue = kZombie
8334   };
8335
8336   const char* PretenureDecisionName(PretenureDecision decision);
8337
8338   DECL_ACCESSORS(transition_info, Object)
8339   // nested_site threads a list of sites that represent nested literals
8340   // walked in a particular order. So [[1, 2], 1, 2] will have one
8341   // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8342   DECL_ACCESSORS(nested_site, Object)
8343   DECL_ACCESSORS(pretenure_data, Smi)
8344   DECL_ACCESSORS(pretenure_create_count, Smi)
8345   DECL_ACCESSORS(dependent_code, DependentCode)
8346   DECL_ACCESSORS(weak_next, Object)
8347
8348   inline void Initialize();
8349
8350   // This method is expensive, it should only be called for reporting.
8351   bool IsNestedSite();
8352
8353   // transition_info bitfields, for constructed array transition info.
8354   class ElementsKindBits:       public BitField<ElementsKind, 0,  15> {};
8355   class UnusedBits:             public BitField<int,          15, 14> {};
8356   class DoNotInlineBit:         public BitField<bool,         29,  1> {};
8357
8358   // Bitfields for pretenure_data
8359   class MementoFoundCountBits:  public BitField<int,               0, 26> {};
8360   class PretenureDecisionBits:  public BitField<PretenureDecision, 26, 3> {};
8361   class DeoptDependentCodeBit:  public BitField<bool,              29, 1> {};
8362   STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8363
8364   // Increments the mementos found counter and returns true when the first
8365   // memento was found for a given allocation site.
8366   inline bool IncrementMementoFoundCount();
8367
8368   inline void IncrementMementoCreateCount();
8369
8370   PretenureFlag GetPretenureMode();
8371
8372   void ResetPretenureDecision();
8373
8374   PretenureDecision pretenure_decision() {
8375     int value = pretenure_data()->value();
8376     return PretenureDecisionBits::decode(value);
8377   }
8378
8379   void set_pretenure_decision(PretenureDecision decision) {
8380     int value = pretenure_data()->value();
8381     set_pretenure_data(
8382         Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8383         SKIP_WRITE_BARRIER);
8384   }
8385
8386   bool deopt_dependent_code() {
8387     int value = pretenure_data()->value();
8388     return DeoptDependentCodeBit::decode(value);
8389   }
8390
8391   void set_deopt_dependent_code(bool deopt) {
8392     int value = pretenure_data()->value();
8393     set_pretenure_data(
8394         Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8395         SKIP_WRITE_BARRIER);
8396   }
8397
8398   int memento_found_count() {
8399     int value = pretenure_data()->value();
8400     return MementoFoundCountBits::decode(value);
8401   }
8402
8403   inline void set_memento_found_count(int count);
8404
8405   int memento_create_count() {
8406     return pretenure_create_count()->value();
8407   }
8408
8409   void set_memento_create_count(int count) {
8410     set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8411   }
8412
8413   // The pretenuring decision is made during gc, and the zombie state allows
8414   // us to recognize when an allocation site is just being kept alive because
8415   // a later traversal of new space may discover AllocationMementos that point
8416   // to this AllocationSite.
8417   bool IsZombie() {
8418     return pretenure_decision() == kZombie;
8419   }
8420
8421   bool IsMaybeTenure() {
8422     return pretenure_decision() == kMaybeTenure;
8423   }
8424
8425   inline void MarkZombie();
8426
8427   inline bool MakePretenureDecision(PretenureDecision current_decision,
8428                                     double ratio,
8429                                     bool maximum_size_scavenge);
8430
8431   inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8432
8433   ElementsKind GetElementsKind() {
8434     DCHECK(!SitePointsToLiteral());
8435     int value = Smi::cast(transition_info())->value();
8436     return ElementsKindBits::decode(value);
8437   }
8438
8439   void SetElementsKind(ElementsKind kind) {
8440     int value = Smi::cast(transition_info())->value();
8441     set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8442                         SKIP_WRITE_BARRIER);
8443   }
8444
8445   bool CanInlineCall() {
8446     int value = Smi::cast(transition_info())->value();
8447     return DoNotInlineBit::decode(value) == 0;
8448   }
8449
8450   void SetDoNotInlineCall() {
8451     int value = Smi::cast(transition_info())->value();
8452     set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8453                         SKIP_WRITE_BARRIER);
8454   }
8455
8456   bool SitePointsToLiteral() {
8457     // If transition_info is a smi, then it represents an ElementsKind
8458     // for a constructed array. Otherwise, it must be a boilerplate
8459     // for an object or array literal.
8460     return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8461   }
8462
8463   static void DigestTransitionFeedback(Handle<AllocationSite> site,
8464                                        ElementsKind to_kind);
8465
8466   static void RegisterForDeoptOnTenureChange(Handle<AllocationSite> site,
8467                                              CompilationInfo* info);
8468
8469   static void RegisterForDeoptOnTransitionChange(Handle<AllocationSite> site,
8470                                                  CompilationInfo* info);
8471
8472   DECLARE_PRINTER(AllocationSite)
8473   DECLARE_VERIFIER(AllocationSite)
8474
8475   DECLARE_CAST(AllocationSite)
8476   static inline AllocationSiteMode GetMode(
8477       ElementsKind boilerplate_elements_kind);
8478   static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8479   static inline bool CanTrack(InstanceType type);
8480
8481   static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8482   static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8483   static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8484   static const int kPretenureCreateCountOffset =
8485       kPretenureDataOffset + kPointerSize;
8486   static const int kDependentCodeOffset =
8487       kPretenureCreateCountOffset + kPointerSize;
8488   static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8489   static const int kSize = kWeakNextOffset + kPointerSize;
8490
8491   // During mark compact we need to take special care for the dependent code
8492   // field.
8493   static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8494   static const int kPointerFieldsEndOffset = kWeakNextOffset;
8495
8496   // For other visitors, use the fixed body descriptor below.
8497   typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8498                               kDependentCodeOffset + kPointerSize,
8499                               kSize> BodyDescriptor;
8500
8501  private:
8502   static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8503                                           DependentCode::DependencyGroup group,
8504                                           CompilationInfo* info);
8505
8506   bool PretenuringDecisionMade() {
8507     return pretenure_decision() != kUndecided;
8508   }
8509
8510   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8511 };
8512
8513
8514 class AllocationMemento: public Struct {
8515  public:
8516   static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8517   static const int kSize = kAllocationSiteOffset + kPointerSize;
8518
8519   DECL_ACCESSORS(allocation_site, Object)
8520
8521   bool IsValid() {
8522     return allocation_site()->IsAllocationSite() &&
8523         !AllocationSite::cast(allocation_site())->IsZombie();
8524   }
8525   AllocationSite* GetAllocationSite() {
8526     DCHECK(IsValid());
8527     return AllocationSite::cast(allocation_site());
8528   }
8529
8530   DECLARE_PRINTER(AllocationMemento)
8531   DECLARE_VERIFIER(AllocationMemento)
8532
8533   DECLARE_CAST(AllocationMemento)
8534
8535  private:
8536   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8537 };
8538
8539
8540 // Representation of a slow alias as part of a sloppy arguments objects.
8541 // For fast aliases (if HasSloppyArgumentsElements()):
8542 // - the parameter map contains an index into the context
8543 // - all attributes of the element have default values
8544 // For slow aliases (if HasDictionaryArgumentsElements()):
8545 // - the parameter map contains no fast alias mapping (i.e. the hole)
8546 // - this struct (in the slow backing store) contains an index into the context
8547 // - all attributes are available as part if the property details
8548 class AliasedArgumentsEntry: public Struct {
8549  public:
8550   inline int aliased_context_slot() const;
8551   inline void set_aliased_context_slot(int count);
8552
8553   DECLARE_CAST(AliasedArgumentsEntry)
8554
8555   // Dispatched behavior.
8556   DECLARE_PRINTER(AliasedArgumentsEntry)
8557   DECLARE_VERIFIER(AliasedArgumentsEntry)
8558
8559   static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8560   static const int kSize = kAliasedContextSlot + kPointerSize;
8561
8562  private:
8563   DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8564 };
8565
8566
8567 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8568 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8569
8570
8571 class StringHasher {
8572  public:
8573   explicit inline StringHasher(int length, uint32_t seed);
8574
8575   template <typename schar>
8576   static inline uint32_t HashSequentialString(const schar* chars,
8577                                               int length,
8578                                               uint32_t seed);
8579
8580   // Reads all the data, even for long strings and computes the utf16 length.
8581   static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8582                                   uint32_t seed,
8583                                   int* utf16_length_out);
8584
8585   // Calculated hash value for a string consisting of 1 to
8586   // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8587   // value is represented decimal value.
8588   static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8589
8590   // No string is allowed to have a hash of zero.  That value is reserved
8591   // for internal properties.  If the hash calculation yields zero then we
8592   // use 27 instead.
8593   static const int kZeroHash = 27;
8594
8595   // Reusable parts of the hashing algorithm.
8596   INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8597   INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8598   INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8599                                             const uc16* chars, int length));
8600   INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8601                                                    const char* chars,
8602                                                    int length));
8603
8604  protected:
8605   // Returns the value to store in the hash field of a string with
8606   // the given length and contents.
8607   uint32_t GetHashField();
8608   // Returns true if the hash of this string can be computed without
8609   // looking at the contents.
8610   inline bool has_trivial_hash();
8611   // Adds a block of characters to the hash.
8612   template<typename Char>
8613   inline void AddCharacters(const Char* chars, int len);
8614
8615  private:
8616   // Add a character to the hash.
8617   inline void AddCharacter(uint16_t c);
8618   // Update index. Returns true if string is still an index.
8619   inline bool UpdateIndex(uint16_t c);
8620
8621   int length_;
8622   uint32_t raw_running_hash_;
8623   uint32_t array_index_;
8624   bool is_array_index_;
8625   bool is_first_char_;
8626   DISALLOW_COPY_AND_ASSIGN(StringHasher);
8627 };
8628
8629
8630 class IteratingStringHasher : public StringHasher {
8631  public:
8632   static inline uint32_t Hash(String* string, uint32_t seed);
8633   inline void VisitOneByteString(const uint8_t* chars, int length);
8634   inline void VisitTwoByteString(const uint16_t* chars, int length);
8635
8636  private:
8637   inline IteratingStringHasher(int len, uint32_t seed)
8638       : StringHasher(len, seed) {}
8639   void VisitConsString(ConsString* cons_string);
8640   DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8641 };
8642
8643
8644 // The characteristics of a string are stored in its map.  Retrieving these
8645 // few bits of information is moderately expensive, involving two memory
8646 // loads where the second is dependent on the first.  To improve efficiency
8647 // the shape of the string is given its own class so that it can be retrieved
8648 // once and used for several string operations.  A StringShape is small enough
8649 // to be passed by value and is immutable, but be aware that flattening a
8650 // string can potentially alter its shape.  Also be aware that a GC caused by
8651 // something else can alter the shape of a string due to ConsString
8652 // shortcutting.  Keeping these restrictions in mind has proven to be error-
8653 // prone and so we no longer put StringShapes in variables unless there is a
8654 // concrete performance benefit at that particular point in the code.
8655 class StringShape BASE_EMBEDDED {
8656  public:
8657   inline explicit StringShape(const String* s);
8658   inline explicit StringShape(Map* s);
8659   inline explicit StringShape(InstanceType t);
8660   inline bool IsSequential();
8661   inline bool IsExternal();
8662   inline bool IsCons();
8663   inline bool IsSliced();
8664   inline bool IsIndirect();
8665   inline bool IsExternalOneByte();
8666   inline bool IsExternalTwoByte();
8667   inline bool IsSequentialOneByte();
8668   inline bool IsSequentialTwoByte();
8669   inline bool IsInternalized();
8670   inline StringRepresentationTag representation_tag();
8671   inline uint32_t encoding_tag();
8672   inline uint32_t full_representation_tag();
8673   inline uint32_t size_tag();
8674 #ifdef DEBUG
8675   inline uint32_t type() { return type_; }
8676   inline void invalidate() { valid_ = false; }
8677   inline bool valid() { return valid_; }
8678 #else
8679   inline void invalidate() { }
8680 #endif
8681
8682  private:
8683   uint32_t type_;
8684 #ifdef DEBUG
8685   inline void set_valid() { valid_ = true; }
8686   bool valid_;
8687 #else
8688   inline void set_valid() { }
8689 #endif
8690 };
8691
8692
8693 // The Name abstract class captures anything that can be used as a property
8694 // name, i.e., strings and symbols.  All names store a hash value.
8695 class Name: public HeapObject {
8696  public:
8697   // Get and set the hash field of the name.
8698   inline uint32_t hash_field();
8699   inline void set_hash_field(uint32_t value);
8700
8701   // Tells whether the hash code has been computed.
8702   inline bool HasHashCode();
8703
8704   // Returns a hash value used for the property table
8705   inline uint32_t Hash();
8706
8707   // Equality operations.
8708   inline bool Equals(Name* other);
8709   inline static bool Equals(Handle<Name> one, Handle<Name> two);
8710
8711   // Conversion.
8712   inline bool AsArrayIndex(uint32_t* index);
8713
8714   // Whether name can only name own properties.
8715   inline bool IsOwn();
8716
8717   DECLARE_CAST(Name)
8718
8719   DECLARE_PRINTER(Name)
8720 #if TRACE_MAPS
8721   void NameShortPrint();
8722   int NameShortPrint(Vector<char> str);
8723 #endif
8724
8725   // Layout description.
8726   static const int kHashFieldSlot = HeapObject::kHeaderSize;
8727 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8728   static const int kHashFieldOffset = kHashFieldSlot;
8729 #else
8730   static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8731 #endif
8732   static const int kSize = kHashFieldSlot + kPointerSize;
8733
8734   // Mask constant for checking if a name has a computed hash code
8735   // and if it is a string that is an array index.  The least significant bit
8736   // indicates whether a hash code has been computed.  If the hash code has
8737   // been computed the 2nd bit tells whether the string can be used as an
8738   // array index.
8739   static const int kHashNotComputedMask = 1;
8740   static const int kIsNotArrayIndexMask = 1 << 1;
8741   static const int kNofHashBitFields = 2;
8742
8743   // Shift constant retrieving hash code from hash field.
8744   static const int kHashShift = kNofHashBitFields;
8745
8746   // Only these bits are relevant in the hash, since the top two are shifted
8747   // out.
8748   static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8749
8750   // Array index strings this short can keep their index in the hash field.
8751   static const int kMaxCachedArrayIndexLength = 7;
8752
8753   // For strings which are array indexes the hash value has the string length
8754   // mixed into the hash, mainly to avoid a hash value of zero which would be
8755   // the case for the string '0'. 24 bits are used for the array index value.
8756   static const int kArrayIndexValueBits = 24;
8757   static const int kArrayIndexLengthBits =
8758       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8759
8760   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8761
8762   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8763       kArrayIndexValueBits> {};  // NOLINT
8764   class ArrayIndexLengthBits : public BitField<unsigned int,
8765       kNofHashBitFields + kArrayIndexValueBits,
8766       kArrayIndexLengthBits> {};  // NOLINT
8767
8768   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8769   // could use a mask to test if the length of string is less than or equal to
8770   // kMaxCachedArrayIndexLength.
8771   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8772
8773   static const unsigned int kContainsCachedArrayIndexMask =
8774       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8775        << ArrayIndexLengthBits::kShift) |
8776       kIsNotArrayIndexMask;
8777
8778   // Value of empty hash field indicating that the hash is not computed.
8779   static const int kEmptyHashField =
8780       kIsNotArrayIndexMask | kHashNotComputedMask;
8781
8782  protected:
8783   static inline bool IsHashFieldComputed(uint32_t field);
8784
8785  private:
8786   DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8787 };
8788
8789
8790 // ES6 symbols.
8791 class Symbol: public Name {
8792  public:
8793   // [name]: the print name of a symbol, or undefined if none.
8794   DECL_ACCESSORS(name, Object)
8795
8796   DECL_ACCESSORS(flags, Smi)
8797
8798   // [is_private]: whether this is a private symbol.
8799   DECL_BOOLEAN_ACCESSORS(is_private)
8800
8801   // [is_own]: whether this is an own symbol, that is, only used to designate
8802   // own properties of objects.
8803   DECL_BOOLEAN_ACCESSORS(is_own)
8804
8805   DECLARE_CAST(Symbol)
8806
8807   // Dispatched behavior.
8808   DECLARE_PRINTER(Symbol)
8809   DECLARE_VERIFIER(Symbol)
8810
8811   // Layout description.
8812   static const int kNameOffset = Name::kSize;
8813   static const int kFlagsOffset = kNameOffset + kPointerSize;
8814   static const int kSize = kFlagsOffset + kPointerSize;
8815
8816   typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8817
8818   void SymbolShortPrint(std::ostream& os);
8819
8820  private:
8821   static const int kPrivateBit = 0;
8822   static const int kOwnBit = 1;
8823
8824   const char* PrivateSymbolToName() const;
8825
8826 #if TRACE_MAPS
8827   friend class Name;  // For PrivateSymbolToName.
8828 #endif
8829
8830   DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8831 };
8832
8833
8834 class ConsString;
8835
8836 // The String abstract class captures JavaScript string values:
8837 //
8838 // Ecma-262:
8839 //  4.3.16 String Value
8840 //    A string value is a member of the type String and is a finite
8841 //    ordered sequence of zero or more 16-bit unsigned integer values.
8842 //
8843 // All string values have a length field.
8844 class String: public Name {
8845  public:
8846   enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8847
8848   // Array index strings this short can keep their index in the hash field.
8849   static const int kMaxCachedArrayIndexLength = 7;
8850
8851   // For strings which are array indexes the hash value has the string length
8852   // mixed into the hash, mainly to avoid a hash value of zero which would be
8853   // the case for the string '0'. 24 bits are used for the array index value.
8854   static const int kArrayIndexValueBits = 24;
8855   static const int kArrayIndexLengthBits =
8856       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8857
8858   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8859
8860   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8861       kArrayIndexValueBits> {};  // NOLINT
8862   class ArrayIndexLengthBits : public BitField<unsigned int,
8863       kNofHashBitFields + kArrayIndexValueBits,
8864       kArrayIndexLengthBits> {};  // NOLINT
8865
8866   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8867   // could use a mask to test if the length of string is less than or equal to
8868   // kMaxCachedArrayIndexLength.
8869   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8870
8871   static const unsigned int kContainsCachedArrayIndexMask =
8872       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8873        << ArrayIndexLengthBits::kShift) |
8874       kIsNotArrayIndexMask;
8875
8876   class SubStringRange {
8877    public:
8878     explicit SubStringRange(String* string, int first = 0, int length = -1)
8879         : string_(string),
8880           first_(first),
8881           length_(length == -1 ? string->length() : length) {}
8882     class iterator;
8883     inline iterator begin();
8884     inline iterator end();
8885
8886    private:
8887     String* string_;
8888     int first_;
8889     int length_;
8890   };
8891
8892   // Representation of the flat content of a String.
8893   // A non-flat string doesn't have flat content.
8894   // A flat string has content that's encoded as a sequence of either
8895   // one-byte chars or two-byte UC16.
8896   // Returned by String::GetFlatContent().
8897   class FlatContent {
8898    public:
8899     // Returns true if the string is flat and this structure contains content.
8900     bool IsFlat() { return state_ != NON_FLAT; }
8901     // Returns true if the structure contains one-byte content.
8902     bool IsOneByte() { return state_ == ONE_BYTE; }
8903     // Returns true if the structure contains two-byte content.
8904     bool IsTwoByte() { return state_ == TWO_BYTE; }
8905
8906     // Return the one byte content of the string. Only use if IsOneByte()
8907     // returns true.
8908     Vector<const uint8_t> ToOneByteVector() {
8909       DCHECK_EQ(ONE_BYTE, state_);
8910       return Vector<const uint8_t>(onebyte_start, length_);
8911     }
8912     // Return the two-byte content of the string. Only use if IsTwoByte()
8913     // returns true.
8914     Vector<const uc16> ToUC16Vector() {
8915       DCHECK_EQ(TWO_BYTE, state_);
8916       return Vector<const uc16>(twobyte_start, length_);
8917     }
8918
8919     uc16 Get(int i) {
8920       DCHECK(i < length_);
8921       DCHECK(state_ != NON_FLAT);
8922       if (state_ == ONE_BYTE) return onebyte_start[i];
8923       return twobyte_start[i];
8924     }
8925
8926     bool UsesSameString(const FlatContent& other) const {
8927       return onebyte_start == other.onebyte_start;
8928     }
8929
8930    private:
8931     enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8932
8933     // Constructors only used by String::GetFlatContent().
8934     explicit FlatContent(const uint8_t* start, int length)
8935         : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8936     explicit FlatContent(const uc16* start, int length)
8937         : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8938     FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8939
8940     union {
8941       const uint8_t* onebyte_start;
8942       const uc16* twobyte_start;
8943     };
8944     int length_;
8945     State state_;
8946
8947     friend class String;
8948     friend class IterableSubString;
8949   };
8950
8951   template <typename Char>
8952   INLINE(Vector<const Char> GetCharVector());
8953
8954   // Get and set the length of the string.
8955   inline int length() const;
8956   inline void set_length(int value);
8957
8958   // Get and set the length of the string using acquire loads and release
8959   // stores.
8960   inline int synchronized_length() const;
8961   inline void synchronized_set_length(int value);
8962
8963   // Returns whether this string has only one-byte chars, i.e. all of them can
8964   // be one-byte encoded.  This might be the case even if the string is
8965   // two-byte.  Such strings may appear when the embedder prefers
8966   // two-byte external representations even for one-byte data.
8967   inline bool IsOneByteRepresentation() const;
8968   inline bool IsTwoByteRepresentation() const;
8969
8970   // Cons and slices have an encoding flag that may not represent the actual
8971   // encoding of the underlying string.  This is taken into account here.
8972   // Requires: this->IsFlat()
8973   inline bool IsOneByteRepresentationUnderneath();
8974   inline bool IsTwoByteRepresentationUnderneath();
8975
8976   // NOTE: this should be considered only a hint.  False negatives are
8977   // possible.
8978   inline bool HasOnlyOneByteChars();
8979
8980   // Get and set individual two byte chars in the string.
8981   inline void Set(int index, uint16_t value);
8982   // Get individual two byte char in the string.  Repeated calls
8983   // to this method are not efficient unless the string is flat.
8984   INLINE(uint16_t Get(int index));
8985
8986   // Flattens the string.  Checks first inline to see if it is
8987   // necessary.  Does nothing if the string is not a cons string.
8988   // Flattening allocates a sequential string with the same data as
8989   // the given string and mutates the cons string to a degenerate
8990   // form, where the first component is the new sequential string and
8991   // the second component is the empty string.  If allocation fails,
8992   // this function returns a failure.  If flattening succeeds, this
8993   // function returns the sequential string that is now the first
8994   // component of the cons string.
8995   //
8996   // Degenerate cons strings are handled specially by the garbage
8997   // collector (see IsShortcutCandidate).
8998
8999   static inline Handle<String> Flatten(Handle<String> string,
9000                                        PretenureFlag pretenure = NOT_TENURED);
9001
9002   // Tries to return the content of a flat string as a structure holding either
9003   // a flat vector of char or of uc16.
9004   // If the string isn't flat, and therefore doesn't have flat content, the
9005   // returned structure will report so, and can't provide a vector of either
9006   // kind.
9007   FlatContent GetFlatContent();
9008
9009   // Returns the parent of a sliced string or first part of a flat cons string.
9010   // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9011   inline String* GetUnderlying();
9012
9013   // String equality operations.
9014   inline bool Equals(String* other);
9015   inline static bool Equals(Handle<String> one, Handle<String> two);
9016   bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9017   bool IsOneByteEqualTo(Vector<const uint8_t> str);
9018   bool IsTwoByteEqualTo(Vector<const uc16> str);
9019
9020   // Return a UTF8 representation of the string.  The string is null
9021   // terminated but may optionally contain nulls.  Length is returned
9022   // in length_output if length_output is not a null pointer  The string
9023   // should be nearly flat, otherwise the performance of this method may
9024   // be very slow (quadratic in the length).  Setting robustness_flag to
9025   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9026   // handles unexpected data without causing assert failures and it does not
9027   // do any heap allocations.  This is useful when printing stack traces.
9028   SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9029                                     RobustnessFlag robustness_flag,
9030                                     int offset,
9031                                     int length,
9032                                     int* length_output = 0);
9033   SmartArrayPointer<char> ToCString(
9034       AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9035       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9036       int* length_output = 0);
9037
9038   // Return a 16 bit Unicode representation of the string.
9039   // The string should be nearly flat, otherwise the performance of
9040   // of this method may be very bad.  Setting robustness_flag to
9041   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9042   // handles unexpected data without causing assert failures and it does not
9043   // do any heap allocations.  This is useful when printing stack traces.
9044   SmartArrayPointer<uc16> ToWideCString(
9045       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9046
9047   bool ComputeArrayIndex(uint32_t* index);
9048
9049   // Externalization.
9050   bool MakeExternal(v8::String::ExternalStringResource* resource);
9051   bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
9052
9053   // Conversion.
9054   inline bool AsArrayIndex(uint32_t* index);
9055
9056   DECLARE_CAST(String)
9057
9058   void PrintOn(FILE* out);
9059
9060   // For use during stack traces.  Performs rudimentary sanity check.
9061   bool LooksValid();
9062
9063   // Dispatched behavior.
9064   void StringShortPrint(StringStream* accumulator);
9065   void PrintUC16(std::ostream& os, int start = 0, int end = -1);  // NOLINT
9066 #if defined(DEBUG) || defined(OBJECT_PRINT)
9067   char* ToAsciiArray();
9068 #endif
9069   DECLARE_PRINTER(String)
9070   DECLARE_VERIFIER(String)
9071
9072   inline bool IsFlat();
9073
9074   // Layout description.
9075   static const int kLengthOffset = Name::kSize;
9076   static const int kSize = kLengthOffset + kPointerSize;
9077
9078   // Maximum number of characters to consider when trying to convert a string
9079   // value into an array index.
9080   static const int kMaxArrayIndexSize = 10;
9081   STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9082
9083   // Max char codes.
9084   static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9085   static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9086   static const int kMaxUtf16CodeUnit = 0xffff;
9087   static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
9088
9089   // Value of hash field containing computed hash equal to zero.
9090   static const int kEmptyStringHash = kIsNotArrayIndexMask;
9091
9092   // Maximal string length.
9093   static const int kMaxLength = (1 << 28) - 16;
9094
9095   // Max length for computing hash. For strings longer than this limit the
9096   // string length is used as the hash value.
9097   static const int kMaxHashCalcLength = 16383;
9098
9099   // Limit for truncation in short printing.
9100   static const int kMaxShortPrintLength = 1024;
9101
9102   // Support for regular expressions.
9103   const uc16* GetTwoByteData(unsigned start);
9104
9105   // Helper function for flattening strings.
9106   template <typename sinkchar>
9107   static void WriteToFlat(String* source,
9108                           sinkchar* sink,
9109                           int from,
9110                           int to);
9111
9112   // The return value may point to the first aligned word containing the first
9113   // non-one-byte character, rather than directly to the non-one-byte character.
9114   // If the return value is >= the passed length, the entire string was
9115   // one-byte.
9116   static inline int NonAsciiStart(const char* chars, int length) {
9117     const char* start = chars;
9118     const char* limit = chars + length;
9119
9120     if (length >= kIntptrSize) {
9121       // Check unaligned bytes.
9122       while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
9123         if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9124           return static_cast<int>(chars - start);
9125         }
9126         ++chars;
9127       }
9128       // Check aligned words.
9129       DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9130       const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9131       while (chars + sizeof(uintptr_t) <= limit) {
9132         if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
9133           return static_cast<int>(chars - start);
9134         }
9135         chars += sizeof(uintptr_t);
9136       }
9137     }
9138     // Check remaining unaligned bytes.
9139     while (chars < limit) {
9140       if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9141         return static_cast<int>(chars - start);
9142       }
9143       ++chars;
9144     }
9145
9146     return static_cast<int>(chars - start);
9147   }
9148
9149   static inline bool IsAscii(const char* chars, int length) {
9150     return NonAsciiStart(chars, length) >= length;
9151   }
9152
9153   static inline bool IsAscii(const uint8_t* chars, int length) {
9154     return
9155         NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9156   }
9157
9158   static inline int NonOneByteStart(const uc16* chars, int length) {
9159     const uc16* limit = chars + length;
9160     const uc16* start = chars;
9161     while (chars < limit) {
9162       if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9163       ++chars;
9164     }
9165     return static_cast<int>(chars - start);
9166   }
9167
9168   static inline bool IsOneByte(const uc16* chars, int length) {
9169     return NonOneByteStart(chars, length) >= length;
9170   }
9171
9172   template<class Visitor>
9173   static inline ConsString* VisitFlat(Visitor* visitor,
9174                                       String* string,
9175                                       int offset = 0);
9176
9177   static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9178                                               bool include_ending_line);
9179
9180   // Use the hash field to forward to the canonical internalized string
9181   // when deserializing an internalized string.
9182   inline void SetForwardedInternalizedString(String* string);
9183   inline String* GetForwardedInternalizedString();
9184
9185  private:
9186   friend class Name;
9187   friend class StringTableInsertionKey;
9188
9189   static Handle<String> SlowFlatten(Handle<ConsString> cons,
9190                                     PretenureFlag tenure);
9191
9192   // Slow case of String::Equals.  This implementation works on any strings
9193   // but it is most efficient on strings that are almost flat.
9194   bool SlowEquals(String* other);
9195
9196   static bool SlowEquals(Handle<String> one, Handle<String> two);
9197
9198   // Slow case of AsArrayIndex.
9199   bool SlowAsArrayIndex(uint32_t* index);
9200
9201   // Compute and set the hash code.
9202   uint32_t ComputeAndSetHash();
9203
9204   DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9205 };
9206
9207
9208 // The SeqString abstract class captures sequential string values.
9209 class SeqString: public String {
9210  public:
9211   DECLARE_CAST(SeqString)
9212
9213   // Layout description.
9214   static const int kHeaderSize = String::kSize;
9215
9216   // Truncate the string in-place if possible and return the result.
9217   // In case of new_length == 0, the empty string is returned without
9218   // truncating the original string.
9219   MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9220                                                  int new_length);
9221  private:
9222   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9223 };
9224
9225
9226 // The OneByteString class captures sequential one-byte string objects.
9227 // Each character in the OneByteString is an one-byte character.
9228 class SeqOneByteString: public SeqString {
9229  public:
9230   static const bool kHasOneByteEncoding = true;
9231
9232   // Dispatched behavior.
9233   inline uint16_t SeqOneByteStringGet(int index);
9234   inline void SeqOneByteStringSet(int index, uint16_t value);
9235
9236   // Get the address of the characters in this string.
9237   inline Address GetCharsAddress();
9238
9239   inline uint8_t* GetChars();
9240
9241   DECLARE_CAST(SeqOneByteString)
9242
9243   // Garbage collection support.  This method is called by the
9244   // garbage collector to compute the actual size of an OneByteString
9245   // instance.
9246   inline int SeqOneByteStringSize(InstanceType instance_type);
9247
9248   // Computes the size for an OneByteString instance of a given length.
9249   static int SizeFor(int length) {
9250     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9251   }
9252
9253   // Maximal memory usage for a single sequential one-byte string.
9254   static const int kMaxSize = 512 * MB - 1;
9255   STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9256
9257  private:
9258   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9259 };
9260
9261
9262 // The TwoByteString class captures sequential unicode string objects.
9263 // Each character in the TwoByteString is a two-byte uint16_t.
9264 class SeqTwoByteString: public SeqString {
9265  public:
9266   static const bool kHasOneByteEncoding = false;
9267
9268   // Dispatched behavior.
9269   inline uint16_t SeqTwoByteStringGet(int index);
9270   inline void SeqTwoByteStringSet(int index, uint16_t value);
9271
9272   // Get the address of the characters in this string.
9273   inline Address GetCharsAddress();
9274
9275   inline uc16* GetChars();
9276
9277   // For regexp code.
9278   const uint16_t* SeqTwoByteStringGetData(unsigned start);
9279
9280   DECLARE_CAST(SeqTwoByteString)
9281
9282   // Garbage collection support.  This method is called by the
9283   // garbage collector to compute the actual size of a TwoByteString
9284   // instance.
9285   inline int SeqTwoByteStringSize(InstanceType instance_type);
9286
9287   // Computes the size for a TwoByteString instance of a given length.
9288   static int SizeFor(int length) {
9289     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9290   }
9291
9292   // Maximal memory usage for a single sequential two-byte string.
9293   static const int kMaxSize = 512 * MB - 1;
9294   STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9295                String::kMaxLength);
9296
9297  private:
9298   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9299 };
9300
9301
9302 // The ConsString class describes string values built by using the
9303 // addition operator on strings.  A ConsString is a pair where the
9304 // first and second components are pointers to other string values.
9305 // One or both components of a ConsString can be pointers to other
9306 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9307 // are non-ConsString string values.  The string value represented by
9308 // a ConsString can be obtained by concatenating the leaf string
9309 // values in a left-to-right depth-first traversal of the tree.
9310 class ConsString: public String {
9311  public:
9312   // First string of the cons cell.
9313   inline String* first();
9314   // Doesn't check that the result is a string, even in debug mode.  This is
9315   // useful during GC where the mark bits confuse the checks.
9316   inline Object* unchecked_first();
9317   inline void set_first(String* first,
9318                         WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9319
9320   // Second string of the cons cell.
9321   inline String* second();
9322   // Doesn't check that the result is a string, even in debug mode.  This is
9323   // useful during GC where the mark bits confuse the checks.
9324   inline Object* unchecked_second();
9325   inline void set_second(String* second,
9326                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9327
9328   // Dispatched behavior.
9329   uint16_t ConsStringGet(int index);
9330
9331   DECLARE_CAST(ConsString)
9332
9333   // Layout description.
9334   static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9335   static const int kSecondOffset = kFirstOffset + kPointerSize;
9336   static const int kSize = kSecondOffset + kPointerSize;
9337
9338   // Minimum length for a cons string.
9339   static const int kMinLength = 13;
9340
9341   typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9342           BodyDescriptor;
9343
9344   DECLARE_VERIFIER(ConsString)
9345
9346  private:
9347   DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9348 };
9349
9350
9351 // The Sliced String class describes strings that are substrings of another
9352 // sequential string.  The motivation is to save time and memory when creating
9353 // a substring.  A Sliced String is described as a pointer to the parent,
9354 // the offset from the start of the parent string and the length.  Using
9355 // a Sliced String therefore requires unpacking of the parent string and
9356 // adding the offset to the start address.  A substring of a Sliced String
9357 // are not nested since the double indirection is simplified when creating
9358 // such a substring.
9359 // Currently missing features are:
9360 //  - handling externalized parent strings
9361 //  - external strings as parent
9362 //  - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9363 class SlicedString: public String {
9364  public:
9365   inline String* parent();
9366   inline void set_parent(String* parent,
9367                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9368   inline int offset() const;
9369   inline void set_offset(int offset);
9370
9371   // Dispatched behavior.
9372   uint16_t SlicedStringGet(int index);
9373
9374   DECLARE_CAST(SlicedString)
9375
9376   // Layout description.
9377   static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9378   static const int kOffsetOffset = kParentOffset + kPointerSize;
9379   static const int kSize = kOffsetOffset + kPointerSize;
9380
9381   // Minimum length for a sliced string.
9382   static const int kMinLength = 13;
9383
9384   typedef FixedBodyDescriptor<kParentOffset,
9385                               kOffsetOffset + kPointerSize, kSize>
9386           BodyDescriptor;
9387
9388   DECLARE_VERIFIER(SlicedString)
9389
9390  private:
9391   DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9392 };
9393
9394
9395 // The ExternalString class describes string values that are backed by
9396 // a string resource that lies outside the V8 heap.  ExternalStrings
9397 // consist of the length field common to all strings, a pointer to the
9398 // external resource.  It is important to ensure (externally) that the
9399 // resource is not deallocated while the ExternalString is live in the
9400 // V8 heap.
9401 //
9402 // The API expects that all ExternalStrings are created through the
9403 // API.  Therefore, ExternalStrings should not be used internally.
9404 class ExternalString: public String {
9405  public:
9406   DECLARE_CAST(ExternalString)
9407
9408   // Layout description.
9409   static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9410   static const int kShortSize = kResourceOffset + kPointerSize;
9411   static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9412   static const int kSize = kResourceDataOffset + kPointerSize;
9413
9414   static const int kMaxShortLength =
9415       (kShortSize - SeqString::kHeaderSize) / kCharSize;
9416
9417   // Return whether external string is short (data pointer is not cached).
9418   inline bool is_short();
9419
9420   STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9421
9422  private:
9423   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9424 };
9425
9426
9427 // The ExternalOneByteString class is an external string backed by an
9428 // one-byte string.
9429 class ExternalOneByteString : public ExternalString {
9430  public:
9431   static const bool kHasOneByteEncoding = true;
9432
9433   typedef v8::String::ExternalOneByteStringResource Resource;
9434
9435   // The underlying resource.
9436   inline const Resource* resource();
9437   inline void set_resource(const Resource* buffer);
9438
9439   // Update the pointer cache to the external character array.
9440   // The cached pointer is always valid, as the external character array does =
9441   // not move during lifetime.  Deserialization is the only exception, after
9442   // which the pointer cache has to be refreshed.
9443   inline void update_data_cache();
9444
9445   inline const uint8_t* GetChars();
9446
9447   // Dispatched behavior.
9448   inline uint16_t ExternalOneByteStringGet(int index);
9449
9450   DECLARE_CAST(ExternalOneByteString)
9451
9452   // Garbage collection support.
9453   inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9454
9455   template <typename StaticVisitor>
9456   inline void ExternalOneByteStringIterateBody();
9457
9458  private:
9459   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9460 };
9461
9462
9463 // The ExternalTwoByteString class is an external string backed by a UTF-16
9464 // encoded string.
9465 class ExternalTwoByteString: public ExternalString {
9466  public:
9467   static const bool kHasOneByteEncoding = false;
9468
9469   typedef v8::String::ExternalStringResource Resource;
9470
9471   // The underlying string resource.
9472   inline const Resource* resource();
9473   inline void set_resource(const Resource* buffer);
9474
9475   // Update the pointer cache to the external character array.
9476   // The cached pointer is always valid, as the external character array does =
9477   // not move during lifetime.  Deserialization is the only exception, after
9478   // which the pointer cache has to be refreshed.
9479   inline void update_data_cache();
9480
9481   inline const uint16_t* GetChars();
9482
9483   // Dispatched behavior.
9484   inline uint16_t ExternalTwoByteStringGet(int index);
9485
9486   // For regexp code.
9487   inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9488
9489   DECLARE_CAST(ExternalTwoByteString)
9490
9491   // Garbage collection support.
9492   inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9493
9494   template<typename StaticVisitor>
9495   inline void ExternalTwoByteStringIterateBody();
9496
9497  private:
9498   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9499 };
9500
9501
9502 // Utility superclass for stack-allocated objects that must be updated
9503 // on gc.  It provides two ways for the gc to update instances, either
9504 // iterating or updating after gc.
9505 class Relocatable BASE_EMBEDDED {
9506  public:
9507   explicit inline Relocatable(Isolate* isolate);
9508   inline virtual ~Relocatable();
9509   virtual void IterateInstance(ObjectVisitor* v) { }
9510   virtual void PostGarbageCollection() { }
9511
9512   static void PostGarbageCollectionProcessing(Isolate* isolate);
9513   static int ArchiveSpacePerThread();
9514   static char* ArchiveState(Isolate* isolate, char* to);
9515   static char* RestoreState(Isolate* isolate, char* from);
9516   static void Iterate(Isolate* isolate, ObjectVisitor* v);
9517   static void Iterate(ObjectVisitor* v, Relocatable* top);
9518   static char* Iterate(ObjectVisitor* v, char* t);
9519
9520  private:
9521   Isolate* isolate_;
9522   Relocatable* prev_;
9523 };
9524
9525
9526 // A flat string reader provides random access to the contents of a
9527 // string independent of the character width of the string.  The handle
9528 // must be valid as long as the reader is being used.
9529 class FlatStringReader : public Relocatable {
9530  public:
9531   FlatStringReader(Isolate* isolate, Handle<String> str);
9532   FlatStringReader(Isolate* isolate, Vector<const char> input);
9533   void PostGarbageCollection();
9534   inline uc32 Get(int index);
9535   template <typename Char>
9536   inline Char Get(int index);
9537   int length() { return length_; }
9538  private:
9539   String** str_;
9540   bool is_one_byte_;
9541   int length_;
9542   const void* start_;
9543 };
9544
9545
9546 // This maintains an off-stack representation of the stack frames required
9547 // to traverse a ConsString, allowing an entirely iterative and restartable
9548 // traversal of the entire string
9549 class ConsStringIterator {
9550  public:
9551   inline ConsStringIterator() {}
9552   inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9553     Reset(cons_string, offset);
9554   }
9555   inline void Reset(ConsString* cons_string, int offset = 0) {
9556     depth_ = 0;
9557     // Next will always return NULL.
9558     if (cons_string == NULL) return;
9559     Initialize(cons_string, offset);
9560   }
9561   // Returns NULL when complete.
9562   inline String* Next(int* offset_out) {
9563     *offset_out = 0;
9564     if (depth_ == 0) return NULL;
9565     return Continue(offset_out);
9566   }
9567
9568  private:
9569   static const int kStackSize = 32;
9570   // Use a mask instead of doing modulo operations for stack wrapping.
9571   static const int kDepthMask = kStackSize-1;
9572   STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9573   static inline int OffsetForDepth(int depth);
9574
9575   inline void PushLeft(ConsString* string);
9576   inline void PushRight(ConsString* string);
9577   inline void AdjustMaximumDepth();
9578   inline void Pop();
9579   inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9580   void Initialize(ConsString* cons_string, int offset);
9581   String* Continue(int* offset_out);
9582   String* NextLeaf(bool* blew_stack);
9583   String* Search(int* offset_out);
9584
9585   // Stack must always contain only frames for which right traversal
9586   // has not yet been performed.
9587   ConsString* frames_[kStackSize];
9588   ConsString* root_;
9589   int depth_;
9590   int maximum_depth_;
9591   int consumed_;
9592   DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9593 };
9594
9595
9596 class StringCharacterStream {
9597  public:
9598   inline StringCharacterStream(String* string,
9599                                int offset = 0);
9600   inline uint16_t GetNext();
9601   inline bool HasMore();
9602   inline void Reset(String* string, int offset = 0);
9603   inline void VisitOneByteString(const uint8_t* chars, int length);
9604   inline void VisitTwoByteString(const uint16_t* chars, int length);
9605
9606  private:
9607   ConsStringIterator iter_;
9608   bool is_one_byte_;
9609   union {
9610     const uint8_t* buffer8_;
9611     const uint16_t* buffer16_;
9612   };
9613   const uint8_t* end_;
9614   DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9615 };
9616
9617
9618 template <typename T>
9619 class VectorIterator {
9620  public:
9621   VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9622   explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9623   T GetNext() { return data_[index_++]; }
9624   bool has_more() { return index_ < data_.length(); }
9625  private:
9626   Vector<const T> data_;
9627   int index_;
9628 };
9629
9630
9631 // The Oddball describes objects null, undefined, true, and false.
9632 class Oddball: public HeapObject {
9633  public:
9634   // [to_string]: Cached to_string computed at startup.
9635   DECL_ACCESSORS(to_string, String)
9636
9637   // [to_number]: Cached to_number computed at startup.
9638   DECL_ACCESSORS(to_number, Object)
9639
9640   inline byte kind() const;
9641   inline void set_kind(byte kind);
9642
9643   DECLARE_CAST(Oddball)
9644
9645   // Dispatched behavior.
9646   DECLARE_VERIFIER(Oddball)
9647
9648   // Initialize the fields.
9649   static void Initialize(Isolate* isolate,
9650                          Handle<Oddball> oddball,
9651                          const char* to_string,
9652                          Handle<Object> to_number,
9653                          byte kind);
9654
9655   // Layout description.
9656   static const int kToStringOffset = HeapObject::kHeaderSize;
9657   static const int kToNumberOffset = kToStringOffset + kPointerSize;
9658   static const int kKindOffset = kToNumberOffset + kPointerSize;
9659   static const int kSize = kKindOffset + kPointerSize;
9660
9661   static const byte kFalse = 0;
9662   static const byte kTrue = 1;
9663   static const byte kNotBooleanMask = ~1;
9664   static const byte kTheHole = 2;
9665   static const byte kNull = 3;
9666   static const byte kArgumentMarker = 4;
9667   static const byte kUndefined = 5;
9668   static const byte kUninitialized = 6;
9669   static const byte kOther = 7;
9670   static const byte kException = 8;
9671
9672   typedef FixedBodyDescriptor<kToStringOffset,
9673                               kToNumberOffset + kPointerSize,
9674                               kSize> BodyDescriptor;
9675
9676   STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9677   STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9678   STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9679
9680  private:
9681   DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9682 };
9683
9684
9685 class Cell: public HeapObject {
9686  public:
9687   // [value]: value of the global property.
9688   DECL_ACCESSORS(value, Object)
9689
9690   DECLARE_CAST(Cell)
9691
9692   static inline Cell* FromValueAddress(Address value) {
9693     Object* result = FromAddress(value - kValueOffset);
9694     DCHECK(result->IsCell() || result->IsPropertyCell());
9695     return static_cast<Cell*>(result);
9696   }
9697
9698   inline Address ValueAddress() {
9699     return address() + kValueOffset;
9700   }
9701
9702   // Dispatched behavior.
9703   DECLARE_PRINTER(Cell)
9704   DECLARE_VERIFIER(Cell)
9705
9706   // Layout description.
9707   static const int kValueOffset = HeapObject::kHeaderSize;
9708   static const int kSize = kValueOffset + kPointerSize;
9709
9710   typedef FixedBodyDescriptor<kValueOffset,
9711                               kValueOffset + kPointerSize,
9712                               kSize> BodyDescriptor;
9713
9714  private:
9715   DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9716 };
9717
9718
9719 class PropertyCell: public Cell {
9720  public:
9721   // [type]: type of the global property.
9722   HeapType* type();
9723   void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9724
9725   // [dependent_code]: dependent code that depends on the type of the global
9726   // property.
9727   DECL_ACCESSORS(dependent_code, DependentCode)
9728
9729   // Sets the value of the cell and updates the type field to be the union
9730   // of the cell's current type and the value's type. If the change causes
9731   // a change of the type of the cell's contents, code dependent on the cell
9732   // will be deoptimized.
9733   // Usually returns the value that was passed in, but may perform
9734   // non-observable modifications on it, such as internalize strings.
9735   static Handle<Object> SetValueInferType(Handle<PropertyCell> cell,
9736                                           Handle<Object> value);
9737
9738   // Computes the new type of the cell's contents for the given value, but
9739   // without actually modifying the 'type' field.
9740   static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9741                                       Handle<Object> value);
9742
9743   static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9744                                           CompilationInfo* info);
9745
9746   DECLARE_CAST(PropertyCell)
9747
9748   inline Address TypeAddress() {
9749     return address() + kTypeOffset;
9750   }
9751
9752   // Dispatched behavior.
9753   DECLARE_PRINTER(PropertyCell)
9754   DECLARE_VERIFIER(PropertyCell)
9755
9756   // Layout description.
9757   static const int kTypeOffset = kValueOffset + kPointerSize;
9758   static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9759   static const int kSize = kDependentCodeOffset + kPointerSize;
9760
9761   static const int kPointerFieldsBeginOffset = kValueOffset;
9762   static const int kPointerFieldsEndOffset = kSize;
9763
9764   typedef FixedBodyDescriptor<kValueOffset,
9765                               kSize,
9766                               kSize> BodyDescriptor;
9767
9768  private:
9769   DECL_ACCESSORS(type_raw, Object)
9770   DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9771 };
9772
9773
9774 class WeakCell : public HeapObject {
9775  public:
9776   inline Object* value() const;
9777
9778   // This should not be called by anyone except GC.
9779   inline void clear();
9780
9781   // This should not be called by anyone except allocator.
9782   inline void initialize(HeapObject* value);
9783
9784   inline bool cleared() const;
9785
9786   DECL_ACCESSORS(next, Object)
9787
9788   DECLARE_CAST(WeakCell)
9789
9790   DECLARE_PRINTER(WeakCell)
9791   DECLARE_VERIFIER(WeakCell)
9792
9793   // Layout description.
9794   static const int kValueOffset = HeapObject::kHeaderSize;
9795   static const int kNextOffset = kValueOffset + kPointerSize;
9796   static const int kSize = kNextOffset + kPointerSize;
9797
9798   typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9799
9800  private:
9801   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9802 };
9803
9804
9805 // The JSProxy describes EcmaScript Harmony proxies
9806 class JSProxy: public JSReceiver {
9807  public:
9808   // [handler]: The handler property.
9809   DECL_ACCESSORS(handler, Object)
9810
9811   // [hash]: The hash code property (undefined if not initialized yet).
9812   DECL_ACCESSORS(hash, Object)
9813
9814   DECLARE_CAST(JSProxy)
9815
9816   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9817       Handle<JSProxy> proxy,
9818       Handle<Object> receiver,
9819       Handle<Name> name);
9820   MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9821       Handle<JSProxy> proxy,
9822       Handle<Object> receiver,
9823       uint32_t index);
9824
9825   // If the handler defines an accessor property with a setter, invoke it.
9826   // If it defines an accessor property without a setter, or a data property
9827   // that is read-only, throw. In all these cases set '*done' to true,
9828   // otherwise set it to false.
9829   MUST_USE_RESULT
9830   static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9831       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9832       Handle<Object> value, LanguageMode language_mode, bool* done);
9833
9834   MUST_USE_RESULT static Maybe<PropertyAttributes>
9835       GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9836                                        Handle<Object> receiver,
9837                                        Handle<Name> name);
9838   MUST_USE_RESULT static Maybe<PropertyAttributes>
9839       GetElementAttributeWithHandler(Handle<JSProxy> proxy,
9840                                      Handle<JSReceiver> receiver,
9841                                      uint32_t index);
9842   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9843       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9844       Handle<Object> value, LanguageMode language_mode);
9845
9846   // Turn the proxy into an (empty) JSObject.
9847   static void Fix(Handle<JSProxy> proxy);
9848
9849   // Initializes the body after the handler slot.
9850   inline void InitializeBody(int object_size, Object* value);
9851
9852   // Invoke a trap by name. If the trap does not exist on this's handler,
9853   // but derived_trap is non-NULL, invoke that instead.  May cause GC.
9854   MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9855       Handle<JSProxy> proxy,
9856       const char* name,
9857       Handle<Object> derived_trap,
9858       int argc,
9859       Handle<Object> args[]);
9860
9861   // Dispatched behavior.
9862   DECLARE_PRINTER(JSProxy)
9863   DECLARE_VERIFIER(JSProxy)
9864
9865   // Layout description. We add padding so that a proxy has the same
9866   // size as a virgin JSObject. This is essential for becoming a JSObject
9867   // upon freeze.
9868   static const int kHandlerOffset = HeapObject::kHeaderSize;
9869   static const int kHashOffset = kHandlerOffset + kPointerSize;
9870   static const int kPaddingOffset = kHashOffset + kPointerSize;
9871   static const int kSize = JSObject::kHeaderSize;
9872   static const int kHeaderSize = kPaddingOffset;
9873   static const int kPaddingSize = kSize - kPaddingOffset;
9874
9875   STATIC_ASSERT(kPaddingSize >= 0);
9876
9877   typedef FixedBodyDescriptor<kHandlerOffset,
9878                               kPaddingOffset,
9879                               kSize> BodyDescriptor;
9880
9881  private:
9882   friend class JSReceiver;
9883
9884   MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
9885       Handle<JSProxy> proxy, Handle<JSReceiver> receiver, uint32_t index,
9886       Handle<Object> value, LanguageMode language_mode);
9887
9888   MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9889       Handle<JSProxy> proxy, Handle<Name> name);
9890   MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
9891       Handle<JSProxy> proxy, uint32_t index);
9892
9893   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9894       Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9895   MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
9896       Handle<JSProxy> proxy, uint32_t index, LanguageMode language_mode);
9897
9898   MUST_USE_RESULT Object* GetIdentityHash();
9899
9900   static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9901
9902   DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9903 };
9904
9905
9906 class JSFunctionProxy: public JSProxy {
9907  public:
9908   // [call_trap]: The call trap.
9909   DECL_ACCESSORS(call_trap, Object)
9910
9911   // [construct_trap]: The construct trap.
9912   DECL_ACCESSORS(construct_trap, Object)
9913
9914   DECLARE_CAST(JSFunctionProxy)
9915
9916   // Dispatched behavior.
9917   DECLARE_PRINTER(JSFunctionProxy)
9918   DECLARE_VERIFIER(JSFunctionProxy)
9919
9920   // Layout description.
9921   static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9922   static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9923   static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9924   static const int kSize = JSFunction::kSize;
9925   static const int kPaddingSize = kSize - kPaddingOffset;
9926
9927   STATIC_ASSERT(kPaddingSize >= 0);
9928
9929   typedef FixedBodyDescriptor<kHandlerOffset,
9930                               kConstructTrapOffset + kPointerSize,
9931                               kSize> BodyDescriptor;
9932
9933  private:
9934   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9935 };
9936
9937
9938 class JSCollection : public JSObject {
9939  public:
9940   // [table]: the backing hash table
9941   DECL_ACCESSORS(table, Object)
9942
9943   static const int kTableOffset = JSObject::kHeaderSize;
9944   static const int kSize = kTableOffset + kPointerSize;
9945
9946  private:
9947   DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9948 };
9949
9950
9951 // The JSSet describes EcmaScript Harmony sets
9952 class JSSet : public JSCollection {
9953  public:
9954   DECLARE_CAST(JSSet)
9955
9956   // Dispatched behavior.
9957   DECLARE_PRINTER(JSSet)
9958   DECLARE_VERIFIER(JSSet)
9959
9960  private:
9961   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9962 };
9963
9964
9965 // The JSMap describes EcmaScript Harmony maps
9966 class JSMap : public JSCollection {
9967  public:
9968   DECLARE_CAST(JSMap)
9969
9970   // Dispatched behavior.
9971   DECLARE_PRINTER(JSMap)
9972   DECLARE_VERIFIER(JSMap)
9973
9974  private:
9975   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9976 };
9977
9978
9979 // OrderedHashTableIterator is an iterator that iterates over the keys and
9980 // values of an OrderedHashTable.
9981 //
9982 // The iterator has a reference to the underlying OrderedHashTable data,
9983 // [table], as well as the current [index] the iterator is at.
9984 //
9985 // When the OrderedHashTable is rehashed it adds a reference from the old table
9986 // to the new table as well as storing enough data about the changes so that the
9987 // iterator [index] can be adjusted accordingly.
9988 //
9989 // When the [Next] result from the iterator is requested, the iterator checks if
9990 // there is a newer table that it needs to transition to.
9991 template<class Derived, class TableType>
9992 class OrderedHashTableIterator: public JSObject {
9993  public:
9994   // [table]: the backing hash table mapping keys to values.
9995   DECL_ACCESSORS(table, Object)
9996
9997   // [index]: The index into the data table.
9998   DECL_ACCESSORS(index, Object)
9999
10000   // [kind]: The kind of iteration this is. One of the [Kind] enum values.
10001   DECL_ACCESSORS(kind, Object)
10002
10003 #ifdef OBJECT_PRINT
10004   void OrderedHashTableIteratorPrint(std::ostream& os);  // NOLINT
10005 #endif
10006
10007   static const int kTableOffset = JSObject::kHeaderSize;
10008   static const int kIndexOffset = kTableOffset + kPointerSize;
10009   static const int kKindOffset = kIndexOffset + kPointerSize;
10010   static const int kSize = kKindOffset + kPointerSize;
10011
10012   enum Kind {
10013     kKindKeys = 1,
10014     kKindValues = 2,
10015     kKindEntries = 3
10016   };
10017
10018   // Whether the iterator has more elements. This needs to be called before
10019   // calling |CurrentKey| and/or |CurrentValue|.
10020   bool HasMore();
10021
10022   // Move the index forward one.
10023   void MoveNext() {
10024     set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
10025   }
10026
10027   // Populates the array with the next key and value and then moves the iterator
10028   // forward.
10029   // This returns the |kind| or 0 if the iterator is already at the end.
10030   Smi* Next(JSArray* value_array);
10031
10032   // Returns the current key of the iterator. This should only be called when
10033   // |HasMore| returns true.
10034   inline Object* CurrentKey();
10035
10036  private:
10037   // Transitions the iterator to the non obsolete backing store. This is a NOP
10038   // if the [table] is not obsolete.
10039   void Transition();
10040
10041   DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
10042 };
10043
10044
10045 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
10046                                                      OrderedHashSet> {
10047  public:
10048   // Dispatched behavior.
10049   DECLARE_PRINTER(JSSetIterator)
10050   DECLARE_VERIFIER(JSSetIterator)
10051
10052   DECLARE_CAST(JSSetIterator)
10053
10054   // Called by |Next| to populate the array. This allows the subclasses to
10055   // populate the array differently.
10056   inline void PopulateValueArray(FixedArray* array);
10057
10058  private:
10059   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
10060 };
10061
10062
10063 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
10064                                                      OrderedHashMap> {
10065  public:
10066   // Dispatched behavior.
10067   DECLARE_PRINTER(JSMapIterator)
10068   DECLARE_VERIFIER(JSMapIterator)
10069
10070   DECLARE_CAST(JSMapIterator)
10071
10072   // Called by |Next| to populate the array. This allows the subclasses to
10073   // populate the array differently.
10074   inline void PopulateValueArray(FixedArray* array);
10075
10076  private:
10077   // Returns the current value of the iterator. This should only be called when
10078   // |HasMore| returns true.
10079   inline Object* CurrentValue();
10080
10081   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
10082 };
10083
10084
10085 // Base class for both JSWeakMap and JSWeakSet
10086 class JSWeakCollection: public JSObject {
10087  public:
10088   // [table]: the backing hash table mapping keys to values.
10089   DECL_ACCESSORS(table, Object)
10090
10091   // [next]: linked list of encountered weak maps during GC.
10092   DECL_ACCESSORS(next, Object)
10093
10094   static const int kTableOffset = JSObject::kHeaderSize;
10095   static const int kNextOffset = kTableOffset + kPointerSize;
10096   static const int kSize = kNextOffset + kPointerSize;
10097
10098  private:
10099   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10100 };
10101
10102
10103 // The JSWeakMap describes EcmaScript Harmony weak maps
10104 class JSWeakMap: public JSWeakCollection {
10105  public:
10106   DECLARE_CAST(JSWeakMap)
10107
10108   // Dispatched behavior.
10109   DECLARE_PRINTER(JSWeakMap)
10110   DECLARE_VERIFIER(JSWeakMap)
10111
10112  private:
10113   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10114 };
10115
10116
10117 // The JSWeakSet describes EcmaScript Harmony weak sets
10118 class JSWeakSet: public JSWeakCollection {
10119  public:
10120   DECLARE_CAST(JSWeakSet)
10121
10122   // Dispatched behavior.
10123   DECLARE_PRINTER(JSWeakSet)
10124   DECLARE_VERIFIER(JSWeakSet)
10125
10126  private:
10127   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10128 };
10129
10130
10131 class JSArrayBuffer: public JSObject {
10132  public:
10133   // [backing_store]: backing memory for this array
10134   DECL_ACCESSORS(backing_store, void)
10135
10136   // [byte_length]: length in bytes
10137   DECL_ACCESSORS(byte_length, Object)
10138
10139   // [flags]
10140   DECL_ACCESSORS(flag, Smi)
10141
10142   inline bool is_external();
10143   inline void set_is_external(bool value);
10144
10145   inline bool should_be_freed();
10146   inline void set_should_be_freed(bool value);
10147
10148   inline bool is_neuterable();
10149   inline void set_is_neuterable(bool value);
10150
10151   // [weak_next]: linked list of array buffers.
10152   DECL_ACCESSORS(weak_next, Object)
10153
10154   // [weak_first_array]: weak linked list of views.
10155   DECL_ACCESSORS(weak_first_view, Object)
10156
10157   DECLARE_CAST(JSArrayBuffer)
10158
10159   // Neutering. Only neuters the buffer, not associated typed arrays.
10160   void Neuter();
10161
10162   // Dispatched behavior.
10163   DECLARE_PRINTER(JSArrayBuffer)
10164   DECLARE_VERIFIER(JSArrayBuffer)
10165
10166   static const int kBackingStoreOffset = JSObject::kHeaderSize;
10167   static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10168   static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10169   static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10170   static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10171   static const int kSize = kWeakFirstViewOffset + kPointerSize;
10172
10173   static const int kSizeWithInternalFields =
10174       kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10175
10176  private:
10177   // Bit position in a flag
10178   static const int kIsExternalBit = 0;
10179   static const int kShouldBeFreed = 1;
10180   static const int kIsNeuterableBit = 2;
10181
10182   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10183 };
10184
10185
10186 class JSArrayBufferView: public JSObject {
10187  public:
10188   // [buffer]: ArrayBuffer that this typed array views.
10189   DECL_ACCESSORS(buffer, Object)
10190
10191   // [byte_length]: offset of typed array in bytes.
10192   DECL_ACCESSORS(byte_offset, Object)
10193
10194   // [byte_length]: length of typed array in bytes.
10195   DECL_ACCESSORS(byte_length, Object)
10196
10197   // [weak_next]: linked list of typed arrays over the same array buffer.
10198   DECL_ACCESSORS(weak_next, Object)
10199
10200   DECLARE_CAST(JSArrayBufferView)
10201
10202   DECLARE_VERIFIER(JSArrayBufferView)
10203
10204   static const int kBufferOffset = JSObject::kHeaderSize;
10205   static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10206   static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10207   static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10208   static const int kViewSize = kWeakNextOffset + kPointerSize;
10209
10210  protected:
10211   void NeuterView();
10212
10213  private:
10214   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10215 };
10216
10217
10218 class JSTypedArray: public JSArrayBufferView {
10219  public:
10220   // [length]: length of typed array in elements.
10221   DECL_ACCESSORS(length, Object)
10222
10223   // Neutering. Only neuters this typed array.
10224   void Neuter();
10225
10226   DECLARE_CAST(JSTypedArray)
10227
10228   ExternalArrayType type();
10229   size_t element_size();
10230
10231   Handle<JSArrayBuffer> GetBuffer();
10232
10233   // Dispatched behavior.
10234   DECLARE_PRINTER(JSTypedArray)
10235   DECLARE_VERIFIER(JSTypedArray)
10236
10237   static const int kLengthOffset = kViewSize + kPointerSize;
10238   static const int kSize = kLengthOffset + kPointerSize;
10239
10240   static const int kSizeWithInternalFields =
10241       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10242
10243  private:
10244   static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10245       Handle<JSTypedArray> typed_array);
10246
10247   DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10248 };
10249
10250
10251 class JSDataView: public JSArrayBufferView {
10252  public:
10253   // Only neuters this DataView
10254   void Neuter();
10255
10256   DECLARE_CAST(JSDataView)
10257
10258   // Dispatched behavior.
10259   DECLARE_PRINTER(JSDataView)
10260   DECLARE_VERIFIER(JSDataView)
10261
10262   static const int kSize = kViewSize;
10263
10264   static const int kSizeWithInternalFields =
10265       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10266
10267  private:
10268   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10269 };
10270
10271
10272 // Foreign describes objects pointing from JavaScript to C structures.
10273 // Since they cannot contain references to JS HeapObjects they can be
10274 // placed in old_data_space.
10275 class Foreign: public HeapObject {
10276  public:
10277   // [address]: field containing the address.
10278   inline Address foreign_address();
10279   inline void set_foreign_address(Address value);
10280
10281   DECLARE_CAST(Foreign)
10282
10283   // Dispatched behavior.
10284   inline void ForeignIterateBody(ObjectVisitor* v);
10285
10286   template<typename StaticVisitor>
10287   inline void ForeignIterateBody();
10288
10289   // Dispatched behavior.
10290   DECLARE_PRINTER(Foreign)
10291   DECLARE_VERIFIER(Foreign)
10292
10293   // Layout description.
10294
10295   static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10296   static const int kSize = kForeignAddressOffset + kPointerSize;
10297
10298   STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10299
10300  private:
10301   DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10302 };
10303
10304
10305 // The JSArray describes JavaScript Arrays
10306 //  Such an array can be in one of two modes:
10307 //    - fast, backing storage is a FixedArray and length <= elements.length();
10308 //       Please note: push and pop can be used to grow and shrink the array.
10309 //    - slow, backing storage is a HashTable with numbers as keys.
10310 class JSArray: public JSObject {
10311  public:
10312   // [length]: The length property.
10313   DECL_ACCESSORS(length, Object)
10314
10315   // Overload the length setter to skip write barrier when the length
10316   // is set to a smi. This matches the set function on FixedArray.
10317   inline void set_length(Smi* length);
10318
10319   static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10320                                            uint32_t index,
10321                                            Handle<Object> value);
10322
10323   static bool HasReadOnlyLength(Handle<JSArray> array);
10324   static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10325   static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10326
10327   // Initialize the array with the given capacity. The function may
10328   // fail due to out-of-memory situations, but only if the requested
10329   // capacity is non-zero.
10330   static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10331
10332   // Initializes the array to a certain length.
10333   inline bool AllowsSetElementsLength();
10334   // Can cause GC.
10335   MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10336       Handle<JSArray> array,
10337       Handle<Object> length);
10338
10339   // Set the content of the array to the content of storage.
10340   static inline void SetContent(Handle<JSArray> array,
10341                                 Handle<FixedArrayBase> storage);
10342
10343   DECLARE_CAST(JSArray)
10344
10345   // Ensures that the fixed array backing the JSArray has at
10346   // least the stated size.
10347   static inline void EnsureSize(Handle<JSArray> array,
10348                                 int minimum_size_of_backing_fixed_array);
10349
10350   // Expand the fixed array backing of a fast-case JSArray to at least
10351   // the requested size.
10352   static void Expand(Handle<JSArray> array,
10353                      int minimum_size_of_backing_fixed_array);
10354
10355   // Dispatched behavior.
10356   DECLARE_PRINTER(JSArray)
10357   DECLARE_VERIFIER(JSArray)
10358
10359   // Number of element slots to pre-allocate for an empty array.
10360   static const int kPreallocatedArrayElements = 4;
10361
10362   // Layout description.
10363   static const int kLengthOffset = JSObject::kHeaderSize;
10364   static const int kSize = kLengthOffset + kPointerSize;
10365
10366  private:
10367   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10368 };
10369
10370
10371 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10372                                        Handle<Map> initial_map);
10373
10374
10375 // JSRegExpResult is just a JSArray with a specific initial map.
10376 // This initial map adds in-object properties for "index" and "input"
10377 // properties, as assigned by RegExp.prototype.exec, which allows
10378 // faster creation of RegExp exec results.
10379 // This class just holds constants used when creating the result.
10380 // After creation the result must be treated as a JSArray in all regards.
10381 class JSRegExpResult: public JSArray {
10382  public:
10383   // Offsets of object fields.
10384   static const int kIndexOffset = JSArray::kSize;
10385   static const int kInputOffset = kIndexOffset + kPointerSize;
10386   static const int kSize = kInputOffset + kPointerSize;
10387   // Indices of in-object properties.
10388   static const int kIndexIndex = 0;
10389   static const int kInputIndex = 1;
10390  private:
10391   DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10392 };
10393
10394
10395 class AccessorInfo: public Struct {
10396  public:
10397   DECL_ACCESSORS(name, Object)
10398   DECL_ACCESSORS(flag, Smi)
10399   DECL_ACCESSORS(expected_receiver_type, Object)
10400
10401   inline bool all_can_read();
10402   inline void set_all_can_read(bool value);
10403
10404   inline bool all_can_write();
10405   inline void set_all_can_write(bool value);
10406
10407   inline PropertyAttributes property_attributes();
10408   inline void set_property_attributes(PropertyAttributes attributes);
10409
10410   // Checks whether the given receiver is compatible with this accessor.
10411   static bool IsCompatibleReceiverMap(Isolate* isolate,
10412                                       Handle<AccessorInfo> info,
10413                                       Handle<Map> map);
10414   inline bool IsCompatibleReceiver(Object* receiver);
10415
10416   DECLARE_CAST(AccessorInfo)
10417
10418   // Dispatched behavior.
10419   DECLARE_VERIFIER(AccessorInfo)
10420
10421   // Append all descriptors to the array that are not already there.
10422   // Return number added.
10423   static int AppendUnique(Handle<Object> descriptors,
10424                           Handle<FixedArray> array,
10425                           int valid_descriptors);
10426
10427   static const int kNameOffset = HeapObject::kHeaderSize;
10428   static const int kFlagOffset = kNameOffset + kPointerSize;
10429   static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10430   static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10431
10432  private:
10433   inline bool HasExpectedReceiverType() {
10434     return expected_receiver_type()->IsFunctionTemplateInfo();
10435   }
10436   // Bit positions in flag.
10437   static const int kAllCanReadBit = 0;
10438   static const int kAllCanWriteBit = 1;
10439   class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10440
10441   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10442 };
10443
10444
10445 // An accessor must have a getter, but can have no setter.
10446 //
10447 // When setting a property, V8 searches accessors in prototypes.
10448 // If an accessor was found and it does not have a setter,
10449 // the request is ignored.
10450 //
10451 // If the accessor in the prototype has the READ_ONLY property attribute, then
10452 // a new value is added to the derived object when the property is set.
10453 // This shadows the accessor in the prototype.
10454 class ExecutableAccessorInfo: public AccessorInfo {
10455  public:
10456   DECL_ACCESSORS(getter, Object)
10457   DECL_ACCESSORS(setter, Object)
10458   DECL_ACCESSORS(data, Object)
10459
10460   DECLARE_CAST(ExecutableAccessorInfo)
10461
10462   // Dispatched behavior.
10463   DECLARE_PRINTER(ExecutableAccessorInfo)
10464   DECLARE_VERIFIER(ExecutableAccessorInfo)
10465
10466   static const int kGetterOffset = AccessorInfo::kSize;
10467   static const int kSetterOffset = kGetterOffset + kPointerSize;
10468   static const int kDataOffset = kSetterOffset + kPointerSize;
10469   static const int kSize = kDataOffset + kPointerSize;
10470
10471   inline void clear_setter();
10472
10473  private:
10474   DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10475 };
10476
10477
10478 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10479 // accessor can either be
10480 //   * a pointer to a JavaScript function or proxy: a real accessor
10481 //   * undefined: considered an accessor by the spec, too, strangely enough
10482 //   * the hole: an accessor which has not been set
10483 //   * a pointer to a map: a transition used to ensure map sharing
10484 class AccessorPair: public Struct {
10485  public:
10486   DECL_ACCESSORS(getter, Object)
10487   DECL_ACCESSORS(setter, Object)
10488
10489   DECLARE_CAST(AccessorPair)
10490
10491   static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10492
10493   Object* get(AccessorComponent component) {
10494     return component == ACCESSOR_GETTER ? getter() : setter();
10495   }
10496
10497   void set(AccessorComponent component, Object* value) {
10498     if (component == ACCESSOR_GETTER) {
10499       set_getter(value);
10500     } else {
10501       set_setter(value);
10502     }
10503   }
10504
10505   // Note: Returns undefined instead in case of a hole.
10506   Object* GetComponent(AccessorComponent component);
10507
10508   // Set both components, skipping arguments which are a JavaScript null.
10509   void SetComponents(Object* getter, Object* setter) {
10510     if (!getter->IsNull()) set_getter(getter);
10511     if (!setter->IsNull()) set_setter(setter);
10512   }
10513
10514   bool Equals(AccessorPair* pair) {
10515     return (this == pair) || pair->Equals(getter(), setter());
10516   }
10517
10518   bool Equals(Object* getter_value, Object* setter_value) {
10519     return (getter() == getter_value) && (setter() == setter_value);
10520   }
10521
10522   bool ContainsAccessor() {
10523     return IsJSAccessor(getter()) || IsJSAccessor(setter());
10524   }
10525
10526   // Dispatched behavior.
10527   DECLARE_PRINTER(AccessorPair)
10528   DECLARE_VERIFIER(AccessorPair)
10529
10530   static const int kGetterOffset = HeapObject::kHeaderSize;
10531   static const int kSetterOffset = kGetterOffset + kPointerSize;
10532   static const int kSize = kSetterOffset + kPointerSize;
10533
10534  private:
10535   // Strangely enough, in addition to functions and harmony proxies, the spec
10536   // requires us to consider undefined as a kind of accessor, too:
10537   //    var obj = {};
10538   //    Object.defineProperty(obj, "foo", {get: undefined});
10539   //    assertTrue("foo" in obj);
10540   bool IsJSAccessor(Object* obj) {
10541     return obj->IsSpecFunction() || obj->IsUndefined();
10542   }
10543
10544   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10545 };
10546
10547
10548 class AccessCheckInfo: public Struct {
10549  public:
10550   DECL_ACCESSORS(named_callback, Object)
10551   DECL_ACCESSORS(indexed_callback, Object)
10552   DECL_ACCESSORS(data, Object)
10553
10554   DECLARE_CAST(AccessCheckInfo)
10555
10556   // Dispatched behavior.
10557   DECLARE_PRINTER(AccessCheckInfo)
10558   DECLARE_VERIFIER(AccessCheckInfo)
10559
10560   static const int kNamedCallbackOffset   = HeapObject::kHeaderSize;
10561   static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10562   static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10563   static const int kSize = kDataOffset + kPointerSize;
10564
10565  private:
10566   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10567 };
10568
10569
10570 class InterceptorInfo: public Struct {
10571  public:
10572   DECL_ACCESSORS(getter, Object)
10573   DECL_ACCESSORS(setter, Object)
10574   DECL_ACCESSORS(query, Object)
10575   DECL_ACCESSORS(deleter, Object)
10576   DECL_ACCESSORS(enumerator, Object)
10577   DECL_ACCESSORS(data, Object)
10578   DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10579   DECL_BOOLEAN_ACCESSORS(all_can_read)
10580
10581   inline int flags() const;
10582   inline void set_flags(int flags);
10583
10584   DECLARE_CAST(InterceptorInfo)
10585
10586   // Dispatched behavior.
10587   DECLARE_PRINTER(InterceptorInfo)
10588   DECLARE_VERIFIER(InterceptorInfo)
10589
10590   static const int kGetterOffset = HeapObject::kHeaderSize;
10591   static const int kSetterOffset = kGetterOffset + kPointerSize;
10592   static const int kQueryOffset = kSetterOffset + kPointerSize;
10593   static const int kDeleterOffset = kQueryOffset + kPointerSize;
10594   static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10595   static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10596   static const int kFlagsOffset = kDataOffset + kPointerSize;
10597   static const int kSize = kFlagsOffset + kPointerSize;
10598
10599   static const int kCanInterceptSymbolsBit = 0;
10600   static const int kAllCanReadBit = 1;
10601
10602  private:
10603   DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10604 };
10605
10606
10607 class CallHandlerInfo: public Struct {
10608  public:
10609   DECL_ACCESSORS(callback, Object)
10610   DECL_ACCESSORS(data, Object)
10611
10612   DECLARE_CAST(CallHandlerInfo)
10613
10614   // Dispatched behavior.
10615   DECLARE_PRINTER(CallHandlerInfo)
10616   DECLARE_VERIFIER(CallHandlerInfo)
10617
10618   static const int kCallbackOffset = HeapObject::kHeaderSize;
10619   static const int kDataOffset = kCallbackOffset + kPointerSize;
10620   static const int kSize = kDataOffset + kPointerSize;
10621
10622  private:
10623   DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10624 };
10625
10626
10627 class TemplateInfo: public Struct {
10628  public:
10629   DECL_ACCESSORS(tag, Object)
10630   DECL_ACCESSORS(property_list, Object)
10631   DECL_ACCESSORS(property_accessors, Object)
10632
10633   DECLARE_VERIFIER(TemplateInfo)
10634
10635   static const int kTagOffset = HeapObject::kHeaderSize;
10636   static const int kPropertyListOffset = kTagOffset + kPointerSize;
10637   static const int kPropertyAccessorsOffset =
10638       kPropertyListOffset + kPointerSize;
10639   static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10640
10641  private:
10642   DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10643 };
10644
10645
10646 class FunctionTemplateInfo: public TemplateInfo {
10647  public:
10648   DECL_ACCESSORS(serial_number, Object)
10649   DECL_ACCESSORS(call_code, Object)
10650   DECL_ACCESSORS(prototype_template, Object)
10651   DECL_ACCESSORS(parent_template, Object)
10652   DECL_ACCESSORS(named_property_handler, Object)
10653   DECL_ACCESSORS(indexed_property_handler, Object)
10654   DECL_ACCESSORS(instance_template, Object)
10655   DECL_ACCESSORS(class_name, Object)
10656   DECL_ACCESSORS(signature, Object)
10657   DECL_ACCESSORS(instance_call_handler, Object)
10658   DECL_ACCESSORS(access_check_info, Object)
10659   DECL_ACCESSORS(flag, Smi)
10660
10661   inline int length() const;
10662   inline void set_length(int value);
10663
10664   // Following properties use flag bits.
10665   DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10666   DECL_BOOLEAN_ACCESSORS(undetectable)
10667   // If the bit is set, object instances created by this function
10668   // requires access check.
10669   DECL_BOOLEAN_ACCESSORS(needs_access_check)
10670   DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10671   DECL_BOOLEAN_ACCESSORS(remove_prototype)
10672   DECL_BOOLEAN_ACCESSORS(do_not_cache)
10673   DECL_BOOLEAN_ACCESSORS(instantiated)
10674
10675   DECLARE_CAST(FunctionTemplateInfo)
10676
10677   // Dispatched behavior.
10678   DECLARE_PRINTER(FunctionTemplateInfo)
10679   DECLARE_VERIFIER(FunctionTemplateInfo)
10680
10681   static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10682   static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10683   static const int kPrototypeTemplateOffset =
10684       kCallCodeOffset + kPointerSize;
10685   static const int kParentTemplateOffset =
10686       kPrototypeTemplateOffset + kPointerSize;
10687   static const int kNamedPropertyHandlerOffset =
10688       kParentTemplateOffset + kPointerSize;
10689   static const int kIndexedPropertyHandlerOffset =
10690       kNamedPropertyHandlerOffset + kPointerSize;
10691   static const int kInstanceTemplateOffset =
10692       kIndexedPropertyHandlerOffset + kPointerSize;
10693   static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10694   static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10695   static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10696   static const int kAccessCheckInfoOffset =
10697       kInstanceCallHandlerOffset + kPointerSize;
10698   static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10699   static const int kLengthOffset = kFlagOffset + kPointerSize;
10700   static const int kSize = kLengthOffset + kPointerSize;
10701
10702   // Returns true if |object| is an instance of this function template.
10703   bool IsTemplateFor(Object* object);
10704   bool IsTemplateFor(Map* map);
10705
10706   // Returns the holder JSObject if the function can legally be called with this
10707   // receiver.  Returns Heap::null_value() if the call is illegal.
10708   Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10709
10710  private:
10711   // Bit position in the flag, from least significant bit position.
10712   static const int kHiddenPrototypeBit   = 0;
10713   static const int kUndetectableBit      = 1;
10714   static const int kNeedsAccessCheckBit  = 2;
10715   static const int kReadOnlyPrototypeBit = 3;
10716   static const int kRemovePrototypeBit   = 4;
10717   static const int kDoNotCacheBit        = 5;
10718   static const int kInstantiatedBit      = 6;
10719
10720   DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10721 };
10722
10723
10724 class ObjectTemplateInfo: public TemplateInfo {
10725  public:
10726   DECL_ACCESSORS(constructor, Object)
10727   DECL_ACCESSORS(internal_field_count, Object)
10728
10729   DECLARE_CAST(ObjectTemplateInfo)
10730
10731   // Dispatched behavior.
10732   DECLARE_PRINTER(ObjectTemplateInfo)
10733   DECLARE_VERIFIER(ObjectTemplateInfo)
10734
10735   static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10736   static const int kInternalFieldCountOffset =
10737       kConstructorOffset + kPointerSize;
10738   static const int kSize = kInternalFieldCountOffset + kPointerSize;
10739 };
10740
10741
10742 class TypeSwitchInfo: public Struct {
10743  public:
10744   DECL_ACCESSORS(types, Object)
10745
10746   DECLARE_CAST(TypeSwitchInfo)
10747
10748   // Dispatched behavior.
10749   DECLARE_PRINTER(TypeSwitchInfo)
10750   DECLARE_VERIFIER(TypeSwitchInfo)
10751
10752   static const int kTypesOffset = Struct::kHeaderSize;
10753   static const int kSize        = kTypesOffset + kPointerSize;
10754 };
10755
10756
10757 // The DebugInfo class holds additional information for a function being
10758 // debugged.
10759 class DebugInfo: public Struct {
10760  public:
10761   // The shared function info for the source being debugged.
10762   DECL_ACCESSORS(shared, SharedFunctionInfo)
10763   // Code object for the original code.
10764   DECL_ACCESSORS(original_code, Code)
10765   // Code object for the patched code. This code object is the code object
10766   // currently active for the function.
10767   DECL_ACCESSORS(code, Code)
10768   // Fixed array holding status information for each active break point.
10769   DECL_ACCESSORS(break_points, FixedArray)
10770
10771   // Check if there is a break point at a code position.
10772   bool HasBreakPoint(int code_position);
10773   // Get the break point info object for a code position.
10774   Object* GetBreakPointInfo(int code_position);
10775   // Clear a break point.
10776   static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10777                               int code_position,
10778                               Handle<Object> break_point_object);
10779   // Set a break point.
10780   static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10781                             int source_position, int statement_position,
10782                             Handle<Object> break_point_object);
10783   // Get the break point objects for a code position.
10784   Object* GetBreakPointObjects(int code_position);
10785   // Find the break point info holding this break point object.
10786   static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10787                                     Handle<Object> break_point_object);
10788   // Get the number of break points for this function.
10789   int GetBreakPointCount();
10790
10791   DECLARE_CAST(DebugInfo)
10792
10793   // Dispatched behavior.
10794   DECLARE_PRINTER(DebugInfo)
10795   DECLARE_VERIFIER(DebugInfo)
10796
10797   static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10798   static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10799   static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10800   static const int kActiveBreakPointsCountIndex =
10801       kPatchedCodeIndex + kPointerSize;
10802   static const int kBreakPointsStateIndex =
10803       kActiveBreakPointsCountIndex + kPointerSize;
10804   static const int kSize = kBreakPointsStateIndex + kPointerSize;
10805
10806   static const int kEstimatedNofBreakPointsInFunction = 16;
10807
10808  private:
10809   static const int kNoBreakPointInfo = -1;
10810
10811   // Lookup the index in the break_points array for a code position.
10812   int GetBreakPointInfoIndex(int code_position);
10813
10814   DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10815 };
10816
10817
10818 // The BreakPointInfo class holds information for break points set in a
10819 // function. The DebugInfo object holds a BreakPointInfo object for each code
10820 // position with one or more break points.
10821 class BreakPointInfo: public Struct {
10822  public:
10823   // The position in the code for the break point.
10824   DECL_ACCESSORS(code_position, Smi)
10825   // The position in the source for the break position.
10826   DECL_ACCESSORS(source_position, Smi)
10827   // The position in the source for the last statement before this break
10828   // position.
10829   DECL_ACCESSORS(statement_position, Smi)
10830   // List of related JavaScript break points.
10831   DECL_ACCESSORS(break_point_objects, Object)
10832
10833   // Removes a break point.
10834   static void ClearBreakPoint(Handle<BreakPointInfo> info,
10835                               Handle<Object> break_point_object);
10836   // Set a break point.
10837   static void SetBreakPoint(Handle<BreakPointInfo> info,
10838                             Handle<Object> break_point_object);
10839   // Check if break point info has this break point object.
10840   static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10841                                   Handle<Object> break_point_object);
10842   // Get the number of break points for this code position.
10843   int GetBreakPointCount();
10844
10845   DECLARE_CAST(BreakPointInfo)
10846
10847   // Dispatched behavior.
10848   DECLARE_PRINTER(BreakPointInfo)
10849   DECLARE_VERIFIER(BreakPointInfo)
10850
10851   static const int kCodePositionIndex = Struct::kHeaderSize;
10852   static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10853   static const int kStatementPositionIndex =
10854       kSourcePositionIndex + kPointerSize;
10855   static const int kBreakPointObjectsIndex =
10856       kStatementPositionIndex + kPointerSize;
10857   static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10858
10859  private:
10860   DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10861 };
10862
10863
10864 #undef DECL_BOOLEAN_ACCESSORS
10865 #undef DECL_ACCESSORS
10866 #undef DECLARE_CAST
10867 #undef DECLARE_VERIFIER
10868
10869 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V)                            \
10870   V(kStringTable, "string_table", "(Internalized strings)")             \
10871   V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10872   V(kStrongRootList, "strong_root_list", "(Strong roots)")              \
10873   V(kSmiRootList, "smi_root_list", "(Smi roots)")                       \
10874   V(kInternalizedString, "internalized_string", "(Internal string)")    \
10875   V(kBootstrapper, "bootstrapper", "(Bootstrapper)")                    \
10876   V(kTop, "top", "(Isolate)")                                           \
10877   V(kRelocatable, "relocatable", "(Relocatable)")                       \
10878   V(kDebug, "debug", "(Debugger)")                                      \
10879   V(kCompilationCache, "compilationcache", "(Compilation cache)")       \
10880   V(kHandleScope, "handlescope", "(Handle scope)")                      \
10881   V(kBuiltins, "builtins", "(Builtins)")                                \
10882   V(kGlobalHandles, "globalhandles", "(Global handles)")                \
10883   V(kEternalHandles, "eternalhandles", "(Eternal handles)")             \
10884   V(kThreadManager, "threadmanager", "(Thread manager)")                \
10885   V(kExtensions, "Extensions", "(Extensions)")
10886
10887 class VisitorSynchronization : public AllStatic {
10888  public:
10889 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10890   enum SyncTag {
10891     VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10892     kNumberOfSyncTags
10893   };
10894 #undef DECLARE_ENUM
10895
10896   static const char* const kTags[kNumberOfSyncTags];
10897   static const char* const kTagNames[kNumberOfSyncTags];
10898 };
10899
10900 // Abstract base class for visiting, and optionally modifying, the
10901 // pointers contained in Objects. Used in GC and serialization/deserialization.
10902 class ObjectVisitor BASE_EMBEDDED {
10903  public:
10904   virtual ~ObjectVisitor() {}
10905
10906   // Visits a contiguous arrays of pointers in the half-open range
10907   // [start, end). Any or all of the values may be modified on return.
10908   virtual void VisitPointers(Object** start, Object** end) = 0;
10909
10910   // Handy shorthand for visiting a single pointer.
10911   virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10912
10913   // Visit weak next_code_link in Code object.
10914   virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10915
10916   // To allow lazy clearing of inline caches the visitor has
10917   // a rich interface for iterating over Code objects..
10918
10919   // Visits a code target in the instruction stream.
10920   virtual void VisitCodeTarget(RelocInfo* rinfo);
10921
10922   // Visits a code entry in a JS function.
10923   virtual void VisitCodeEntry(Address entry_address);
10924
10925   // Visits a global property cell reference in the instruction stream.
10926   virtual void VisitCell(RelocInfo* rinfo);
10927
10928   // Visits a runtime entry in the instruction stream.
10929   virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10930
10931   // Visits the resource of an one-byte or two-byte string.
10932   virtual void VisitExternalOneByteString(
10933       v8::String::ExternalOneByteStringResource** resource) {}
10934   virtual void VisitExternalTwoByteString(
10935       v8::String::ExternalStringResource** resource) {}
10936
10937   // Visits a debug call target in the instruction stream.
10938   virtual void VisitDebugTarget(RelocInfo* rinfo);
10939
10940   // Visits the byte sequence in a function's prologue that contains information
10941   // about the code's age.
10942   virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10943
10944   // Visit pointer embedded into a code object.
10945   virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10946
10947   // Visits an external reference embedded into a code object.
10948   virtual void VisitExternalReference(RelocInfo* rinfo);
10949
10950   // Visits an external reference. The value may be modified on return.
10951   virtual void VisitExternalReference(Address* p) {}
10952
10953   // Visits a handle that has an embedder-assigned class ID.
10954   virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10955
10956   // Intended for serialization/deserialization checking: insert, or
10957   // check for the presence of, a tag at this position in the stream.
10958   // Also used for marking up GC roots in heap snapshots.
10959   virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10960 };
10961
10962
10963 class StructBodyDescriptor : public
10964   FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10965  public:
10966   static inline int SizeOf(Map* map, HeapObject* object) {
10967     return map->instance_size();
10968   }
10969 };
10970
10971
10972 // BooleanBit is a helper class for setting and getting a bit in an
10973 // integer or Smi.
10974 class BooleanBit : public AllStatic {
10975  public:
10976   static inline bool get(Smi* smi, int bit_position) {
10977     return get(smi->value(), bit_position);
10978   }
10979
10980   static inline bool get(int value, int bit_position) {
10981     return (value & (1 << bit_position)) != 0;
10982   }
10983
10984   static inline Smi* set(Smi* smi, int bit_position, bool v) {
10985     return Smi::FromInt(set(smi->value(), bit_position, v));
10986   }
10987
10988   static inline int set(int value, int bit_position, bool v) {
10989     if (v) {
10990       value |= (1 << bit_position);
10991     } else {
10992       value &= ~(1 << bit_position);
10993     }
10994     return value;
10995   }
10996 };
10997
10998 } }  // namespace v8::internal
10999
11000 #endif  // V8_OBJECTS_H_