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