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