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