Upstream version 11.39.258.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(static_cast<int>(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 #define TYPED_ARRAYS_SIMD_LOAD_OPERATIONS(V)                                   \
6826   V(Float32Array.prototype, _getFloat32x4XYZW, Float32ArrayGetFloat32x4XYZW)   \
6827   V(Float32Array.prototype, _getFloat32x4XYZ, Float32ArrayGetFloat32x4XYZ)     \
6828   V(Float32Array.prototype, _getFloat32x4XY, Float32ArrayGetFloat32x4XY)       \
6829   V(Float32Array.prototype, _getFloat32x4X, Float32ArrayGetFloat32x4X)         \
6830   V(Float64Array.prototype, _getFloat64x2XY, Float64ArrayGetFloat64x2XY)       \
6831   V(Float64Array.prototype, _getFloat64x2X, Float64ArrayGetFloat64x2X)         \
6832   V(Int32Array.prototype, _getInt32x4XYZW, Int32ArrayGetInt32x4XYZW)           \
6833   V(Int32Array.prototype, _getInt32x4XYZ, Int32ArrayGetInt32x4XYZ)             \
6834   V(Int32Array.prototype, _getInt32x4XY, Int32ArrayGetInt32x4XY)               \
6835   V(Int32Array.prototype, _getInt32x4X, Int32ArrayGetInt32x4X)                 \
6836   V(Int8Array.prototype, _getFloat32x4XYZW, Int8ArrayGetFloat32x4XYZW)         \
6837   V(Int8Array.prototype, _getFloat32x4XYZ, Int8ArrayGetFloat32x4XYZ)           \
6838   V(Int8Array.prototype, _getFloat32x4XY, Int8ArrayGetFloat32x4XY)             \
6839   V(Int8Array.prototype, _getFloat32x4X, Int8ArrayGetFloat32x4X)               \
6840   V(Int8Array.prototype, _getFloat64x2XY, Int8ArrayGetFloat64x2XY)             \
6841   V(Int8Array.prototype, _getFloat64x2X, Int8ArrayGetFloat64x2X)               \
6842   V(Int8Array.prototype, _getInt32x4XYZW, Int8ArrayGetInt32x4XYZW)             \
6843   V(Int8Array.prototype, _getInt32x4XYZ, Int8ArrayGetInt32x4XYZ)               \
6844   V(Int8Array.prototype, _getInt32x4XY, Int8ArrayGetInt32x4XY)                 \
6845   V(Int8Array.prototype, _getInt32x4X, Int8ArrayGetInt32x4X)
6846
6847 #define TYPED_ARRAYS_SIMD_STORE_OPERATIONS(V)                                  \
6848   V(Float32Array.prototype, _setFloat32x4XYZW, Float32ArraySetFloat32x4XYZW)   \
6849   V(Float32Array.prototype, _setFloat32x4XYZ, Float32ArraySetFloat32x4XYZ)     \
6850   V(Float32Array.prototype, _setFloat32x4XY, Float32ArraySetFloat32x4XY)       \
6851   V(Float32Array.prototype, _setFloat32x4X, Float32ArraySetFloat32x4X)         \
6852   V(Float64Array.prototype, _setFloat64x2XY, Float64ArraySetFloat64x2XY)       \
6853   V(Float64Array.prototype, _setFloat64x2X, Float64ArraySetFloat64x2X)         \
6854   V(Int32Array.prototype, _setInt32x4XYZW, Int32ArraySetInt32x4XYZW)           \
6855   V(Int32Array.prototype, _setInt32x4XYZ, Int32ArraySetInt32x4XYZ)             \
6856   V(Int32Array.prototype, _setInt32x4XY, Int32ArraySetInt32x4XY)               \
6857   V(Int32Array.prototype, _setInt32x4X, Int32ArraySetInt32x4X)                 \
6858   V(Int8Array.prototype, _setFloat32x4XYZW, Int8ArraySetFloat32x4XYZW)         \
6859   V(Int8Array.prototype, _setFloat32x4XYZ, Int8ArraySetFloat32x4XYZ)           \
6860   V(Int8Array.prototype, _setFloat32x4XY, Int8ArraySetFloat32x4XY)             \
6861   V(Int8Array.prototype, _setFloat32x4X, Int8ArraySetFloat32x4X)               \
6862   V(Int8Array.prototype, _setFloat64x2XY, Int8ArraySetFloat64x2XY)             \
6863   V(Int8Array.prototype, _setFloat64x2X, Int8ArraySetFloat64x2X)               \
6864   V(Int8Array.prototype, _setInt32x4XYZW, Int8ArraySetInt32x4XYZW)             \
6865   V(Int8Array.prototype, _setInt32x4XYZ, Int8ArraySetInt32x4XYZ)               \
6866   V(Int8Array.prototype, _setInt32x4XY, Int8ArraySetInt32x4XY)                 \
6867   V(Int8Array.prototype, _setInt32x4X, Int8ArraySetInt32x4X)
6868
6869 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6870 #define SIMD_FAKE_ID_LISTS(V)                                                  \
6871   V(SIMD, unreachable, SIMD128Unreachable)                                     \
6872   V(SIMD, change, SIMD128Change)
6873
6874 enum BuiltinFunctionId {
6875   kArrayCode,
6876 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name)    \
6877   k##name,
6878   FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6879   // Fake id for a special case of Math.pow. Note, it continues the
6880   // list of math functions.
6881   kMathPowHalf,
6882   SIMD_FAKE_ID_LISTS(DECLARE_FUNCTION_ID)
6883   SIMD_ARRAY_OPERATIONS(DECLARE_FUNCTION_ID)
6884   TYPED_ARRAYS_SIMD_LOAD_OPERATIONS(DECLARE_FUNCTION_ID)
6885   TYPED_ARRAYS_SIMD_STORE_OPERATIONS(DECLARE_FUNCTION_ID)
6886 #undef DECLARE_FUNCTION_ID
6887 #define DECLARE_SIMD_NULLARY_FUNCTION_ID(i1, i2, name, i3)                     \
6888   k##name,
6889   SIMD_NULLARY_OPERATIONS(DECLARE_SIMD_NULLARY_FUNCTION_ID)
6890 #undef DECLARE_SIMD_NULLARY_FUNCTION_ID
6891 #define DECLARE_SIMD_UNARY_FUNCTION_ID(i1, i2, name, i3, i4)                   \
6892   k##name,
6893   SIMD_UNARY_OPERATIONS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6894   SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6895 #undef DECLARE_SIMD_UNARY_FUNCTION_ID
6896 #define DECLARE_SIMD_BINARY_FUNCTION_ID(i1, i2, name, i3, i4, i5)              \
6897   k##name,
6898   SIMD_BINARY_OPERATIONS(DECLARE_SIMD_BINARY_FUNCTION_ID)
6899 #undef DECLARE_SIMD_BINARY_FUNCTION_ID
6900 #define DECLARE_SIMD_TERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6)         \
6901   k##name,
6902   SIMD_TERNARY_OPERATIONS(DECLARE_SIMD_TERNARY_FUNCTION_ID)
6903 #undef DECLARE_SIMD_TERNARY_FUNCTION_ID
6904 #define DECLARE_SIMD_QUARTERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6, i7) \
6905   k##name,
6906   SIMD_QUARTERNARY_OPERATIONS(DECLARE_SIMD_QUARTERNARY_FUNCTION_ID)
6907 #undef DECLARE_SIMD_QUARTERNARY_FUNCTION_ID
6908   kNumberOfBuiltinFunction
6909 };
6910
6911
6912 // SharedFunctionInfo describes the JSFunction information that can be
6913 // shared by multiple instances of the function.
6914 class SharedFunctionInfo: public HeapObject {
6915  public:
6916   // [name]: Function name.
6917   DECL_ACCESSORS(name, Object)
6918
6919   // [code]: Function code.
6920   DECL_ACCESSORS(code, Code)
6921   inline void ReplaceCode(Code* code);
6922
6923   // [optimized_code_map]: Map from native context to optimized code
6924   // and a shared literals array or Smi(0) if none.
6925   DECL_ACCESSORS(optimized_code_map, Object)
6926
6927   // Returns index i of the entry with the specified context and OSR entry.
6928   // At position i - 1 is the context, position i the code, and i + 1 the
6929   // literals array.  Returns -1 when no matching entry is found.
6930   int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6931
6932   // Installs optimized code from the code map on the given closure. The
6933   // index has to be consistent with a search result as defined above.
6934   FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6935
6936   Code* GetCodeFromOptimizedCodeMap(int index);
6937
6938   // Clear optimized code map.
6939   void ClearOptimizedCodeMap();
6940
6941   // Removed a specific optimized code object from the optimized code map.
6942   void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6943
6944   void ClearTypeFeedbackInfo();
6945
6946   // Trims the optimized code map after entries have been removed.
6947   void TrimOptimizedCodeMap(int shrink_by);
6948
6949   // Add a new entry to the optimized code map.
6950   static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6951                                     Handle<Context> native_context,
6952                                     Handle<Code> code,
6953                                     Handle<FixedArray> literals,
6954                                     BailoutId osr_ast_id);
6955
6956   // Layout description of the optimized code map.
6957   static const int kNextMapIndex = 0;
6958   static const int kEntriesStart = 1;
6959   static const int kContextOffset = 0;
6960   static const int kCachedCodeOffset = 1;
6961   static const int kLiteralsOffset = 2;
6962   static const int kOsrAstIdOffset = 3;
6963   static const int kEntryLength = 4;
6964   static const int kInitialLength = kEntriesStart + kEntryLength;
6965
6966   // [scope_info]: Scope info.
6967   DECL_ACCESSORS(scope_info, ScopeInfo)
6968
6969   // [construct stub]: Code stub for constructing instances of this function.
6970   DECL_ACCESSORS(construct_stub, Code)
6971
6972   // Returns if this function has been compiled to native code yet.
6973   inline bool is_compiled();
6974
6975   // [length]: The function length - usually the number of declared parameters.
6976   // Use up to 2^30 parameters.
6977   inline int length() const;
6978   inline void set_length(int value);
6979
6980   // [formal parameter count]: The declared number of parameters.
6981   inline int formal_parameter_count() const;
6982   inline void set_formal_parameter_count(int value);
6983
6984   // Set the formal parameter count so the function code will be
6985   // called without using argument adaptor frames.
6986   inline void DontAdaptArguments();
6987
6988   // [expected_nof_properties]: Expected number of properties for the function.
6989   inline int expected_nof_properties() const;
6990   inline void set_expected_nof_properties(int value);
6991
6992   // [feedback_vector] - accumulates ast node feedback from full-codegen and
6993   // (increasingly) from crankshafted code where sufficient feedback isn't
6994   // available.
6995   DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6996
6997   // [instance class name]: class name for instances.
6998   DECL_ACCESSORS(instance_class_name, Object)
6999
7000   // [function data]: This field holds some additional data for function.
7001   // Currently it either has FunctionTemplateInfo to make benefit the API
7002   // or Smi identifying a builtin function.
7003   // In the long run we don't want all functions to have this field but
7004   // we can fix that when we have a better model for storing hidden data
7005   // on objects.
7006   DECL_ACCESSORS(function_data, Object)
7007
7008   inline bool IsApiFunction();
7009   inline FunctionTemplateInfo* get_api_func_data();
7010   inline bool HasBuiltinFunctionId();
7011   inline BuiltinFunctionId builtin_function_id();
7012
7013   // [script info]: Script from which the function originates.
7014   DECL_ACCESSORS(script, Object)
7015
7016   // [num_literals]: Number of literals used by this function.
7017   inline int num_literals() const;
7018   inline void set_num_literals(int value);
7019
7020   // [start_position_and_type]: Field used to store both the source code
7021   // position, whether or not the function is a function expression,
7022   // and whether or not the function is a toplevel function. The two
7023   // least significants bit indicates whether the function is an
7024   // expression and the rest contains the source code position.
7025   inline int start_position_and_type() const;
7026   inline void set_start_position_and_type(int value);
7027
7028   // [debug info]: Debug information.
7029   DECL_ACCESSORS(debug_info, Object)
7030
7031   // [inferred name]: Name inferred from variable or property
7032   // assignment of this function. Used to facilitate debugging and
7033   // profiling of JavaScript code written in OO style, where almost
7034   // all functions are anonymous but are assigned to object
7035   // properties.
7036   DECL_ACCESSORS(inferred_name, String)
7037
7038   // The function's name if it is non-empty, otherwise the inferred name.
7039   String* DebugName();
7040
7041   // Position of the 'function' token in the script source.
7042   inline int function_token_position() const;
7043   inline void set_function_token_position(int function_token_position);
7044
7045   // Position of this function in the script source.
7046   inline int start_position() const;
7047   inline void set_start_position(int start_position);
7048
7049   // End position of this function in the script source.
7050   inline int end_position() const;
7051   inline void set_end_position(int end_position);
7052
7053   // Is this function a function expression in the source code.
7054   DECL_BOOLEAN_ACCESSORS(is_expression)
7055
7056   // Is this function a top-level function (scripts, evals).
7057   DECL_BOOLEAN_ACCESSORS(is_toplevel)
7058
7059   // Bit field containing various information collected by the compiler to
7060   // drive optimization.
7061   inline int compiler_hints() const;
7062   inline void set_compiler_hints(int value);
7063
7064   inline int ast_node_count() const;
7065   inline void set_ast_node_count(int count);
7066
7067   inline int profiler_ticks() const;
7068   inline void set_profiler_ticks(int ticks);
7069
7070   // Inline cache age is used to infer whether the function survived a context
7071   // disposal or not. In the former case we reset the opt_count.
7072   inline int ic_age();
7073   inline void set_ic_age(int age);
7074
7075   // Indicates if this function can be lazy compiled.
7076   // This is used to determine if we can safely flush code from a function
7077   // when doing GC if we expect that the function will no longer be used.
7078   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7079
7080   // Indicates if this function can be lazy compiled without a context.
7081   // This is used to determine if we can force compilation without reaching
7082   // the function through program execution but through other means (e.g. heap
7083   // iteration by the debugger).
7084   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7085
7086   // Indicates whether optimizations have been disabled for this
7087   // shared function info. If a function is repeatedly optimized or if
7088   // we cannot optimize the function we disable optimization to avoid
7089   // spending time attempting to optimize it again.
7090   DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7091
7092   // Indicates the language mode.
7093   inline StrictMode strict_mode();
7094   inline void set_strict_mode(StrictMode strict_mode);
7095
7096   // False if the function definitely does not allocate an arguments object.
7097   DECL_BOOLEAN_ACCESSORS(uses_arguments)
7098
7099   // True if the function has any duplicated parameter names.
7100   DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7101
7102   // Indicates whether the function is a native function.
7103   // These needs special treatment in .call and .apply since
7104   // null passed as the receiver should not be translated to the
7105   // global object.
7106   DECL_BOOLEAN_ACCESSORS(native)
7107
7108   // Indicate that this builtin needs to be inlined in crankshaft.
7109   DECL_BOOLEAN_ACCESSORS(inline_builtin)
7110
7111   // Indicates that the function was created by the Function function.
7112   // Though it's anonymous, toString should treat it as if it had the name
7113   // "anonymous".  We don't set the name itself so that the system does not
7114   // see a binding for it.
7115   DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7116
7117   // Indicates whether the function is a bound function created using
7118   // the bind function.
7119   DECL_BOOLEAN_ACCESSORS(bound)
7120
7121   // Indicates that the function is anonymous (the name field can be set
7122   // through the API, which does not change this flag).
7123   DECL_BOOLEAN_ACCESSORS(is_anonymous)
7124
7125   // Is this a function or top-level/eval code.
7126   DECL_BOOLEAN_ACCESSORS(is_function)
7127
7128   // Indicates that code for this function cannot be cached.
7129   DECL_BOOLEAN_ACCESSORS(dont_cache)
7130
7131   // Indicates that code for this function cannot be flushed.
7132   DECL_BOOLEAN_ACCESSORS(dont_flush)
7133
7134   // Indicates that this function is a generator.
7135   DECL_BOOLEAN_ACCESSORS(is_generator)
7136
7137   // Indicates that this function is an arrow function.
7138   DECL_BOOLEAN_ACCESSORS(is_arrow)
7139
7140   // Indicates that this function is a concise method.
7141   DECL_BOOLEAN_ACCESSORS(is_concise_method)
7142
7143   // Indicates that this function is an asm function.
7144   DECL_BOOLEAN_ACCESSORS(asm_function)
7145
7146   inline FunctionKind kind();
7147   inline void set_kind(FunctionKind kind);
7148
7149   // Indicates whether or not the code in the shared function support
7150   // deoptimization.
7151   inline bool has_deoptimization_support();
7152
7153   // Enable deoptimization support through recompiled code.
7154   void EnableDeoptimizationSupport(Code* recompiled);
7155
7156   // Disable (further) attempted optimization of all functions sharing this
7157   // shared function info.
7158   void DisableOptimization(BailoutReason reason);
7159
7160   inline BailoutReason DisableOptimizationReason();
7161
7162   // Lookup the bailout ID and DCHECK that it exists in the non-optimized
7163   // code, returns whether it asserted (i.e., always true if assertions are
7164   // disabled).
7165   bool VerifyBailoutId(BailoutId id);
7166
7167   // [source code]: Source code for the function.
7168   bool HasSourceCode() const;
7169   Handle<Object> GetSourceCode();
7170
7171   // Number of times the function was optimized.
7172   inline int opt_count();
7173   inline void set_opt_count(int opt_count);
7174
7175   // Number of times the function was deoptimized.
7176   inline void set_deopt_count(int value);
7177   inline int deopt_count();
7178   inline void increment_deopt_count();
7179
7180   // Number of time we tried to re-enable optimization after it
7181   // was disabled due to high number of deoptimizations.
7182   inline void set_opt_reenable_tries(int value);
7183   inline int opt_reenable_tries();
7184
7185   inline void TryReenableOptimization();
7186
7187   // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7188   inline void set_counters(int value);
7189   inline int counters() const;
7190
7191   // Stores opt_count and bailout_reason as bit-fields.
7192   inline void set_opt_count_and_bailout_reason(int value);
7193   inline int opt_count_and_bailout_reason() const;
7194
7195   void set_bailout_reason(BailoutReason reason) {
7196     set_opt_count_and_bailout_reason(
7197         DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7198                                                reason));
7199   }
7200
7201   // Check whether or not this function is inlineable.
7202   bool IsInlineable();
7203
7204   // Source size of this function.
7205   int SourceSize();
7206
7207   // Calculate the instance size.
7208   int CalculateInstanceSize();
7209
7210   // Calculate the number of in-object properties.
7211   int CalculateInObjectProperties();
7212
7213   // Dispatched behavior.
7214   DECLARE_PRINTER(SharedFunctionInfo)
7215   DECLARE_VERIFIER(SharedFunctionInfo)
7216
7217   void ResetForNewContext(int new_ic_age);
7218
7219   DECLARE_CAST(SharedFunctionInfo)
7220
7221   // Constants.
7222   static const int kDontAdaptArgumentsSentinel = -1;
7223
7224   // Layout description.
7225   // Pointer fields.
7226   static const int kNameOffset = HeapObject::kHeaderSize;
7227   static const int kCodeOffset = kNameOffset + kPointerSize;
7228   static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7229   static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7230   static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7231   static const int kInstanceClassNameOffset =
7232       kConstructStubOffset + kPointerSize;
7233   static const int kFunctionDataOffset =
7234       kInstanceClassNameOffset + kPointerSize;
7235   static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7236   static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7237   static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7238   static const int kFeedbackVectorOffset =
7239       kInferredNameOffset + kPointerSize;
7240 #if V8_HOST_ARCH_32_BIT
7241   // Smi fields.
7242   static const int kLengthOffset =
7243       kFeedbackVectorOffset + kPointerSize;
7244   static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7245   static const int kExpectedNofPropertiesOffset =
7246       kFormalParameterCountOffset + kPointerSize;
7247   static const int kNumLiteralsOffset =
7248       kExpectedNofPropertiesOffset + kPointerSize;
7249   static const int kStartPositionAndTypeOffset =
7250       kNumLiteralsOffset + kPointerSize;
7251   static const int kEndPositionOffset =
7252       kStartPositionAndTypeOffset + kPointerSize;
7253   static const int kFunctionTokenPositionOffset =
7254       kEndPositionOffset + kPointerSize;
7255   static const int kCompilerHintsOffset =
7256       kFunctionTokenPositionOffset + kPointerSize;
7257   static const int kOptCountAndBailoutReasonOffset =
7258       kCompilerHintsOffset + kPointerSize;
7259   static const int kCountersOffset =
7260       kOptCountAndBailoutReasonOffset + kPointerSize;
7261   static const int kAstNodeCountOffset =
7262       kCountersOffset + kPointerSize;
7263   static const int kProfilerTicksOffset =
7264       kAstNodeCountOffset + kPointerSize;
7265
7266   // Total size.
7267   static const int kSize = kProfilerTicksOffset + kPointerSize;
7268 #else
7269   // The only reason to use smi fields instead of int fields
7270   // is to allow iteration without maps decoding during
7271   // garbage collections.
7272   // To avoid wasting space on 64-bit architectures we use
7273   // the following trick: we group integer fields into pairs
7274   // First integer in each pair is shifted left by 1.
7275   // By doing this we guarantee that LSB of each kPointerSize aligned
7276   // word is not set and thus this word cannot be treated as pointer
7277   // to HeapObject during old space traversal.
7278   static const int kLengthOffset =
7279       kFeedbackVectorOffset + kPointerSize;
7280   static const int kFormalParameterCountOffset =
7281       kLengthOffset + kIntSize;
7282
7283   static const int kExpectedNofPropertiesOffset =
7284       kFormalParameterCountOffset + kIntSize;
7285   static const int kNumLiteralsOffset =
7286       kExpectedNofPropertiesOffset + kIntSize;
7287
7288   static const int kEndPositionOffset =
7289       kNumLiteralsOffset + kIntSize;
7290   static const int kStartPositionAndTypeOffset =
7291       kEndPositionOffset + kIntSize;
7292
7293   static const int kFunctionTokenPositionOffset =
7294       kStartPositionAndTypeOffset + kIntSize;
7295   static const int kCompilerHintsOffset =
7296       kFunctionTokenPositionOffset + kIntSize;
7297
7298   static const int kOptCountAndBailoutReasonOffset =
7299       kCompilerHintsOffset + kIntSize;
7300   static const int kCountersOffset =
7301       kOptCountAndBailoutReasonOffset + kIntSize;
7302
7303   static const int kAstNodeCountOffset =
7304       kCountersOffset + kIntSize;
7305   static const int kProfilerTicksOffset =
7306       kAstNodeCountOffset + kIntSize;
7307
7308   // Total size.
7309   static const int kSize = kProfilerTicksOffset + kIntSize;
7310
7311 #endif
7312
7313   static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7314
7315   typedef FixedBodyDescriptor<kNameOffset,
7316                               kFeedbackVectorOffset + kPointerSize,
7317                               kSize> BodyDescriptor;
7318
7319   // Bit positions in start_position_and_type.
7320   // The source code start position is in the 30 most significant bits of
7321   // the start_position_and_type field.
7322   static const int kIsExpressionBit    = 0;
7323   static const int kIsTopLevelBit      = 1;
7324   static const int kStartPositionShift = 2;
7325   static const int kStartPositionMask  = ~((1 << kStartPositionShift) - 1);
7326
7327   // Bit positions in compiler_hints.
7328   enum CompilerHints {
7329     kAllowLazyCompilation,
7330     kAllowLazyCompilationWithoutContext,
7331     kOptimizationDisabled,
7332     kStrictModeFunction,
7333     kUsesArguments,
7334     kHasDuplicateParameters,
7335     kNative,
7336     kInlineBuiltin,
7337     kBoundFunction,
7338     kIsAnonymous,
7339     kNameShouldPrintAsAnonymous,
7340     kIsFunction,
7341     kDontCache,
7342     kDontFlush,
7343     kIsArrow,
7344     kIsGenerator,
7345     kIsConciseMethod,
7346     kIsAsmFunction,
7347     kCompilerHintsCount  // Pseudo entry
7348   };
7349
7350   class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 3> {};
7351
7352   class DeoptCountBits : public BitField<int, 0, 4> {};
7353   class OptReenableTriesBits : public BitField<int, 4, 18> {};
7354   class ICAgeBits : public BitField<int, 22, 8> {};
7355
7356   class OptCountBits : public BitField<int, 0, 22> {};
7357   class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7358
7359  private:
7360 #if V8_HOST_ARCH_32_BIT
7361   // On 32 bit platforms, compiler hints is a smi.
7362   static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7363   static const int kCompilerHintsSize = kPointerSize;
7364 #else
7365   // On 64 bit platforms, compiler hints is not a smi, see comment above.
7366   static const int kCompilerHintsSmiTagSize = 0;
7367   static const int kCompilerHintsSize = kIntSize;
7368 #endif
7369
7370   STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7371                 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7372
7373  public:
7374   // Constants for optimizing codegen for strict mode function and
7375   // native tests.
7376   // Allows to use byte-width instructions.
7377   static const int kStrictModeBitWithinByte =
7378       (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7379
7380   static const int kNativeBitWithinByte =
7381       (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7382
7383 #if defined(V8_TARGET_LITTLE_ENDIAN)
7384   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7385       (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7386   static const int kNativeByteOffset = kCompilerHintsOffset +
7387       (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7388 #elif defined(V8_TARGET_BIG_ENDIAN)
7389   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7390       (kCompilerHintsSize - 1) -
7391       ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7392   static const int kNativeByteOffset = kCompilerHintsOffset +
7393       (kCompilerHintsSize - 1) -
7394       ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7395 #else
7396 #error Unknown byte ordering
7397 #endif
7398
7399  private:
7400   DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7401 };
7402
7403
7404 // Printing support.
7405 struct SourceCodeOf {
7406   explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7407       : value(v), max_length(max) {}
7408   const SharedFunctionInfo* value;
7409   int max_length;
7410 };
7411
7412
7413 OStream& operator<<(OStream& os, const SourceCodeOf& v);
7414
7415
7416 class JSGeneratorObject: public JSObject {
7417  public:
7418   // [function]: The function corresponding to this generator object.
7419   DECL_ACCESSORS(function, JSFunction)
7420
7421   // [context]: The context of the suspended computation.
7422   DECL_ACCESSORS(context, Context)
7423
7424   // [receiver]: The receiver of the suspended computation.
7425   DECL_ACCESSORS(receiver, Object)
7426
7427   // [continuation]: Offset into code of continuation.
7428   //
7429   // A positive offset indicates a suspended generator.  The special
7430   // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7431   // cannot be resumed.
7432   inline int continuation() const;
7433   inline void set_continuation(int continuation);
7434   inline bool is_closed();
7435   inline bool is_executing();
7436   inline bool is_suspended();
7437
7438   // [operand_stack]: Saved operand stack.
7439   DECL_ACCESSORS(operand_stack, FixedArray)
7440
7441   // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7442   // if the captured activation had no stack handler.
7443   inline int stack_handler_index() const;
7444   inline void set_stack_handler_index(int stack_handler_index);
7445
7446   DECLARE_CAST(JSGeneratorObject)
7447
7448   // Dispatched behavior.
7449   DECLARE_PRINTER(JSGeneratorObject)
7450   DECLARE_VERIFIER(JSGeneratorObject)
7451
7452   // Magic sentinel values for the continuation.
7453   static const int kGeneratorExecuting = -1;
7454   static const int kGeneratorClosed = 0;
7455
7456   // Layout description.
7457   static const int kFunctionOffset = JSObject::kHeaderSize;
7458   static const int kContextOffset = kFunctionOffset + kPointerSize;
7459   static const int kReceiverOffset = kContextOffset + kPointerSize;
7460   static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7461   static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7462   static const int kStackHandlerIndexOffset =
7463       kOperandStackOffset + kPointerSize;
7464   static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7465
7466   // Resume mode, for use by runtime functions.
7467   enum ResumeMode { NEXT, THROW };
7468
7469   // Yielding from a generator returns an object with the following inobject
7470   // properties.  See Context::iterator_result_map() for the map.
7471   static const int kResultValuePropertyIndex = 0;
7472   static const int kResultDonePropertyIndex = 1;
7473   static const int kResultPropertyCount = 2;
7474
7475   static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7476   static const int kResultDonePropertyOffset =
7477       kResultValuePropertyOffset + kPointerSize;
7478   static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7479
7480  private:
7481   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7482 };
7483
7484
7485 // Representation for module instance objects.
7486 class JSModule: public JSObject {
7487  public:
7488   // [context]: the context holding the module's locals, or undefined if none.
7489   DECL_ACCESSORS(context, Object)
7490
7491   // [scope_info]: Scope info.
7492   DECL_ACCESSORS(scope_info, ScopeInfo)
7493
7494   DECLARE_CAST(JSModule)
7495
7496   // Dispatched behavior.
7497   DECLARE_PRINTER(JSModule)
7498   DECLARE_VERIFIER(JSModule)
7499
7500   // Layout description.
7501   static const int kContextOffset = JSObject::kHeaderSize;
7502   static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7503   static const int kSize = kScopeInfoOffset + kPointerSize;
7504
7505  private:
7506   DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7507 };
7508
7509
7510 // JSFunction describes JavaScript functions.
7511 class JSFunction: public JSObject {
7512  public:
7513   // [prototype_or_initial_map]:
7514   DECL_ACCESSORS(prototype_or_initial_map, Object)
7515
7516   // [shared]: The information about the function that
7517   // can be shared by instances.
7518   DECL_ACCESSORS(shared, SharedFunctionInfo)
7519
7520   // [context]: The context for this function.
7521   inline Context* context();
7522   inline void set_context(Object* context);
7523   inline JSObject* global_proxy();
7524
7525   // [code]: The generated code object for this function.  Executed
7526   // when the function is invoked, e.g. foo() or new foo(). See
7527   // [[Call]] and [[Construct]] description in ECMA-262, section
7528   // 8.6.2, page 27.
7529   inline Code* code();
7530   inline void set_code(Code* code);
7531   inline void set_code_no_write_barrier(Code* code);
7532   inline void ReplaceCode(Code* code);
7533
7534   // Tells whether this function is builtin.
7535   inline bool IsBuiltin();
7536
7537   // Tells whether this function is defined in a native script.
7538   inline bool IsFromNativeScript();
7539
7540   // Tells whether this function is defined in an extension script.
7541   inline bool IsFromExtensionScript();
7542
7543   // Tells whether or not the function needs arguments adaption.
7544   inline bool NeedsArgumentsAdaption();
7545
7546   // Tells whether or not this function has been optimized.
7547   inline bool IsOptimized();
7548
7549   // Tells whether or not this function can be optimized.
7550   inline bool IsOptimizable();
7551
7552   // Mark this function for lazy recompilation. The function will be
7553   // recompiled the next time it is executed.
7554   void MarkForOptimization();
7555   void MarkForConcurrentOptimization();
7556   void MarkInOptimizationQueue();
7557
7558   // Tells whether or not the function is already marked for lazy
7559   // recompilation.
7560   inline bool IsMarkedForOptimization();
7561   inline bool IsMarkedForConcurrentOptimization();
7562
7563   // Tells whether or not the function is on the concurrent recompilation queue.
7564   inline bool IsInOptimizationQueue();
7565
7566   // Inobject slack tracking is the way to reclaim unused inobject space.
7567   //
7568   // The instance size is initially determined by adding some slack to
7569   // expected_nof_properties (to allow for a few extra properties added
7570   // after the constructor). There is no guarantee that the extra space
7571   // will not be wasted.
7572   //
7573   // Here is the algorithm to reclaim the unused inobject space:
7574   // - Detect the first constructor call for this JSFunction.
7575   //   When it happens enter the "in progress" state: initialize construction
7576   //   counter in the initial_map and set the |done_inobject_slack_tracking|
7577   //   flag.
7578   // - While the tracking is in progress create objects filled with
7579   //   one_pointer_filler_map instead of undefined_value. This way they can be
7580   //   resized quickly and safely.
7581   // - Once enough (kGenerousAllocationCount) objects have been created
7582   //   compute the 'slack' (traverse the map transition tree starting from the
7583   //   initial_map and find the lowest value of unused_property_fields).
7584   // - Traverse the transition tree again and decrease the instance size
7585   //   of every map. Existing objects will resize automatically (they are
7586   //   filled with one_pointer_filler_map). All further allocations will
7587   //   use the adjusted instance size.
7588   // - SharedFunctionInfo's expected_nof_properties left unmodified since
7589   //   allocations made using different closures could actually create different
7590   //   kind of objects (see prototype inheritance pattern).
7591   //
7592   //  Important: inobject slack tracking is not attempted during the snapshot
7593   //  creation.
7594
7595   static const int kGenerousAllocationCount = Map::ConstructionCount::kMax;
7596   static const int kFinishSlackTracking     = 1;
7597   static const int kNoSlackTracking         = 0;
7598
7599   // True if the initial_map is set and the object constructions countdown
7600   // counter is not zero.
7601   inline bool IsInobjectSlackTrackingInProgress();
7602
7603   // Starts the tracking.
7604   // Initializes object constructions countdown counter in the initial map.
7605   // IsInobjectSlackTrackingInProgress is normally true after this call,
7606   // except when tracking have not been started (e.g. the map has no unused
7607   // properties or the snapshot is being built).
7608   void StartInobjectSlackTracking();
7609
7610   // Completes the tracking.
7611   // IsInobjectSlackTrackingInProgress is false after this call.
7612   void CompleteInobjectSlackTracking();
7613
7614   // [literals_or_bindings]: Fixed array holding either
7615   // the materialized literals or the bindings of a bound function.
7616   //
7617   // If the function contains object, regexp or array literals, the
7618   // literals array prefix contains the object, regexp, and array
7619   // function to be used when creating these literals.  This is
7620   // necessary so that we do not dynamically lookup the object, regexp
7621   // or array functions.  Performing a dynamic lookup, we might end up
7622   // using the functions from a new context that we should not have
7623   // access to.
7624   //
7625   // On bound functions, the array is a (copy-on-write) fixed-array containing
7626   // the function that was bound, bound this-value and any bound
7627   // arguments. Bound functions never contain literals.
7628   DECL_ACCESSORS(literals_or_bindings, FixedArray)
7629
7630   inline FixedArray* literals();
7631   inline void set_literals(FixedArray* literals);
7632
7633   inline FixedArray* function_bindings();
7634   inline void set_function_bindings(FixedArray* bindings);
7635
7636   // The initial map for an object created by this constructor.
7637   inline Map* initial_map();
7638   static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7639                             Handle<Object> prototype);
7640   inline bool has_initial_map();
7641   static void EnsureHasInitialMap(Handle<JSFunction> function);
7642
7643   // Get and set the prototype property on a JSFunction. If the
7644   // function has an initial map the prototype is set on the initial
7645   // map. Otherwise, the prototype is put in the initial map field
7646   // until an initial map is needed.
7647   inline bool has_prototype();
7648   inline bool has_instance_prototype();
7649   inline Object* prototype();
7650   inline Object* instance_prototype();
7651   static void SetPrototype(Handle<JSFunction> function,
7652                            Handle<Object> value);
7653   static void SetInstancePrototype(Handle<JSFunction> function,
7654                                    Handle<Object> value);
7655
7656   // Creates a new closure for the fucntion with the same bindings,
7657   // bound values, and prototype. An equivalent of spec operations
7658   // ``CloneMethod`` and ``CloneBoundFunction``.
7659   static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7660
7661   // After prototype is removed, it will not be created when accessed, and
7662   // [[Construct]] from this function will not be allowed.
7663   bool RemovePrototype();
7664   inline bool should_have_prototype();
7665
7666   // Accessor for this function's initial map's [[class]]
7667   // property. This is primarily used by ECMA native functions.  This
7668   // method sets the class_name field of this function's initial map
7669   // to a given value. It creates an initial map if this function does
7670   // not have one. Note that this method does not copy the initial map
7671   // if it has one already, but simply replaces it with the new value.
7672   // Instances created afterwards will have a map whose [[class]] is
7673   // set to 'value', but there is no guarantees on instances created
7674   // before.
7675   void SetInstanceClassName(String* name);
7676
7677   // Returns if this function has been compiled to native code yet.
7678   inline bool is_compiled();
7679
7680   // [next_function_link]: Links functions into various lists, e.g. the list
7681   // of optimized functions hanging off the native_context. The CodeFlusher
7682   // uses this link to chain together flushing candidates. Treated weakly
7683   // by the garbage collector.
7684   DECL_ACCESSORS(next_function_link, Object)
7685
7686   // Prints the name of the function using PrintF.
7687   void PrintName(FILE* out = stdout);
7688
7689   DECLARE_CAST(JSFunction)
7690
7691   // Iterates the objects, including code objects indirectly referenced
7692   // through pointers to the first instruction in the code object.
7693   void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7694
7695   // Dispatched behavior.
7696   DECLARE_PRINTER(JSFunction)
7697   DECLARE_VERIFIER(JSFunction)
7698
7699   // Returns the number of allocated literals.
7700   inline int NumberOfLiterals();
7701
7702   // Retrieve the native context from a function's literal array.
7703   static Context* NativeContextFromLiterals(FixedArray* literals);
7704
7705   // Used for flags such as --hydrogen-filter.
7706   bool PassesFilter(const char* raw_filter);
7707
7708   // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7709   // kSize) is weak and has special handling during garbage collection.
7710   static const int kCodeEntryOffset = JSObject::kHeaderSize;
7711   static const int kPrototypeOrInitialMapOffset =
7712       kCodeEntryOffset + kPointerSize;
7713   static const int kSharedFunctionInfoOffset =
7714       kPrototypeOrInitialMapOffset + kPointerSize;
7715   static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7716   static const int kLiteralsOffset = kContextOffset + kPointerSize;
7717   static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7718   static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7719   static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7720
7721   // Layout of the literals array.
7722   static const int kLiteralsPrefixSize = 1;
7723   static const int kLiteralNativeContextIndex = 0;
7724
7725   // Layout of the bound-function binding array.
7726   static const int kBoundFunctionIndex = 0;
7727   static const int kBoundThisIndex = 1;
7728   static const int kBoundArgumentsStartIndex = 2;
7729
7730  private:
7731   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7732 };
7733
7734
7735 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7736 // and the prototype is hidden. JSGlobalProxy always delegates
7737 // property accesses to its prototype if the prototype is not null.
7738 //
7739 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7740 //
7741 // Accessing a JSGlobalProxy requires security check.
7742
7743 class JSGlobalProxy : public JSObject {
7744  public:
7745   // [native_context]: the owner native context of this global proxy object.
7746   // It is null value if this object is not used by any context.
7747   DECL_ACCESSORS(native_context, Object)
7748
7749   // [hash]: The hash code property (undefined if not initialized yet).
7750   DECL_ACCESSORS(hash, Object)
7751
7752   DECLARE_CAST(JSGlobalProxy)
7753
7754   inline bool IsDetachedFrom(GlobalObject* global) const;
7755
7756   // Dispatched behavior.
7757   DECLARE_PRINTER(JSGlobalProxy)
7758   DECLARE_VERIFIER(JSGlobalProxy)
7759
7760   // Layout description.
7761   static const int kNativeContextOffset = JSObject::kHeaderSize;
7762   static const int kHashOffset = kNativeContextOffset + kPointerSize;
7763   static const int kSize = kHashOffset + kPointerSize;
7764
7765  private:
7766   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7767 };
7768
7769
7770 // Forward declaration.
7771 class JSBuiltinsObject;
7772
7773 // Common super class for JavaScript global objects and the special
7774 // builtins global objects.
7775 class GlobalObject: public JSObject {
7776  public:
7777   // [builtins]: the object holding the runtime routines written in JS.
7778   DECL_ACCESSORS(builtins, JSBuiltinsObject)
7779
7780   // [native context]: the natives corresponding to this global object.
7781   DECL_ACCESSORS(native_context, Context)
7782
7783   // [global context]: the most recent (i.e. innermost) global context.
7784   DECL_ACCESSORS(global_context, Context)
7785
7786   // [global proxy]: the global proxy object of the context
7787   DECL_ACCESSORS(global_proxy, JSObject)
7788
7789   DECLARE_CAST(GlobalObject)
7790
7791   // Layout description.
7792   static const int kBuiltinsOffset = JSObject::kHeaderSize;
7793   static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7794   static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7795   static const int kGlobalProxyOffset = kGlobalContextOffset + kPointerSize;
7796   static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7797
7798  private:
7799   DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7800 };
7801
7802
7803 // JavaScript global object.
7804 class JSGlobalObject: public GlobalObject {
7805  public:
7806   DECLARE_CAST(JSGlobalObject)
7807
7808   // Ensure that the global object has a cell for the given property name.
7809   static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7810                                                  Handle<Name> name);
7811
7812   inline bool IsDetached();
7813
7814   // Dispatched behavior.
7815   DECLARE_PRINTER(JSGlobalObject)
7816   DECLARE_VERIFIER(JSGlobalObject)
7817
7818   // Layout description.
7819   static const int kSize = GlobalObject::kHeaderSize;
7820
7821  private:
7822   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7823 };
7824
7825
7826 // Builtins global object which holds the runtime routines written in
7827 // JavaScript.
7828 class JSBuiltinsObject: public GlobalObject {
7829  public:
7830   // Accessors for the runtime routines written in JavaScript.
7831   inline Object* javascript_builtin(Builtins::JavaScript id);
7832   inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7833
7834   // Accessors for code of the runtime routines written in JavaScript.
7835   inline Code* javascript_builtin_code(Builtins::JavaScript id);
7836   inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7837
7838   DECLARE_CAST(JSBuiltinsObject)
7839
7840   // Dispatched behavior.
7841   DECLARE_PRINTER(JSBuiltinsObject)
7842   DECLARE_VERIFIER(JSBuiltinsObject)
7843
7844   // Layout description.  The size of the builtins object includes
7845   // room for two pointers per runtime routine written in javascript
7846   // (function and code object).
7847   static const int kJSBuiltinsCount = Builtins::id_count;
7848   static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7849   static const int kJSBuiltinsCodeOffset =
7850       GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7851   static const int kSize =
7852       kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7853
7854   static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7855     return kJSBuiltinsOffset + id * kPointerSize;
7856   }
7857
7858   static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7859     return kJSBuiltinsCodeOffset + id * kPointerSize;
7860   }
7861
7862  private:
7863   DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7864 };
7865
7866
7867 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7868 class JSValue: public JSObject {
7869  public:
7870   // [value]: the object being wrapped.
7871   DECL_ACCESSORS(value, Object)
7872
7873   DECLARE_CAST(JSValue)
7874
7875   // Dispatched behavior.
7876   DECLARE_PRINTER(JSValue)
7877   DECLARE_VERIFIER(JSValue)
7878
7879   // Layout description.
7880   static const int kValueOffset = JSObject::kHeaderSize;
7881   static const int kSize = kValueOffset + kPointerSize;
7882
7883  private:
7884   DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7885 };
7886
7887
7888 class DateCache;
7889
7890 // Representation for JS date objects.
7891 class JSDate: public JSObject {
7892  public:
7893   // If one component is NaN, all of them are, indicating a NaN time value.
7894   // [value]: the time value.
7895   DECL_ACCESSORS(value, Object)
7896   // [year]: caches year. Either undefined, smi, or NaN.
7897   DECL_ACCESSORS(year, Object)
7898   // [month]: caches month. Either undefined, smi, or NaN.
7899   DECL_ACCESSORS(month, Object)
7900   // [day]: caches day. Either undefined, smi, or NaN.
7901   DECL_ACCESSORS(day, Object)
7902   // [weekday]: caches day of week. Either undefined, smi, or NaN.
7903   DECL_ACCESSORS(weekday, Object)
7904   // [hour]: caches hours. Either undefined, smi, or NaN.
7905   DECL_ACCESSORS(hour, Object)
7906   // [min]: caches minutes. Either undefined, smi, or NaN.
7907   DECL_ACCESSORS(min, Object)
7908   // [sec]: caches seconds. Either undefined, smi, or NaN.
7909   DECL_ACCESSORS(sec, Object)
7910   // [cache stamp]: sample of the date cache stamp at the
7911   // moment when chached fields were cached.
7912   DECL_ACCESSORS(cache_stamp, Object)
7913
7914   DECLARE_CAST(JSDate)
7915
7916   // Returns the date field with the specified index.
7917   // See FieldIndex for the list of date fields.
7918   static Object* GetField(Object* date, Smi* index);
7919
7920   void SetValue(Object* value, bool is_value_nan);
7921
7922
7923   // Dispatched behavior.
7924   DECLARE_PRINTER(JSDate)
7925   DECLARE_VERIFIER(JSDate)
7926
7927   // The order is important. It must be kept in sync with date macros
7928   // in macros.py.
7929   enum FieldIndex {
7930     kDateValue,
7931     kYear,
7932     kMonth,
7933     kDay,
7934     kWeekday,
7935     kHour,
7936     kMinute,
7937     kSecond,
7938     kFirstUncachedField,
7939     kMillisecond = kFirstUncachedField,
7940     kDays,
7941     kTimeInDay,
7942     kFirstUTCField,
7943     kYearUTC = kFirstUTCField,
7944     kMonthUTC,
7945     kDayUTC,
7946     kWeekdayUTC,
7947     kHourUTC,
7948     kMinuteUTC,
7949     kSecondUTC,
7950     kMillisecondUTC,
7951     kDaysUTC,
7952     kTimeInDayUTC,
7953     kTimezoneOffset
7954   };
7955
7956   // Layout description.
7957   static const int kValueOffset = JSObject::kHeaderSize;
7958   static const int kYearOffset = kValueOffset + kPointerSize;
7959   static const int kMonthOffset = kYearOffset + kPointerSize;
7960   static const int kDayOffset = kMonthOffset + kPointerSize;
7961   static const int kWeekdayOffset = kDayOffset + kPointerSize;
7962   static const int kHourOffset = kWeekdayOffset  + kPointerSize;
7963   static const int kMinOffset = kHourOffset + kPointerSize;
7964   static const int kSecOffset = kMinOffset + kPointerSize;
7965   static const int kCacheStampOffset = kSecOffset + kPointerSize;
7966   static const int kSize = kCacheStampOffset + kPointerSize;
7967
7968  private:
7969   inline Object* DoGetField(FieldIndex index);
7970
7971   Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7972
7973   // Computes and caches the cacheable fields of the date.
7974   inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7975
7976
7977   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7978 };
7979
7980
7981 // Representation of message objects used for error reporting through
7982 // the API. The messages are formatted in JavaScript so this object is
7983 // a real JavaScript object. The information used for formatting the
7984 // error messages are not directly accessible from JavaScript to
7985 // prevent leaking information to user code called during error
7986 // formatting.
7987 class JSMessageObject: public JSObject {
7988  public:
7989   // [type]: the type of error message.
7990   DECL_ACCESSORS(type, String)
7991
7992   // [arguments]: the arguments for formatting the error message.
7993   DECL_ACCESSORS(arguments, JSArray)
7994
7995   // [script]: the script from which the error message originated.
7996   DECL_ACCESSORS(script, Object)
7997
7998   // [stack_frames]: an array of stack frames for this error object.
7999   DECL_ACCESSORS(stack_frames, Object)
8000
8001   // [start_position]: the start position in the script for the error message.
8002   inline int start_position() const;
8003   inline void set_start_position(int value);
8004
8005   // [end_position]: the end position in the script for the error message.
8006   inline int end_position() const;
8007   inline void set_end_position(int value);
8008
8009   DECLARE_CAST(JSMessageObject)
8010
8011   // Dispatched behavior.
8012   DECLARE_PRINTER(JSMessageObject)
8013   DECLARE_VERIFIER(JSMessageObject)
8014
8015   // Layout description.
8016   static const int kTypeOffset = JSObject::kHeaderSize;
8017   static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8018   static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8019   static const int kStackFramesOffset = kScriptOffset + kPointerSize;
8020   static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8021   static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8022   static const int kSize = kEndPositionOffset + kPointerSize;
8023
8024   typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8025                               kStackFramesOffset + kPointerSize,
8026                               kSize> BodyDescriptor;
8027 };
8028
8029
8030 // Regular expressions
8031 // The regular expression holds a single reference to a FixedArray in
8032 // the kDataOffset field.
8033 // The FixedArray contains the following data:
8034 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8035 // - reference to the original source string
8036 // - reference to the original flag string
8037 // If it is an atom regexp
8038 // - a reference to a literal string to search for
8039 // If it is an irregexp regexp:
8040 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
8041 // used for tracking the last usage (used for code flushing).
8042 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8043 // used for tracking the last usage (used for code flushing)..
8044 // - max number of registers used by irregexp implementations.
8045 // - number of capture registers (output values) of the regexp.
8046 class JSRegExp: public JSObject {
8047  public:
8048   // Meaning of Type:
8049   // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8050   // ATOM: A simple string to match against using an indexOf operation.
8051   // IRREGEXP: Compiled with Irregexp.
8052   // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8053   enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8054   enum Flag {
8055     NONE = 0,
8056     GLOBAL = 1,
8057     IGNORE_CASE = 2,
8058     MULTILINE = 4,
8059     STICKY = 8
8060   };
8061
8062   class Flags {
8063    public:
8064     explicit Flags(uint32_t value) : value_(value) { }
8065     bool is_global() { return (value_ & GLOBAL) != 0; }
8066     bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8067     bool is_multiline() { return (value_ & MULTILINE) != 0; }
8068     bool is_sticky() { return (value_ & STICKY) != 0; }
8069     uint32_t value() { return value_; }
8070    private:
8071     uint32_t value_;
8072   };
8073
8074   DECL_ACCESSORS(data, Object)
8075
8076   inline Type TypeTag();
8077   inline int CaptureCount();
8078   inline Flags GetFlags();
8079   inline String* Pattern();
8080   inline Object* DataAt(int index);
8081   // Set implementation data after the object has been prepared.
8082   inline void SetDataAt(int index, Object* value);
8083
8084   static int code_index(bool is_latin1) {
8085     if (is_latin1) {
8086       return kIrregexpLatin1CodeIndex;
8087     } else {
8088       return kIrregexpUC16CodeIndex;
8089     }
8090   }
8091
8092   static int saved_code_index(bool is_latin1) {
8093     if (is_latin1) {
8094       return kIrregexpLatin1CodeSavedIndex;
8095     } else {
8096       return kIrregexpUC16CodeSavedIndex;
8097     }
8098   }
8099
8100   DECLARE_CAST(JSRegExp)
8101
8102   // Dispatched behavior.
8103   DECLARE_VERIFIER(JSRegExp)
8104
8105   static const int kDataOffset = JSObject::kHeaderSize;
8106   static const int kSize = kDataOffset + kPointerSize;
8107
8108   // Indices in the data array.
8109   static const int kTagIndex = 0;
8110   static const int kSourceIndex = kTagIndex + 1;
8111   static const int kFlagsIndex = kSourceIndex + 1;
8112   static const int kDataIndex = kFlagsIndex + 1;
8113   // The data fields are used in different ways depending on the
8114   // value of the tag.
8115   // Atom regexps (literal strings).
8116   static const int kAtomPatternIndex = kDataIndex;
8117
8118   static const int kAtomDataSize = kAtomPatternIndex + 1;
8119
8120   // Irregexp compiled code or bytecode for Latin1. If compilation
8121   // fails, this fields hold an exception object that should be
8122   // thrown if the regexp is used again.
8123   static const int kIrregexpLatin1CodeIndex = kDataIndex;
8124   // Irregexp compiled code or bytecode for UC16.  If compilation
8125   // fails, this fields hold an exception object that should be
8126   // thrown if the regexp is used again.
8127   static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8128
8129   // Saved instance of Irregexp compiled code or bytecode for Latin1 that
8130   // is a potential candidate for flushing.
8131   static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
8132   // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8133   // a potential candidate for flushing.
8134   static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8135
8136   // Maximal number of registers used by either Latin1 or UC16.
8137   // Only used to check that there is enough stack space
8138   static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8139   // Number of captures in the compiled regexp.
8140   static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8141
8142   static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8143
8144   // Offsets directly into the data fixed array.
8145   static const int kDataTagOffset =
8146       FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8147   static const int kDataOneByteCodeOffset =
8148       FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
8149   static const int kDataUC16CodeOffset =
8150       FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8151   static const int kIrregexpCaptureCountOffset =
8152       FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8153
8154   // In-object fields.
8155   static const int kSourceFieldIndex = 0;
8156   static const int kGlobalFieldIndex = 1;
8157   static const int kIgnoreCaseFieldIndex = 2;
8158   static const int kMultilineFieldIndex = 3;
8159   static const int kLastIndexFieldIndex = 4;
8160   static const int kInObjectFieldCount = 5;
8161
8162   // The uninitialized value for a regexp code object.
8163   static const int kUninitializedValue = -1;
8164
8165   // The compilation error value for the regexp code object. The real error
8166   // object is in the saved code field.
8167   static const int kCompilationErrorValue = -2;
8168
8169   // When we store the sweep generation at which we moved the code from the
8170   // code index to the saved code index we mask it of to be in the [0:255]
8171   // range.
8172   static const int kCodeAgeMask = 0xff;
8173 };
8174
8175
8176 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8177  public:
8178   static inline bool IsMatch(HashTableKey* key, Object* value) {
8179     return key->IsMatch(value);
8180   }
8181
8182   static inline uint32_t Hash(HashTableKey* key) {
8183     return key->Hash();
8184   }
8185
8186   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8187     return key->HashForObject(object);
8188   }
8189
8190   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8191
8192   static const int kPrefixSize = 0;
8193   static const int kEntrySize = 2;
8194 };
8195
8196
8197 class CompilationCacheTable: public HashTable<CompilationCacheTable,
8198                                               CompilationCacheShape,
8199                                               HashTableKey*> {
8200  public:
8201   // Find cached value for a string key, otherwise return null.
8202   Handle<Object> Lookup(Handle<String> src, Handle<Context> context);
8203   Handle<Object> LookupEval(Handle<String> src,
8204                             Handle<SharedFunctionInfo> shared,
8205                             StrictMode strict_mode, int scope_position);
8206   Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
8207   static Handle<CompilationCacheTable> Put(
8208       Handle<CompilationCacheTable> cache, Handle<String> src,
8209       Handle<Context> context, Handle<Object> value);
8210   static Handle<CompilationCacheTable> PutEval(
8211       Handle<CompilationCacheTable> cache, Handle<String> src,
8212       Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
8213       int scope_position);
8214   static Handle<CompilationCacheTable> PutRegExp(
8215       Handle<CompilationCacheTable> cache, Handle<String> src,
8216       JSRegExp::Flags flags, Handle<FixedArray> value);
8217   void Remove(Object* value);
8218
8219   DECLARE_CAST(CompilationCacheTable)
8220
8221  private:
8222   DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8223 };
8224
8225
8226 class CodeCache: public Struct {
8227  public:
8228   DECL_ACCESSORS(default_cache, FixedArray)
8229   DECL_ACCESSORS(normal_type_cache, Object)
8230
8231   // Add the code object to the cache.
8232   static void Update(
8233       Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8234
8235   // Lookup code object in the cache. Returns code object if found and undefined
8236   // if not.
8237   Object* Lookup(Name* name, Code::Flags flags);
8238
8239   // Get the internal index of a code object in the cache. Returns -1 if the
8240   // code object is not in that cache. This index can be used to later call
8241   // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8242   // RemoveByIndex.
8243   int GetIndex(Object* name, Code* code);
8244
8245   // Remove an object from the cache with the provided internal index.
8246   void RemoveByIndex(Object* name, Code* code, int index);
8247
8248   DECLARE_CAST(CodeCache)
8249
8250   // Dispatched behavior.
8251   DECLARE_PRINTER(CodeCache)
8252   DECLARE_VERIFIER(CodeCache)
8253
8254   static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8255   static const int kNormalTypeCacheOffset =
8256       kDefaultCacheOffset + kPointerSize;
8257   static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8258
8259  private:
8260   static void UpdateDefaultCache(
8261       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8262   static void UpdateNormalTypeCache(
8263       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8264   Object* LookupDefaultCache(Name* name, Code::Flags flags);
8265   Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8266
8267   // Code cache layout of the default cache. Elements are alternating name and
8268   // code objects for non normal load/store/call IC's.
8269   static const int kCodeCacheEntrySize = 2;
8270   static const int kCodeCacheEntryNameOffset = 0;
8271   static const int kCodeCacheEntryCodeOffset = 1;
8272
8273   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8274 };
8275
8276
8277 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8278  public:
8279   static inline bool IsMatch(HashTableKey* key, Object* value) {
8280     return key->IsMatch(value);
8281   }
8282
8283   static inline uint32_t Hash(HashTableKey* key) {
8284     return key->Hash();
8285   }
8286
8287   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8288     return key->HashForObject(object);
8289   }
8290
8291   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8292
8293   static const int kPrefixSize = 0;
8294   static const int kEntrySize = 2;
8295 };
8296
8297
8298 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8299                                            CodeCacheHashTableShape,
8300                                            HashTableKey*> {
8301  public:
8302   Object* Lookup(Name* name, Code::Flags flags);
8303   static Handle<CodeCacheHashTable> Put(
8304       Handle<CodeCacheHashTable> table,
8305       Handle<Name> name,
8306       Handle<Code> code);
8307
8308   int GetIndex(Name* name, Code::Flags flags);
8309   void RemoveByIndex(int index);
8310
8311   DECLARE_CAST(CodeCacheHashTable)
8312
8313   // Initial size of the fixed array backing the hash table.
8314   static const int kInitialSize = 64;
8315
8316  private:
8317   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8318 };
8319
8320
8321 class PolymorphicCodeCache: public Struct {
8322  public:
8323   DECL_ACCESSORS(cache, Object)
8324
8325   static void Update(Handle<PolymorphicCodeCache> cache,
8326                      MapHandleList* maps,
8327                      Code::Flags flags,
8328                      Handle<Code> code);
8329
8330
8331   // Returns an undefined value if the entry is not found.
8332   Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8333
8334   DECLARE_CAST(PolymorphicCodeCache)
8335
8336   // Dispatched behavior.
8337   DECLARE_PRINTER(PolymorphicCodeCache)
8338   DECLARE_VERIFIER(PolymorphicCodeCache)
8339
8340   static const int kCacheOffset = HeapObject::kHeaderSize;
8341   static const int kSize = kCacheOffset + kPointerSize;
8342
8343  private:
8344   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8345 };
8346
8347
8348 class PolymorphicCodeCacheHashTable
8349     : public HashTable<PolymorphicCodeCacheHashTable,
8350                        CodeCacheHashTableShape,
8351                        HashTableKey*> {
8352  public:
8353   Object* Lookup(MapHandleList* maps, int code_kind);
8354
8355   static Handle<PolymorphicCodeCacheHashTable> Put(
8356       Handle<PolymorphicCodeCacheHashTable> hash_table,
8357       MapHandleList* maps,
8358       int code_kind,
8359       Handle<Code> code);
8360
8361   DECLARE_CAST(PolymorphicCodeCacheHashTable)
8362
8363   static const int kInitialSize = 64;
8364  private:
8365   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8366 };
8367
8368
8369 class TypeFeedbackInfo: public Struct {
8370  public:
8371   inline int ic_total_count();
8372   inline void set_ic_total_count(int count);
8373
8374   inline int ic_with_type_info_count();
8375   inline void change_ic_with_type_info_count(int delta);
8376
8377   inline int ic_generic_count();
8378   inline void change_ic_generic_count(int delta);
8379
8380   inline void initialize_storage();
8381
8382   inline void change_own_type_change_checksum();
8383   inline int own_type_change_checksum();
8384
8385   inline void set_inlined_type_change_checksum(int checksum);
8386   inline bool matches_inlined_type_change_checksum(int checksum);
8387
8388
8389   DECLARE_CAST(TypeFeedbackInfo)
8390
8391   // Dispatched behavior.
8392   DECLARE_PRINTER(TypeFeedbackInfo)
8393   DECLARE_VERIFIER(TypeFeedbackInfo)
8394
8395   static const int kStorage1Offset = HeapObject::kHeaderSize;
8396   static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8397   static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8398   static const int kSize = kStorage3Offset + kPointerSize;
8399
8400  private:
8401   static const int kTypeChangeChecksumBits = 7;
8402
8403   class ICTotalCountField: public BitField<int, 0,
8404       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8405   class OwnTypeChangeChecksum: public BitField<int,
8406       kSmiValueSize - kTypeChangeChecksumBits,
8407       kTypeChangeChecksumBits> {};  // NOLINT
8408   class ICsWithTypeInfoCountField: public BitField<int, 0,
8409       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8410   class InlinedTypeChangeChecksum: public BitField<int,
8411       kSmiValueSize - kTypeChangeChecksumBits,
8412       kTypeChangeChecksumBits> {};  // NOLINT
8413
8414   DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8415 };
8416
8417
8418 enum AllocationSiteMode {
8419   DONT_TRACK_ALLOCATION_SITE,
8420   TRACK_ALLOCATION_SITE,
8421   LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8422 };
8423
8424
8425 class AllocationSite: public Struct {
8426  public:
8427   static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8428   static const double kPretenureRatio;
8429   static const int kPretenureMinimumCreated = 100;
8430
8431   // Values for pretenure decision field.
8432   enum PretenureDecision {
8433     kUndecided = 0,
8434     kDontTenure = 1,
8435     kMaybeTenure = 2,
8436     kTenure = 3,
8437     kZombie = 4,
8438     kLastPretenureDecisionValue = kZombie
8439   };
8440
8441   const char* PretenureDecisionName(PretenureDecision decision);
8442
8443   DECL_ACCESSORS(transition_info, Object)
8444   // nested_site threads a list of sites that represent nested literals
8445   // walked in a particular order. So [[1, 2], 1, 2] will have one
8446   // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8447   DECL_ACCESSORS(nested_site, Object)
8448   DECL_ACCESSORS(pretenure_data, Smi)
8449   DECL_ACCESSORS(pretenure_create_count, Smi)
8450   DECL_ACCESSORS(dependent_code, DependentCode)
8451   DECL_ACCESSORS(weak_next, Object)
8452
8453   inline void Initialize();
8454
8455   // This method is expensive, it should only be called for reporting.
8456   bool IsNestedSite();
8457
8458   // transition_info bitfields, for constructed array transition info.
8459   class ElementsKindBits:       public BitField<ElementsKind, 0,  15> {};
8460   class UnusedBits:             public BitField<int,          15, 14> {};
8461   class DoNotInlineBit:         public BitField<bool,         29,  1> {};
8462
8463   // Bitfields for pretenure_data
8464   class MementoFoundCountBits:  public BitField<int,               0, 26> {};
8465   class PretenureDecisionBits:  public BitField<PretenureDecision, 26, 3> {};
8466   class DeoptDependentCodeBit:  public BitField<bool,              29, 1> {};
8467   STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8468
8469   // Increments the mementos found counter and returns true when the first
8470   // memento was found for a given allocation site.
8471   inline bool IncrementMementoFoundCount();
8472
8473   inline void IncrementMementoCreateCount();
8474
8475   PretenureFlag GetPretenureMode();
8476
8477   void ResetPretenureDecision();
8478
8479   PretenureDecision pretenure_decision() {
8480     int value = pretenure_data()->value();
8481     return PretenureDecisionBits::decode(value);
8482   }
8483
8484   void set_pretenure_decision(PretenureDecision decision) {
8485     int value = pretenure_data()->value();
8486     set_pretenure_data(
8487         Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8488         SKIP_WRITE_BARRIER);
8489   }
8490
8491   bool deopt_dependent_code() {
8492     int value = pretenure_data()->value();
8493     return DeoptDependentCodeBit::decode(value);
8494   }
8495
8496   void set_deopt_dependent_code(bool deopt) {
8497     int value = pretenure_data()->value();
8498     set_pretenure_data(
8499         Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8500         SKIP_WRITE_BARRIER);
8501   }
8502
8503   int memento_found_count() {
8504     int value = pretenure_data()->value();
8505     return MementoFoundCountBits::decode(value);
8506   }
8507
8508   inline void set_memento_found_count(int count);
8509
8510   int memento_create_count() {
8511     return pretenure_create_count()->value();
8512   }
8513
8514   void set_memento_create_count(int count) {
8515     set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8516   }
8517
8518   // The pretenuring decision is made during gc, and the zombie state allows
8519   // us to recognize when an allocation site is just being kept alive because
8520   // a later traversal of new space may discover AllocationMementos that point
8521   // to this AllocationSite.
8522   bool IsZombie() {
8523     return pretenure_decision() == kZombie;
8524   }
8525
8526   bool IsMaybeTenure() {
8527     return pretenure_decision() == kMaybeTenure;
8528   }
8529
8530   inline void MarkZombie();
8531
8532   inline bool MakePretenureDecision(PretenureDecision current_decision,
8533                                     double ratio,
8534                                     bool maximum_size_scavenge);
8535
8536   inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8537
8538   ElementsKind GetElementsKind() {
8539     DCHECK(!SitePointsToLiteral());
8540     int value = Smi::cast(transition_info())->value();
8541     return ElementsKindBits::decode(value);
8542   }
8543
8544   void SetElementsKind(ElementsKind kind) {
8545     int value = Smi::cast(transition_info())->value();
8546     set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8547                         SKIP_WRITE_BARRIER);
8548   }
8549
8550   bool CanInlineCall() {
8551     int value = Smi::cast(transition_info())->value();
8552     return DoNotInlineBit::decode(value) == 0;
8553   }
8554
8555   void SetDoNotInlineCall() {
8556     int value = Smi::cast(transition_info())->value();
8557     set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8558                         SKIP_WRITE_BARRIER);
8559   }
8560
8561   bool SitePointsToLiteral() {
8562     // If transition_info is a smi, then it represents an ElementsKind
8563     // for a constructed array. Otherwise, it must be a boilerplate
8564     // for an object or array literal.
8565     return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8566   }
8567
8568   static void DigestTransitionFeedback(Handle<AllocationSite> site,
8569                                        ElementsKind to_kind);
8570
8571   enum Reason {
8572     TENURING,
8573     TRANSITIONS
8574   };
8575
8576   static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8577                                           Reason reason,
8578                                           CompilationInfo* info);
8579
8580   DECLARE_PRINTER(AllocationSite)
8581   DECLARE_VERIFIER(AllocationSite)
8582
8583   DECLARE_CAST(AllocationSite)
8584   static inline AllocationSiteMode GetMode(
8585       ElementsKind boilerplate_elements_kind);
8586   static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8587   static inline bool CanTrack(InstanceType type);
8588
8589   static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8590   static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8591   static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8592   static const int kPretenureCreateCountOffset =
8593       kPretenureDataOffset + kPointerSize;
8594   static const int kDependentCodeOffset =
8595       kPretenureCreateCountOffset + kPointerSize;
8596   static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8597   static const int kSize = kWeakNextOffset + kPointerSize;
8598
8599   // During mark compact we need to take special care for the dependent code
8600   // field.
8601   static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8602   static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8603
8604   // For other visitors, use the fixed body descriptor below.
8605   typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8606                               kDependentCodeOffset + kPointerSize,
8607                               kSize> BodyDescriptor;
8608
8609  private:
8610   inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8611   bool PretenuringDecisionMade() {
8612     return pretenure_decision() != kUndecided;
8613   }
8614
8615   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8616 };
8617
8618
8619 class AllocationMemento: public Struct {
8620  public:
8621   static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8622   static const int kSize = kAllocationSiteOffset + kPointerSize;
8623
8624   DECL_ACCESSORS(allocation_site, Object)
8625
8626   bool IsValid() {
8627     return allocation_site()->IsAllocationSite() &&
8628         !AllocationSite::cast(allocation_site())->IsZombie();
8629   }
8630   AllocationSite* GetAllocationSite() {
8631     DCHECK(IsValid());
8632     return AllocationSite::cast(allocation_site());
8633   }
8634
8635   DECLARE_PRINTER(AllocationMemento)
8636   DECLARE_VERIFIER(AllocationMemento)
8637
8638   DECLARE_CAST(AllocationMemento)
8639
8640  private:
8641   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8642 };
8643
8644
8645 // Representation of a slow alias as part of a sloppy arguments objects.
8646 // For fast aliases (if HasSloppyArgumentsElements()):
8647 // - the parameter map contains an index into the context
8648 // - all attributes of the element have default values
8649 // For slow aliases (if HasDictionaryArgumentsElements()):
8650 // - the parameter map contains no fast alias mapping (i.e. the hole)
8651 // - this struct (in the slow backing store) contains an index into the context
8652 // - all attributes are available as part if the property details
8653 class AliasedArgumentsEntry: public Struct {
8654  public:
8655   inline int aliased_context_slot() const;
8656   inline void set_aliased_context_slot(int count);
8657
8658   DECLARE_CAST(AliasedArgumentsEntry)
8659
8660   // Dispatched behavior.
8661   DECLARE_PRINTER(AliasedArgumentsEntry)
8662   DECLARE_VERIFIER(AliasedArgumentsEntry)
8663
8664   static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8665   static const int kSize = kAliasedContextSlot + kPointerSize;
8666
8667  private:
8668   DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8669 };
8670
8671
8672 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8673 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8674
8675
8676 class StringHasher {
8677  public:
8678   explicit inline StringHasher(int length, uint32_t seed);
8679
8680   template <typename schar>
8681   static inline uint32_t HashSequentialString(const schar* chars,
8682                                               int length,
8683                                               uint32_t seed);
8684
8685   // Reads all the data, even for long strings and computes the utf16 length.
8686   static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8687                                   uint32_t seed,
8688                                   int* utf16_length_out);
8689
8690   // Calculated hash value for a string consisting of 1 to
8691   // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8692   // value is represented decimal value.
8693   static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8694
8695   // No string is allowed to have a hash of zero.  That value is reserved
8696   // for internal properties.  If the hash calculation yields zero then we
8697   // use 27 instead.
8698   static const int kZeroHash = 27;
8699
8700   // Reusable parts of the hashing algorithm.
8701   INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8702   INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8703
8704  protected:
8705   // Returns the value to store in the hash field of a string with
8706   // the given length and contents.
8707   uint32_t GetHashField();
8708   // Returns true if the hash of this string can be computed without
8709   // looking at the contents.
8710   inline bool has_trivial_hash();
8711   // Adds a block of characters to the hash.
8712   template<typename Char>
8713   inline void AddCharacters(const Char* chars, int len);
8714
8715  private:
8716   // Add a character to the hash.
8717   inline void AddCharacter(uint16_t c);
8718   // Update index. Returns true if string is still an index.
8719   inline bool UpdateIndex(uint16_t c);
8720
8721   int length_;
8722   uint32_t raw_running_hash_;
8723   uint32_t array_index_;
8724   bool is_array_index_;
8725   bool is_first_char_;
8726   DISALLOW_COPY_AND_ASSIGN(StringHasher);
8727 };
8728
8729
8730 class IteratingStringHasher : public StringHasher {
8731  public:
8732   static inline uint32_t Hash(String* string, uint32_t seed);
8733   inline void VisitOneByteString(const uint8_t* chars, int length);
8734   inline void VisitTwoByteString(const uint16_t* chars, int length);
8735
8736  private:
8737   inline IteratingStringHasher(int len, uint32_t seed)
8738       : StringHasher(len, seed) {}
8739   DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8740 };
8741
8742
8743 // The characteristics of a string are stored in its map.  Retrieving these
8744 // few bits of information is moderately expensive, involving two memory
8745 // loads where the second is dependent on the first.  To improve efficiency
8746 // the shape of the string is given its own class so that it can be retrieved
8747 // once and used for several string operations.  A StringShape is small enough
8748 // to be passed by value and is immutable, but be aware that flattening a
8749 // string can potentially alter its shape.  Also be aware that a GC caused by
8750 // something else can alter the shape of a string due to ConsString
8751 // shortcutting.  Keeping these restrictions in mind has proven to be error-
8752 // prone and so we no longer put StringShapes in variables unless there is a
8753 // concrete performance benefit at that particular point in the code.
8754 class StringShape BASE_EMBEDDED {
8755  public:
8756   inline explicit StringShape(const String* s);
8757   inline explicit StringShape(Map* s);
8758   inline explicit StringShape(InstanceType t);
8759   inline bool IsSequential();
8760   inline bool IsExternal();
8761   inline bool IsCons();
8762   inline bool IsSliced();
8763   inline bool IsIndirect();
8764   inline bool IsExternalOneByte();
8765   inline bool IsExternalTwoByte();
8766   inline bool IsSequentialOneByte();
8767   inline bool IsSequentialTwoByte();
8768   inline bool IsInternalized();
8769   inline StringRepresentationTag representation_tag();
8770   inline uint32_t encoding_tag();
8771   inline uint32_t full_representation_tag();
8772   inline uint32_t size_tag();
8773 #ifdef DEBUG
8774   inline uint32_t type() { return type_; }
8775   inline void invalidate() { valid_ = false; }
8776   inline bool valid() { return valid_; }
8777 #else
8778   inline void invalidate() { }
8779 #endif
8780
8781  private:
8782   uint32_t type_;
8783 #ifdef DEBUG
8784   inline void set_valid() { valid_ = true; }
8785   bool valid_;
8786 #else
8787   inline void set_valid() { }
8788 #endif
8789 };
8790
8791
8792 // The Name abstract class captures anything that can be used as a property
8793 // name, i.e., strings and symbols.  All names store a hash value.
8794 class Name: public HeapObject {
8795  public:
8796   // Get and set the hash field of the name.
8797   inline uint32_t hash_field();
8798   inline void set_hash_field(uint32_t value);
8799
8800   // Tells whether the hash code has been computed.
8801   inline bool HasHashCode();
8802
8803   // Returns a hash value used for the property table
8804   inline uint32_t Hash();
8805
8806   // Equality operations.
8807   inline bool Equals(Name* other);
8808   inline static bool Equals(Handle<Name> one, Handle<Name> two);
8809
8810   // Conversion.
8811   inline bool AsArrayIndex(uint32_t* index);
8812
8813   // Whether name can only name own properties.
8814   inline bool IsOwn();
8815
8816   DECLARE_CAST(Name)
8817
8818   DECLARE_PRINTER(Name)
8819
8820   // Layout description.
8821   static const int kHashFieldOffset = HeapObject::kHeaderSize;
8822   static const int kSize = kHashFieldOffset + kPointerSize;
8823
8824   // Mask constant for checking if a name has a computed hash code
8825   // and if it is a string that is an array index.  The least significant bit
8826   // indicates whether a hash code has been computed.  If the hash code has
8827   // been computed the 2nd bit tells whether the string can be used as an
8828   // array index.
8829   static const int kHashNotComputedMask = 1;
8830   static const int kIsNotArrayIndexMask = 1 << 1;
8831   static const int kNofHashBitFields = 2;
8832
8833   // Shift constant retrieving hash code from hash field.
8834   static const int kHashShift = kNofHashBitFields;
8835
8836   // Only these bits are relevant in the hash, since the top two are shifted
8837   // out.
8838   static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8839
8840   // Array index strings this short can keep their index in the hash field.
8841   static const int kMaxCachedArrayIndexLength = 7;
8842
8843   // For strings which are array indexes the hash value has the string length
8844   // mixed into the hash, mainly to avoid a hash value of zero which would be
8845   // the case for the string '0'. 24 bits are used for the array index value.
8846   static const int kArrayIndexValueBits = 24;
8847   static const int kArrayIndexLengthBits =
8848       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8849
8850   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8851
8852   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8853       kArrayIndexValueBits> {};  // NOLINT
8854   class ArrayIndexLengthBits : public BitField<unsigned int,
8855       kNofHashBitFields + kArrayIndexValueBits,
8856       kArrayIndexLengthBits> {};  // NOLINT
8857
8858   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8859   // could use a mask to test if the length of string is less than or equal to
8860   // kMaxCachedArrayIndexLength.
8861   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8862
8863   static const unsigned int kContainsCachedArrayIndexMask =
8864       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8865        << ArrayIndexLengthBits::kShift) |
8866       kIsNotArrayIndexMask;
8867
8868   // Value of empty hash field indicating that the hash is not computed.
8869   static const int kEmptyHashField =
8870       kIsNotArrayIndexMask | kHashNotComputedMask;
8871
8872  protected:
8873   static inline bool IsHashFieldComputed(uint32_t field);
8874
8875  private:
8876   DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8877 };
8878
8879
8880 // ES6 symbols.
8881 class Symbol: public Name {
8882  public:
8883   // [name]: the print name of a symbol, or undefined if none.
8884   DECL_ACCESSORS(name, Object)
8885
8886   DECL_ACCESSORS(flags, Smi)
8887
8888   // [is_private]: whether this is a private symbol.
8889   DECL_BOOLEAN_ACCESSORS(is_private)
8890
8891   // [is_own]: whether this is an own symbol, that is, only used to designate
8892   // own properties of objects.
8893   DECL_BOOLEAN_ACCESSORS(is_own)
8894
8895   DECLARE_CAST(Symbol)
8896
8897   // Dispatched behavior.
8898   DECLARE_PRINTER(Symbol)
8899   DECLARE_VERIFIER(Symbol)
8900
8901   // Layout description.
8902   static const int kNameOffset = Name::kSize;
8903   static const int kFlagsOffset = kNameOffset + kPointerSize;
8904   static const int kSize = kFlagsOffset + kPointerSize;
8905
8906   typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8907
8908  private:
8909   static const int kPrivateBit = 0;
8910   static const int kOwnBit = 1;
8911
8912   DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8913 };
8914
8915
8916 class ConsString;
8917
8918 // The String abstract class captures JavaScript string values:
8919 //
8920 // Ecma-262:
8921 //  4.3.16 String Value
8922 //    A string value is a member of the type String and is a finite
8923 //    ordered sequence of zero or more 16-bit unsigned integer values.
8924 //
8925 // All string values have a length field.
8926 class String: public Name {
8927  public:
8928   enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8929
8930   // Array index strings this short can keep their index in the hash field.
8931   static const int kMaxCachedArrayIndexLength = 7;
8932
8933   // For strings which are array indexes the hash value has the string length
8934   // mixed into the hash, mainly to avoid a hash value of zero which would be
8935   // the case for the string '0'. 24 bits are used for the array index value.
8936   static const int kArrayIndexValueBits = 24;
8937   static const int kArrayIndexLengthBits =
8938       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8939
8940   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8941
8942   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8943       kArrayIndexValueBits> {};  // NOLINT
8944   class ArrayIndexLengthBits : public BitField<unsigned int,
8945       kNofHashBitFields + kArrayIndexValueBits,
8946       kArrayIndexLengthBits> {};  // NOLINT
8947
8948   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8949   // could use a mask to test if the length of string is less than or equal to
8950   // kMaxCachedArrayIndexLength.
8951   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8952
8953   static const unsigned int kContainsCachedArrayIndexMask =
8954       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8955        << ArrayIndexLengthBits::kShift) |
8956       kIsNotArrayIndexMask;
8957
8958   // Representation of the flat content of a String.
8959   // A non-flat string doesn't have flat content.
8960   // A flat string has content that's encoded as a sequence of either
8961   // one-byte chars or two-byte UC16.
8962   // Returned by String::GetFlatContent().
8963   class FlatContent {
8964    public:
8965     // Returns true if the string is flat and this structure contains content.
8966     bool IsFlat() { return state_ != NON_FLAT; }
8967     // Returns true if the structure contains one-byte content.
8968     bool IsOneByte() { return state_ == ONE_BYTE; }
8969     // Returns true if the structure contains two-byte content.
8970     bool IsTwoByte() { return state_ == TWO_BYTE; }
8971
8972     // Return the one byte content of the string. Only use if IsOneByte()
8973     // returns true.
8974     Vector<const uint8_t> ToOneByteVector() {
8975       DCHECK_EQ(ONE_BYTE, state_);
8976       return Vector<const uint8_t>(onebyte_start, length_);
8977     }
8978     // Return the two-byte content of the string. Only use if IsTwoByte()
8979     // returns true.
8980     Vector<const uc16> ToUC16Vector() {
8981       DCHECK_EQ(TWO_BYTE, state_);
8982       return Vector<const uc16>(twobyte_start, length_);
8983     }
8984
8985     uc16 Get(int i) {
8986       DCHECK(i < length_);
8987       DCHECK(state_ != NON_FLAT);
8988       if (state_ == ONE_BYTE) return onebyte_start[i];
8989       return twobyte_start[i];
8990     }
8991
8992    private:
8993     enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8994
8995     // Constructors only used by String::GetFlatContent().
8996     explicit FlatContent(const uint8_t* start, int length)
8997         : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8998     explicit FlatContent(const uc16* start, int length)
8999         : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
9000     FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
9001
9002     union {
9003       const uint8_t* onebyte_start;
9004       const uc16* twobyte_start;
9005     };
9006     int length_;
9007     State state_;
9008
9009     friend class String;
9010   };
9011
9012   // Get and set the length of the string.
9013   inline int length() const;
9014   inline void set_length(int value);
9015
9016   // Get and set the length of the string using acquire loads and release
9017   // stores.
9018   inline int synchronized_length() const;
9019   inline void synchronized_set_length(int value);
9020
9021   // Returns whether this string has only one-byte chars, i.e. all of them can
9022   // be one-byte encoded.  This might be the case even if the string is
9023   // two-byte.  Such strings may appear when the embedder prefers
9024   // two-byte external representations even for one-byte data.
9025   inline bool IsOneByteRepresentation() const;
9026   inline bool IsTwoByteRepresentation() const;
9027
9028   // Cons and slices have an encoding flag that may not represent the actual
9029   // encoding of the underlying string.  This is taken into account here.
9030   // Requires: this->IsFlat()
9031   inline bool IsOneByteRepresentationUnderneath();
9032   inline bool IsTwoByteRepresentationUnderneath();
9033
9034   // NOTE: this should be considered only a hint.  False negatives are
9035   // possible.
9036   inline bool HasOnlyOneByteChars();
9037
9038   // Get and set individual two byte chars in the string.
9039   inline void Set(int index, uint16_t value);
9040   // Get individual two byte char in the string.  Repeated calls
9041   // to this method are not efficient unless the string is flat.
9042   INLINE(uint16_t Get(int index));
9043
9044   // Flattens the string.  Checks first inline to see if it is
9045   // necessary.  Does nothing if the string is not a cons string.
9046   // Flattening allocates a sequential string with the same data as
9047   // the given string and mutates the cons string to a degenerate
9048   // form, where the first component is the new sequential string and
9049   // the second component is the empty string.  If allocation fails,
9050   // this function returns a failure.  If flattening succeeds, this
9051   // function returns the sequential string that is now the first
9052   // component of the cons string.
9053   //
9054   // Degenerate cons strings are handled specially by the garbage
9055   // collector (see IsShortcutCandidate).
9056
9057   static inline Handle<String> Flatten(Handle<String> string,
9058                                        PretenureFlag pretenure = NOT_TENURED);
9059
9060   // Tries to return the content of a flat string as a structure holding either
9061   // a flat vector of char or of uc16.
9062   // If the string isn't flat, and therefore doesn't have flat content, the
9063   // returned structure will report so, and can't provide a vector of either
9064   // kind.
9065   FlatContent GetFlatContent();
9066
9067   // Returns the parent of a sliced string or first part of a flat cons string.
9068   // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9069   inline String* GetUnderlying();
9070
9071   // Mark the string as an undetectable object. It only applies to
9072   // one-byte and two-byte string types.
9073   bool MarkAsUndetectable();
9074
9075   // String equality operations.
9076   inline bool Equals(String* other);
9077   inline static bool Equals(Handle<String> one, Handle<String> two);
9078   bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9079   bool IsOneByteEqualTo(Vector<const uint8_t> str);
9080   bool IsTwoByteEqualTo(Vector<const uc16> str);
9081
9082   // Return a UTF8 representation of the string.  The string is null
9083   // terminated but may optionally contain nulls.  Length is returned
9084   // in length_output if length_output is not a null pointer  The string
9085   // should be nearly flat, otherwise the performance of this method may
9086   // be very slow (quadratic in the length).  Setting robustness_flag to
9087   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9088   // handles unexpected data without causing assert failures and it does not
9089   // do any heap allocations.  This is useful when printing stack traces.
9090   SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9091                                     RobustnessFlag robustness_flag,
9092                                     int offset,
9093                                     int length,
9094                                     int* length_output = 0);
9095   SmartArrayPointer<char> ToCString(
9096       AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9097       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9098       int* length_output = 0);
9099
9100   // Return a 16 bit Unicode representation of the string.
9101   // The string should be nearly flat, otherwise the performance of
9102   // of this method may be very bad.  Setting robustness_flag to
9103   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9104   // handles unexpected data without causing assert failures and it does not
9105   // do any heap allocations.  This is useful when printing stack traces.
9106   SmartArrayPointer<uc16> ToWideCString(
9107       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9108
9109   bool ComputeArrayIndex(uint32_t* index);
9110
9111   // Externalization.
9112   bool MakeExternal(v8::String::ExternalStringResource* resource);
9113   bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
9114
9115   // Conversion.
9116   inline bool AsArrayIndex(uint32_t* index);
9117
9118   DECLARE_CAST(String)
9119
9120   void PrintOn(FILE* out);
9121
9122   // For use during stack traces.  Performs rudimentary sanity check.
9123   bool LooksValid();
9124
9125   // Dispatched behavior.
9126   void StringShortPrint(StringStream* accumulator);
9127   void PrintUC16(OStream& os, int start = 0, int end = -1);  // NOLINT
9128 #ifdef OBJECT_PRINT
9129   char* ToAsciiArray();
9130 #endif
9131   DECLARE_PRINTER(String)
9132   DECLARE_VERIFIER(String)
9133
9134   inline bool IsFlat();
9135
9136   // Layout description.
9137   static const int kLengthOffset = Name::kSize;
9138   static const int kSize = kLengthOffset + kPointerSize;
9139
9140   // Maximum number of characters to consider when trying to convert a string
9141   // value into an array index.
9142   static const int kMaxArrayIndexSize = 10;
9143   STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9144
9145   // Max char codes.
9146   static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9147   static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9148   static const int kMaxUtf16CodeUnit = 0xffff;
9149   static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
9150
9151   // Value of hash field containing computed hash equal to zero.
9152   static const int kEmptyStringHash = kIsNotArrayIndexMask;
9153
9154   // Maximal string length.
9155   static const int kMaxLength = (1 << 28) - 16;
9156
9157   // Max length for computing hash. For strings longer than this limit the
9158   // string length is used as the hash value.
9159   static const int kMaxHashCalcLength = 16383;
9160
9161   // Limit for truncation in short printing.
9162   static const int kMaxShortPrintLength = 1024;
9163
9164   // Support for regular expressions.
9165   const uc16* GetTwoByteData(unsigned start);
9166
9167   // Helper function for flattening strings.
9168   template <typename sinkchar>
9169   static void WriteToFlat(String* source,
9170                           sinkchar* sink,
9171                           int from,
9172                           int to);
9173
9174   // The return value may point to the first aligned word containing the first
9175   // non-one-byte character, rather than directly to the non-one-byte character.
9176   // If the return value is >= the passed length, the entire string was
9177   // one-byte.
9178   static inline int NonAsciiStart(const char* chars, int length) {
9179     const char* start = chars;
9180     const char* limit = chars + length;
9181
9182     if (length >= kIntptrSize) {
9183       // Check unaligned bytes.
9184       while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
9185         if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9186           return static_cast<int>(chars - start);
9187         }
9188         ++chars;
9189       }
9190       // Check aligned words.
9191       DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9192       const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9193       while (chars + sizeof(uintptr_t) <= limit) {
9194         if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
9195           return static_cast<int>(chars - start);
9196         }
9197         chars += sizeof(uintptr_t);
9198       }
9199     }
9200     // Check remaining unaligned bytes.
9201     while (chars < limit) {
9202       if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9203         return static_cast<int>(chars - start);
9204       }
9205       ++chars;
9206     }
9207
9208     return static_cast<int>(chars - start);
9209   }
9210
9211   static inline bool IsAscii(const char* chars, int length) {
9212     return NonAsciiStart(chars, length) >= length;
9213   }
9214
9215   static inline bool IsAscii(const uint8_t* chars, int length) {
9216     return
9217         NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9218   }
9219
9220   static inline int NonOneByteStart(const uc16* chars, int length) {
9221     const uc16* limit = chars + length;
9222     const uc16* start = chars;
9223     while (chars < limit) {
9224       if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9225       ++chars;
9226     }
9227     return static_cast<int>(chars - start);
9228   }
9229
9230   static inline bool IsOneByte(const uc16* chars, int length) {
9231     return NonOneByteStart(chars, length) >= length;
9232   }
9233
9234   template<class Visitor>
9235   static inline ConsString* VisitFlat(Visitor* visitor,
9236                                       String* string,
9237                                       int offset = 0);
9238
9239   static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9240                                               bool include_ending_line);
9241
9242   // Use the hash field to forward to the canonical internalized string
9243   // when deserializing an internalized string.
9244   inline void SetForwardedInternalizedString(String* string);
9245   inline String* GetForwardedInternalizedString();
9246
9247  private:
9248   friend class Name;
9249   friend class StringTableInsertionKey;
9250
9251   static Handle<String> SlowFlatten(Handle<ConsString> cons,
9252                                     PretenureFlag tenure);
9253
9254   // Slow case of String::Equals.  This implementation works on any strings
9255   // but it is most efficient on strings that are almost flat.
9256   bool SlowEquals(String* other);
9257
9258   static bool SlowEquals(Handle<String> one, Handle<String> two);
9259
9260   // Slow case of AsArrayIndex.
9261   bool SlowAsArrayIndex(uint32_t* index);
9262
9263   // Compute and set the hash code.
9264   uint32_t ComputeAndSetHash();
9265
9266   DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9267 };
9268
9269
9270 // The SeqString abstract class captures sequential string values.
9271 class SeqString: public String {
9272  public:
9273   DECLARE_CAST(SeqString)
9274
9275   // Layout description.
9276   static const int kHeaderSize = String::kSize;
9277
9278   // Truncate the string in-place if possible and return the result.
9279   // In case of new_length == 0, the empty string is returned without
9280   // truncating the original string.
9281   MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9282                                                  int new_length);
9283  private:
9284   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9285 };
9286
9287
9288 // The OneByteString class captures sequential one-byte string objects.
9289 // Each character in the OneByteString is an one-byte character.
9290 class SeqOneByteString: public SeqString {
9291  public:
9292   static const bool kHasOneByteEncoding = true;
9293
9294   // Dispatched behavior.
9295   inline uint16_t SeqOneByteStringGet(int index);
9296   inline void SeqOneByteStringSet(int index, uint16_t value);
9297
9298   // Get the address of the characters in this string.
9299   inline Address GetCharsAddress();
9300
9301   inline uint8_t* GetChars();
9302
9303   DECLARE_CAST(SeqOneByteString)
9304
9305   // Garbage collection support.  This method is called by the
9306   // garbage collector to compute the actual size of an OneByteString
9307   // instance.
9308   inline int SeqOneByteStringSize(InstanceType instance_type);
9309
9310   // Computes the size for an OneByteString instance of a given length.
9311   static int SizeFor(int length) {
9312     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9313   }
9314
9315   // Maximal memory usage for a single sequential one-byte string.
9316   static const int kMaxSize = 512 * MB - 1;
9317   STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9318
9319  private:
9320   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9321 };
9322
9323
9324 // The TwoByteString class captures sequential unicode string objects.
9325 // Each character in the TwoByteString is a two-byte uint16_t.
9326 class SeqTwoByteString: public SeqString {
9327  public:
9328   static const bool kHasOneByteEncoding = false;
9329
9330   // Dispatched behavior.
9331   inline uint16_t SeqTwoByteStringGet(int index);
9332   inline void SeqTwoByteStringSet(int index, uint16_t value);
9333
9334   // Get the address of the characters in this string.
9335   inline Address GetCharsAddress();
9336
9337   inline uc16* GetChars();
9338
9339   // For regexp code.
9340   const uint16_t* SeqTwoByteStringGetData(unsigned start);
9341
9342   DECLARE_CAST(SeqTwoByteString)
9343
9344   // Garbage collection support.  This method is called by the
9345   // garbage collector to compute the actual size of a TwoByteString
9346   // instance.
9347   inline int SeqTwoByteStringSize(InstanceType instance_type);
9348
9349   // Computes the size for a TwoByteString instance of a given length.
9350   static int SizeFor(int length) {
9351     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9352   }
9353
9354   // Maximal memory usage for a single sequential two-byte string.
9355   static const int kMaxSize = 512 * MB - 1;
9356   STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9357                String::kMaxLength);
9358
9359  private:
9360   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9361 };
9362
9363
9364 // The ConsString class describes string values built by using the
9365 // addition operator on strings.  A ConsString is a pair where the
9366 // first and second components are pointers to other string values.
9367 // One or both components of a ConsString can be pointers to other
9368 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9369 // are non-ConsString string values.  The string value represented by
9370 // a ConsString can be obtained by concatenating the leaf string
9371 // values in a left-to-right depth-first traversal of the tree.
9372 class ConsString: public String {
9373  public:
9374   // First string of the cons cell.
9375   inline String* first();
9376   // Doesn't check that the result is a string, even in debug mode.  This is
9377   // useful during GC where the mark bits confuse the checks.
9378   inline Object* unchecked_first();
9379   inline void set_first(String* first,
9380                         WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9381
9382   // Second string of the cons cell.
9383   inline String* second();
9384   // Doesn't check that the result is a string, even in debug mode.  This is
9385   // useful during GC where the mark bits confuse the checks.
9386   inline Object* unchecked_second();
9387   inline void set_second(String* second,
9388                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9389
9390   // Dispatched behavior.
9391   uint16_t ConsStringGet(int index);
9392
9393   DECLARE_CAST(ConsString)
9394
9395   // Layout description.
9396   static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9397   static const int kSecondOffset = kFirstOffset + kPointerSize;
9398   static const int kSize = kSecondOffset + kPointerSize;
9399
9400   // Minimum length for a cons string.
9401   static const int kMinLength = 13;
9402
9403   typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9404           BodyDescriptor;
9405
9406   DECLARE_VERIFIER(ConsString)
9407
9408  private:
9409   DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9410 };
9411
9412
9413 // The Sliced String class describes strings that are substrings of another
9414 // sequential string.  The motivation is to save time and memory when creating
9415 // a substring.  A Sliced String is described as a pointer to the parent,
9416 // the offset from the start of the parent string and the length.  Using
9417 // a Sliced String therefore requires unpacking of the parent string and
9418 // adding the offset to the start address.  A substring of a Sliced String
9419 // are not nested since the double indirection is simplified when creating
9420 // such a substring.
9421 // Currently missing features are:
9422 //  - handling externalized parent strings
9423 //  - external strings as parent
9424 //  - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9425 class SlicedString: public String {
9426  public:
9427   inline String* parent();
9428   inline void set_parent(String* parent,
9429                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9430   inline int offset() const;
9431   inline void set_offset(int offset);
9432
9433   // Dispatched behavior.
9434   uint16_t SlicedStringGet(int index);
9435
9436   DECLARE_CAST(SlicedString)
9437
9438   // Layout description.
9439   static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9440   static const int kOffsetOffset = kParentOffset + kPointerSize;
9441   static const int kSize = kOffsetOffset + kPointerSize;
9442
9443   // Minimum length for a sliced string.
9444   static const int kMinLength = 13;
9445
9446   typedef FixedBodyDescriptor<kParentOffset,
9447                               kOffsetOffset + kPointerSize, kSize>
9448           BodyDescriptor;
9449
9450   DECLARE_VERIFIER(SlicedString)
9451
9452  private:
9453   DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9454 };
9455
9456
9457 // The ExternalString class describes string values that are backed by
9458 // a string resource that lies outside the V8 heap.  ExternalStrings
9459 // consist of the length field common to all strings, a pointer to the
9460 // external resource.  It is important to ensure (externally) that the
9461 // resource is not deallocated while the ExternalString is live in the
9462 // V8 heap.
9463 //
9464 // The API expects that all ExternalStrings are created through the
9465 // API.  Therefore, ExternalStrings should not be used internally.
9466 class ExternalString: public String {
9467  public:
9468   DECLARE_CAST(ExternalString)
9469
9470   // Layout description.
9471   static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9472   static const int kShortSize = kResourceOffset + kPointerSize;
9473   static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9474   static const int kSize = kResourceDataOffset + kPointerSize;
9475
9476   static const int kMaxShortLength =
9477       (kShortSize - SeqString::kHeaderSize) / kCharSize;
9478
9479   // Return whether external string is short (data pointer is not cached).
9480   inline bool is_short();
9481
9482   STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9483
9484  private:
9485   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9486 };
9487
9488
9489 // The ExternalOneByteString class is an external string backed by an
9490 // one-byte string.
9491 class ExternalOneByteString : public ExternalString {
9492  public:
9493   static const bool kHasOneByteEncoding = true;
9494
9495   typedef v8::String::ExternalOneByteStringResource Resource;
9496
9497   // The underlying resource.
9498   inline const Resource* resource();
9499   inline void set_resource(const Resource* buffer);
9500
9501   // Update the pointer cache to the external character array.
9502   // The cached pointer is always valid, as the external character array does =
9503   // not move during lifetime.  Deserialization is the only exception, after
9504   // which the pointer cache has to be refreshed.
9505   inline void update_data_cache();
9506
9507   inline const uint8_t* GetChars();
9508
9509   // Dispatched behavior.
9510   inline uint16_t ExternalOneByteStringGet(int index);
9511
9512   DECLARE_CAST(ExternalOneByteString)
9513
9514   // Garbage collection support.
9515   inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9516
9517   template <typename StaticVisitor>
9518   inline void ExternalOneByteStringIterateBody();
9519
9520  private:
9521   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9522 };
9523
9524
9525 // The ExternalTwoByteString class is an external string backed by a UTF-16
9526 // encoded string.
9527 class ExternalTwoByteString: public ExternalString {
9528  public:
9529   static const bool kHasOneByteEncoding = false;
9530
9531   typedef v8::String::ExternalStringResource Resource;
9532
9533   // The underlying string resource.
9534   inline const Resource* resource();
9535   inline void set_resource(const Resource* buffer);
9536
9537   // Update the pointer cache to the external character array.
9538   // The cached pointer is always valid, as the external character array does =
9539   // not move during lifetime.  Deserialization is the only exception, after
9540   // which the pointer cache has to be refreshed.
9541   inline void update_data_cache();
9542
9543   inline const uint16_t* GetChars();
9544
9545   // Dispatched behavior.
9546   inline uint16_t ExternalTwoByteStringGet(int index);
9547
9548   // For regexp code.
9549   inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9550
9551   DECLARE_CAST(ExternalTwoByteString)
9552
9553   // Garbage collection support.
9554   inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9555
9556   template<typename StaticVisitor>
9557   inline void ExternalTwoByteStringIterateBody();
9558
9559  private:
9560   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9561 };
9562
9563
9564 // Utility superclass for stack-allocated objects that must be updated
9565 // on gc.  It provides two ways for the gc to update instances, either
9566 // iterating or updating after gc.
9567 class Relocatable BASE_EMBEDDED {
9568  public:
9569   explicit inline Relocatable(Isolate* isolate);
9570   inline virtual ~Relocatable();
9571   virtual void IterateInstance(ObjectVisitor* v) { }
9572   virtual void PostGarbageCollection() { }
9573
9574   static void PostGarbageCollectionProcessing(Isolate* isolate);
9575   static int ArchiveSpacePerThread();
9576   static char* ArchiveState(Isolate* isolate, char* to);
9577   static char* RestoreState(Isolate* isolate, char* from);
9578   static void Iterate(Isolate* isolate, ObjectVisitor* v);
9579   static void Iterate(ObjectVisitor* v, Relocatable* top);
9580   static char* Iterate(ObjectVisitor* v, char* t);
9581
9582  private:
9583   Isolate* isolate_;
9584   Relocatable* prev_;
9585 };
9586
9587
9588 // A flat string reader provides random access to the contents of a
9589 // string independent of the character width of the string.  The handle
9590 // must be valid as long as the reader is being used.
9591 class FlatStringReader : public Relocatable {
9592  public:
9593   FlatStringReader(Isolate* isolate, Handle<String> str);
9594   FlatStringReader(Isolate* isolate, Vector<const char> input);
9595   void PostGarbageCollection();
9596   inline uc32 Get(int index);
9597   int length() { return length_; }
9598  private:
9599   String** str_;
9600   bool is_one_byte_;
9601   int length_;
9602   const void* start_;
9603 };
9604
9605
9606 // A ConsStringOp that returns null.
9607 // Useful when the operation to apply on a ConsString
9608 // requires an expensive data structure.
9609 class ConsStringNullOp {
9610  public:
9611   inline ConsStringNullOp() {}
9612   static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9613  private:
9614   DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9615 };
9616
9617
9618 // This maintains an off-stack representation of the stack frames required
9619 // to traverse a ConsString, allowing an entirely iterative and restartable
9620 // traversal of the entire string
9621 class ConsStringIteratorOp {
9622  public:
9623   inline ConsStringIteratorOp() {}
9624   inline explicit ConsStringIteratorOp(ConsString* cons_string,
9625                                        int offset = 0) {
9626     Reset(cons_string, offset);
9627   }
9628   inline void Reset(ConsString* cons_string, int offset = 0) {
9629     depth_ = 0;
9630     // Next will always return NULL.
9631     if (cons_string == NULL) return;
9632     Initialize(cons_string, offset);
9633   }
9634   // Returns NULL when complete.
9635   inline String* Next(int* offset_out) {
9636     *offset_out = 0;
9637     if (depth_ == 0) return NULL;
9638     return Continue(offset_out);
9639   }
9640
9641  private:
9642   static const int kStackSize = 32;
9643   // Use a mask instead of doing modulo operations for stack wrapping.
9644   static const int kDepthMask = kStackSize-1;
9645   STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9646   static inline int OffsetForDepth(int depth);
9647
9648   inline void PushLeft(ConsString* string);
9649   inline void PushRight(ConsString* string);
9650   inline void AdjustMaximumDepth();
9651   inline void Pop();
9652   inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9653   void Initialize(ConsString* cons_string, int offset);
9654   String* Continue(int* offset_out);
9655   String* NextLeaf(bool* blew_stack);
9656   String* Search(int* offset_out);
9657
9658   // Stack must always contain only frames for which right traversal
9659   // has not yet been performed.
9660   ConsString* frames_[kStackSize];
9661   ConsString* root_;
9662   int depth_;
9663   int maximum_depth_;
9664   int consumed_;
9665   DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9666 };
9667
9668
9669 class StringCharacterStream {
9670  public:
9671   inline StringCharacterStream(String* string,
9672                                ConsStringIteratorOp* op,
9673                                int offset = 0);
9674   inline uint16_t GetNext();
9675   inline bool HasMore();
9676   inline void Reset(String* string, int offset = 0);
9677   inline void VisitOneByteString(const uint8_t* chars, int length);
9678   inline void VisitTwoByteString(const uint16_t* chars, int length);
9679
9680  private:
9681   bool is_one_byte_;
9682   union {
9683     const uint8_t* buffer8_;
9684     const uint16_t* buffer16_;
9685   };
9686   const uint8_t* end_;
9687   ConsStringIteratorOp* op_;
9688   DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9689 };
9690
9691
9692 template <typename T>
9693 class VectorIterator {
9694  public:
9695   VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9696   explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9697   T GetNext() { return data_[index_++]; }
9698   bool has_more() { return index_ < data_.length(); }
9699  private:
9700   Vector<const T> data_;
9701   int index_;
9702 };
9703
9704
9705 // The Oddball describes objects null, undefined, true, and false.
9706 class Oddball: public HeapObject {
9707  public:
9708   // [to_string]: Cached to_string computed at startup.
9709   DECL_ACCESSORS(to_string, String)
9710
9711   // [to_number]: Cached to_number computed at startup.
9712   DECL_ACCESSORS(to_number, Object)
9713
9714   inline byte kind() const;
9715   inline void set_kind(byte kind);
9716
9717   DECLARE_CAST(Oddball)
9718
9719   // Dispatched behavior.
9720   DECLARE_VERIFIER(Oddball)
9721
9722   // Initialize the fields.
9723   static void Initialize(Isolate* isolate,
9724                          Handle<Oddball> oddball,
9725                          const char* to_string,
9726                          Handle<Object> to_number,
9727                          byte kind);
9728
9729   // Layout description.
9730   static const int kToStringOffset = HeapObject::kHeaderSize;
9731   static const int kToNumberOffset = kToStringOffset + kPointerSize;
9732   static const int kKindOffset = kToNumberOffset + kPointerSize;
9733   static const int kSize = kKindOffset + kPointerSize;
9734
9735   static const byte kFalse = 0;
9736   static const byte kTrue = 1;
9737   static const byte kNotBooleanMask = ~1;
9738   static const byte kTheHole = 2;
9739   static const byte kNull = 3;
9740   static const byte kArgumentMarker = 4;
9741   static const byte kUndefined = 5;
9742   static const byte kUninitialized = 6;
9743   static const byte kOther = 7;
9744   static const byte kException = 8;
9745
9746   typedef FixedBodyDescriptor<kToStringOffset,
9747                               kToNumberOffset + kPointerSize,
9748                               kSize> BodyDescriptor;
9749
9750   STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9751   STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9752   STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9753
9754  private:
9755   DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9756 };
9757
9758
9759 class Cell: public HeapObject {
9760  public:
9761   // [value]: value of the global property.
9762   DECL_ACCESSORS(value, Object)
9763
9764   DECLARE_CAST(Cell)
9765
9766   static inline Cell* FromValueAddress(Address value) {
9767     Object* result = FromAddress(value - kValueOffset);
9768     DCHECK(result->IsCell() || result->IsPropertyCell());
9769     return static_cast<Cell*>(result);
9770   }
9771
9772   inline Address ValueAddress() {
9773     return address() + kValueOffset;
9774   }
9775
9776   // Dispatched behavior.
9777   DECLARE_PRINTER(Cell)
9778   DECLARE_VERIFIER(Cell)
9779
9780   // Layout description.
9781   static const int kValueOffset = HeapObject::kHeaderSize;
9782   static const int kSize = kValueOffset + kPointerSize;
9783
9784   typedef FixedBodyDescriptor<kValueOffset,
9785                               kValueOffset + kPointerSize,
9786                               kSize> BodyDescriptor;
9787
9788  private:
9789   DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9790 };
9791
9792
9793 class PropertyCell: public Cell {
9794  public:
9795   // [type]: type of the global property.
9796   HeapType* type();
9797   void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9798
9799   // [dependent_code]: dependent code that depends on the type of the global
9800   // property.
9801   DECL_ACCESSORS(dependent_code, DependentCode)
9802
9803   // Sets the value of the cell and updates the type field to be the union
9804   // of the cell's current type and the value's type. If the change causes
9805   // a change of the type of the cell's contents, code dependent on the cell
9806   // will be deoptimized.
9807   static void SetValueInferType(Handle<PropertyCell> cell,
9808                                 Handle<Object> value);
9809
9810   // Computes the new type of the cell's contents for the given value, but
9811   // without actually modifying the 'type' field.
9812   static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9813                                       Handle<Object> value);
9814
9815   static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9816                                           CompilationInfo* info);
9817
9818   DECLARE_CAST(PropertyCell)
9819
9820   inline Address TypeAddress() {
9821     return address() + kTypeOffset;
9822   }
9823
9824   // Dispatched behavior.
9825   DECLARE_PRINTER(PropertyCell)
9826   DECLARE_VERIFIER(PropertyCell)
9827
9828   // Layout description.
9829   static const int kTypeOffset = kValueOffset + kPointerSize;
9830   static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9831   static const int kSize = kDependentCodeOffset + kPointerSize;
9832
9833   static const int kPointerFieldsBeginOffset = kValueOffset;
9834   static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9835
9836   typedef FixedBodyDescriptor<kValueOffset,
9837                               kSize,
9838                               kSize> BodyDescriptor;
9839
9840  private:
9841   DECL_ACCESSORS(type_raw, Object)
9842   DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9843 };
9844
9845
9846 // The JSProxy describes EcmaScript Harmony proxies
9847 class JSProxy: public JSReceiver {
9848  public:
9849   // [handler]: The handler property.
9850   DECL_ACCESSORS(handler, Object)
9851
9852   // [hash]: The hash code property (undefined if not initialized yet).
9853   DECL_ACCESSORS(hash, Object)
9854
9855   DECLARE_CAST(JSProxy)
9856
9857   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9858       Handle<JSProxy> proxy,
9859       Handle<Object> receiver,
9860       Handle<Name> name);
9861   MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9862       Handle<JSProxy> proxy,
9863       Handle<Object> receiver,
9864       uint32_t index);
9865
9866   // If the handler defines an accessor property with a setter, invoke it.
9867   // If it defines an accessor property without a setter, or a data property
9868   // that is read-only, throw. In all these cases set '*done' to true,
9869   // otherwise set it to false.
9870   MUST_USE_RESULT
9871   static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9872       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9873       Handle<Object> value, StrictMode strict_mode, bool* done);
9874
9875   MUST_USE_RESULT static Maybe<PropertyAttributes>
9876       GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9877                                        Handle<Object> receiver,
9878                                        Handle<Name> name);
9879   MUST_USE_RESULT static Maybe<PropertyAttributes>
9880       GetElementAttributeWithHandler(Handle<JSProxy> proxy,
9881                                      Handle<JSReceiver> receiver,
9882                                      uint32_t index);
9883   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9884       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9885       Handle<Object> value, StrictMode strict_mode);
9886
9887   // Turn the proxy into an (empty) JSObject.
9888   static void Fix(Handle<JSProxy> proxy);
9889
9890   // Initializes the body after the handler slot.
9891   inline void InitializeBody(int object_size, Object* value);
9892
9893   // Invoke a trap by name. If the trap does not exist on this's handler,
9894   // but derived_trap is non-NULL, invoke that instead.  May cause GC.
9895   MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9896       Handle<JSProxy> proxy,
9897       const char* name,
9898       Handle<Object> derived_trap,
9899       int argc,
9900       Handle<Object> args[]);
9901
9902   // Dispatched behavior.
9903   DECLARE_PRINTER(JSProxy)
9904   DECLARE_VERIFIER(JSProxy)
9905
9906   // Layout description. We add padding so that a proxy has the same
9907   // size as a virgin JSObject. This is essential for becoming a JSObject
9908   // upon freeze.
9909   static const int kHandlerOffset = HeapObject::kHeaderSize;
9910   static const int kHashOffset = kHandlerOffset + kPointerSize;
9911   static const int kPaddingOffset = kHashOffset + kPointerSize;
9912   static const int kSize = JSObject::kHeaderSize;
9913   static const int kHeaderSize = kPaddingOffset;
9914   static const int kPaddingSize = kSize - kPaddingOffset;
9915
9916   STATIC_ASSERT(kPaddingSize >= 0);
9917
9918   typedef FixedBodyDescriptor<kHandlerOffset,
9919                               kPaddingOffset,
9920                               kSize> BodyDescriptor;
9921
9922  private:
9923   friend class JSReceiver;
9924
9925   MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
9926       Handle<JSProxy> proxy,
9927       Handle<JSReceiver> receiver,
9928       uint32_t index,
9929       Handle<Object> value,
9930       StrictMode strict_mode);
9931
9932   MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9933       Handle<JSProxy> proxy, Handle<Name> name);
9934   MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
9935       Handle<JSProxy> proxy, uint32_t index);
9936
9937   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9938       Handle<JSProxy> proxy,
9939       Handle<Name> name,
9940       DeleteMode mode);
9941   MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
9942       Handle<JSProxy> proxy,
9943       uint32_t index,
9944       DeleteMode mode);
9945
9946   MUST_USE_RESULT Object* GetIdentityHash();
9947
9948   static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9949
9950   DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9951 };
9952
9953
9954 class JSFunctionProxy: public JSProxy {
9955  public:
9956   // [call_trap]: The call trap.
9957   DECL_ACCESSORS(call_trap, Object)
9958
9959   // [construct_trap]: The construct trap.
9960   DECL_ACCESSORS(construct_trap, Object)
9961
9962   DECLARE_CAST(JSFunctionProxy)
9963
9964   // Dispatched behavior.
9965   DECLARE_PRINTER(JSFunctionProxy)
9966   DECLARE_VERIFIER(JSFunctionProxy)
9967
9968   // Layout description.
9969   static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9970   static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9971   static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9972   static const int kSize = JSFunction::kSize;
9973   static const int kPaddingSize = kSize - kPaddingOffset;
9974
9975   STATIC_ASSERT(kPaddingSize >= 0);
9976
9977   typedef FixedBodyDescriptor<kHandlerOffset,
9978                               kConstructTrapOffset + kPointerSize,
9979                               kSize> BodyDescriptor;
9980
9981  private:
9982   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9983 };
9984
9985
9986 class JSCollection : public JSObject {
9987  public:
9988   // [table]: the backing hash table
9989   DECL_ACCESSORS(table, Object)
9990
9991   static const int kTableOffset = JSObject::kHeaderSize;
9992   static const int kSize = kTableOffset + kPointerSize;
9993
9994  private:
9995   DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9996 };
9997
9998
9999 // The JSSet describes EcmaScript Harmony sets
10000 class JSSet : public JSCollection {
10001  public:
10002   DECLARE_CAST(JSSet)
10003
10004   // Dispatched behavior.
10005   DECLARE_PRINTER(JSSet)
10006   DECLARE_VERIFIER(JSSet)
10007
10008  private:
10009   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10010 };
10011
10012
10013 // The JSMap describes EcmaScript Harmony maps
10014 class JSMap : public JSCollection {
10015  public:
10016   DECLARE_CAST(JSMap)
10017
10018   // Dispatched behavior.
10019   DECLARE_PRINTER(JSMap)
10020   DECLARE_VERIFIER(JSMap)
10021
10022  private:
10023   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10024 };
10025
10026
10027 // OrderedHashTableIterator is an iterator that iterates over the keys and
10028 // values of an OrderedHashTable.
10029 //
10030 // The iterator has a reference to the underlying OrderedHashTable data,
10031 // [table], as well as the current [index] the iterator is at.
10032 //
10033 // When the OrderedHashTable is rehashed it adds a reference from the old table
10034 // to the new table as well as storing enough data about the changes so that the
10035 // iterator [index] can be adjusted accordingly.
10036 //
10037 // When the [Next] result from the iterator is requested, the iterator checks if
10038 // there is a newer table that it needs to transition to.
10039 template<class Derived, class TableType>
10040 class OrderedHashTableIterator: public JSObject {
10041  public:
10042   // [table]: the backing hash table mapping keys to values.
10043   DECL_ACCESSORS(table, Object)
10044
10045   // [index]: The index into the data table.
10046   DECL_ACCESSORS(index, Object)
10047
10048   // [kind]: The kind of iteration this is. One of the [Kind] enum values.
10049   DECL_ACCESSORS(kind, Object)
10050
10051 #ifdef OBJECT_PRINT
10052   void OrderedHashTableIteratorPrint(OStream& os);  // NOLINT
10053 #endif
10054
10055   static const int kTableOffset = JSObject::kHeaderSize;
10056   static const int kIndexOffset = kTableOffset + kPointerSize;
10057   static const int kKindOffset = kIndexOffset + kPointerSize;
10058   static const int kSize = kKindOffset + kPointerSize;
10059
10060   enum Kind {
10061     kKindKeys = 1,
10062     kKindValues = 2,
10063     kKindEntries = 3
10064   };
10065
10066   // Whether the iterator has more elements. This needs to be called before
10067   // calling |CurrentKey| and/or |CurrentValue|.
10068   bool HasMore();
10069
10070   // Move the index forward one.
10071   void MoveNext() {
10072     set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
10073   }
10074
10075   // Populates the array with the next key and value and then moves the iterator
10076   // forward.
10077   // This returns the |kind| or 0 if the iterator is already at the end.
10078   Smi* Next(JSArray* value_array);
10079
10080   // Returns the current key of the iterator. This should only be called when
10081   // |HasMore| returns true.
10082   inline Object* CurrentKey();
10083
10084  private:
10085   // Transitions the iterator to the non obsolete backing store. This is a NOP
10086   // if the [table] is not obsolete.
10087   void Transition();
10088
10089   DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
10090 };
10091
10092
10093 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
10094                                                      OrderedHashSet> {
10095  public:
10096   // Dispatched behavior.
10097   DECLARE_PRINTER(JSSetIterator)
10098   DECLARE_VERIFIER(JSSetIterator)
10099
10100   DECLARE_CAST(JSSetIterator)
10101
10102   // Called by |Next| to populate the array. This allows the subclasses to
10103   // populate the array differently.
10104   inline void PopulateValueArray(FixedArray* array);
10105
10106  private:
10107   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
10108 };
10109
10110
10111 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
10112                                                      OrderedHashMap> {
10113  public:
10114   // Dispatched behavior.
10115   DECLARE_PRINTER(JSMapIterator)
10116   DECLARE_VERIFIER(JSMapIterator)
10117
10118   DECLARE_CAST(JSMapIterator)
10119
10120   // Called by |Next| to populate the array. This allows the subclasses to
10121   // populate the array differently.
10122   inline void PopulateValueArray(FixedArray* array);
10123
10124  private:
10125   // Returns the current value of the iterator. This should only be called when
10126   // |HasMore| returns true.
10127   inline Object* CurrentValue();
10128
10129   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
10130 };
10131
10132
10133 // Base class for both JSWeakMap and JSWeakSet
10134 class JSWeakCollection: public JSObject {
10135  public:
10136   // [table]: the backing hash table mapping keys to values.
10137   DECL_ACCESSORS(table, Object)
10138
10139   // [next]: linked list of encountered weak maps during GC.
10140   DECL_ACCESSORS(next, Object)
10141
10142   static const int kTableOffset = JSObject::kHeaderSize;
10143   static const int kNextOffset = kTableOffset + kPointerSize;
10144   static const int kSize = kNextOffset + kPointerSize;
10145
10146  private:
10147   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10148 };
10149
10150
10151 // The JSWeakMap describes EcmaScript Harmony weak maps
10152 class JSWeakMap: public JSWeakCollection {
10153  public:
10154   DECLARE_CAST(JSWeakMap)
10155
10156   // Dispatched behavior.
10157   DECLARE_PRINTER(JSWeakMap)
10158   DECLARE_VERIFIER(JSWeakMap)
10159
10160  private:
10161   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10162 };
10163
10164
10165 // The JSWeakSet describes EcmaScript Harmony weak sets
10166 class JSWeakSet: public JSWeakCollection {
10167  public:
10168   DECLARE_CAST(JSWeakSet)
10169
10170   // Dispatched behavior.
10171   DECLARE_PRINTER(JSWeakSet)
10172   DECLARE_VERIFIER(JSWeakSet)
10173
10174  private:
10175   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10176 };
10177
10178
10179 class JSArrayBuffer: public JSObject {
10180  public:
10181   // [backing_store]: backing memory for this array
10182   DECL_ACCESSORS(backing_store, void)
10183
10184   // [byte_length]: length in bytes
10185   DECL_ACCESSORS(byte_length, Object)
10186
10187   // [flags]
10188   DECL_ACCESSORS(flag, Smi)
10189
10190   inline bool is_external();
10191   inline void set_is_external(bool value);
10192
10193   inline bool should_be_freed();
10194   inline void set_should_be_freed(bool value);
10195
10196   // [weak_next]: linked list of array buffers.
10197   DECL_ACCESSORS(weak_next, Object)
10198
10199   // [weak_first_array]: weak linked list of views.
10200   DECL_ACCESSORS(weak_first_view, Object)
10201
10202   DECLARE_CAST(JSArrayBuffer)
10203
10204   // Neutering. Only neuters the buffer, not associated typed arrays.
10205   void Neuter();
10206
10207   // Dispatched behavior.
10208   DECLARE_PRINTER(JSArrayBuffer)
10209   DECLARE_VERIFIER(JSArrayBuffer)
10210
10211   static const int kBackingStoreOffset = JSObject::kHeaderSize;
10212   static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10213   static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10214   static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10215   static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10216   static const int kSize = kWeakFirstViewOffset + kPointerSize;
10217
10218   static const int kSizeWithInternalFields =
10219       kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10220
10221  private:
10222   // Bit position in a flag
10223   static const int kIsExternalBit = 0;
10224   static const int kShouldBeFreed = 1;
10225
10226   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10227 };
10228
10229
10230 class JSArrayBufferView: public JSObject {
10231  public:
10232   // [buffer]: ArrayBuffer that this typed array views.
10233   DECL_ACCESSORS(buffer, Object)
10234
10235   // [byte_length]: offset of typed array in bytes.
10236   DECL_ACCESSORS(byte_offset, Object)
10237
10238   // [byte_length]: length of typed array in bytes.
10239   DECL_ACCESSORS(byte_length, Object)
10240
10241   // [weak_next]: linked list of typed arrays over the same array buffer.
10242   DECL_ACCESSORS(weak_next, Object)
10243
10244   DECLARE_CAST(JSArrayBufferView)
10245
10246   DECLARE_VERIFIER(JSArrayBufferView)
10247
10248   static const int kBufferOffset = JSObject::kHeaderSize;
10249   static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10250   static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10251   static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10252   static const int kViewSize = kWeakNextOffset + kPointerSize;
10253
10254  protected:
10255   void NeuterView();
10256
10257  private:
10258   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10259 };
10260
10261
10262 class JSTypedArray: public JSArrayBufferView {
10263  public:
10264   // [length]: length of typed array in elements.
10265   DECL_ACCESSORS(length, Object)
10266
10267   // Neutering. Only neuters this typed array.
10268   void Neuter();
10269
10270   DECLARE_CAST(JSTypedArray)
10271
10272   ExternalArrayType type();
10273   size_t element_size();
10274
10275   Handle<JSArrayBuffer> GetBuffer();
10276
10277   // Dispatched behavior.
10278   DECLARE_PRINTER(JSTypedArray)
10279   DECLARE_VERIFIER(JSTypedArray)
10280
10281   static const int kLengthOffset = kViewSize + kPointerSize;
10282   static const int kSize = kLengthOffset + kPointerSize;
10283
10284   static const int kSizeWithInternalFields =
10285       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10286
10287  private:
10288   static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10289       Handle<JSTypedArray> typed_array);
10290
10291   DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10292 };
10293
10294
10295 class JSDataView: public JSArrayBufferView {
10296  public:
10297   // Only neuters this DataView
10298   void Neuter();
10299
10300   DECLARE_CAST(JSDataView)
10301
10302   // Dispatched behavior.
10303   DECLARE_PRINTER(JSDataView)
10304   DECLARE_VERIFIER(JSDataView)
10305
10306   static const int kSize = kViewSize;
10307
10308   static const int kSizeWithInternalFields =
10309       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10310
10311  private:
10312   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10313 };
10314
10315
10316 class Float32x4: public JSObject {
10317  public:
10318   typedef float32x4_value_t value_t;
10319   static const int kValueSize = kFloat32x4Size;
10320   static const InstanceType kInstanceType = FLOAT32x4_TYPE;
10321   static inline const char* Name();
10322   static inline int kRuntimeAllocatorId();
10323
10324   // [value]: the FixedFloat32x4Array with length 1.
10325   DECL_ACCESSORS(value, Object)
10326
10327   // Casting.
10328   DECLARE_CAST(Float32x4)
10329
10330   // Dispatched behavior.
10331   void Float32x4Print(OStream& os);
10332   DECLARE_VERIFIER(Float32x4)
10333
10334   // Helpers.
10335   static const int kLanes = 4;
10336   inline float getAt(int index);
10337   inline float x() { return getAt(0); }
10338   inline float y() { return getAt(1); }
10339   inline float z() { return getAt(2); }
10340   inline float w() { return getAt(3); }
10341   inline float32x4_value_t get();
10342   inline void set(float32x4_value_t f32x4);
10343
10344   // Layout description.
10345   static const int kValueOffset = JSObject::kHeaderSize;
10346   static const int kSize = kValueOffset + kPointerSize;
10347
10348  private:
10349   DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
10350 };
10351
10352
10353 class Float64x2: public JSObject {
10354  public:
10355   typedef float64x2_value_t value_t;
10356   static const int kValueSize = kFloat64x2Size;
10357   static const InstanceType kInstanceType = FLOAT64x2_TYPE;
10358   static inline const char* Name();
10359   static inline int kRuntimeAllocatorId();
10360
10361   // [value]: the FixedFloat64x2Array with length 1.
10362   DECL_ACCESSORS(value, Object)
10363
10364   // Casting.
10365   DECLARE_CAST(Float64x2)
10366
10367   // Dispatched behavior.
10368   void Float64x2Print(OStream& os);
10369   DECLARE_VERIFIER(Float64x2)
10370
10371   // Helpers.
10372   static const int kLanes = 2;
10373   inline double getAt(int index);
10374   inline double x() { return getAt(0); }
10375   inline double y() { return getAt(1); }
10376   inline float64x2_value_t get();
10377   inline void set(float64x2_value_t f64x2);
10378
10379   // Layout description.
10380   static const int kValueOffset = JSObject::kHeaderSize;
10381   static const int kSize = kValueOffset + kPointerSize;
10382
10383  private:
10384   DISALLOW_IMPLICIT_CONSTRUCTORS(Float64x2);
10385 };
10386
10387
10388 class Int32x4: public JSObject {
10389  public:
10390   typedef int32x4_value_t value_t;
10391   static const int kValueSize = kInt32x4Size;
10392   static const InstanceType kInstanceType = INT32x4_TYPE;
10393   static inline const char* Name();
10394   static inline int kRuntimeAllocatorId();
10395
10396   // [value]: the FixedInt32x4Array with length 1.
10397   DECL_ACCESSORS(value, Object)
10398
10399   // Casting.
10400   DECLARE_CAST(Int32x4)
10401
10402   // Dispatched behavior.
10403   void Int32x4Print(OStream& os);
10404   DECLARE_VERIFIER(Int32x4)
10405
10406   // Helpers.
10407   static const int kLanes = 4;
10408   inline int32_t getAt(int32_t index);
10409   inline int32_t x() { return getAt(0); }
10410   inline int32_t y() { return getAt(1); }
10411   inline int32_t z() { return getAt(2); }
10412   inline int32_t w() { return getAt(3); }
10413   inline int32x4_value_t get();
10414   inline void set(int32x4_value_t i32x4);
10415
10416   // Layout description.
10417   static const int kValueOffset = JSObject::kHeaderSize;
10418   static const int kSize = kValueOffset + kPointerSize;
10419
10420  private:
10421   DISALLOW_IMPLICIT_CONSTRUCTORS(Int32x4);
10422 };
10423
10424
10425 // Foreign describes objects pointing from JavaScript to C structures.
10426 // Since they cannot contain references to JS HeapObjects they can be
10427 // placed in old_data_space.
10428 class Foreign: public HeapObject {
10429  public:
10430   // [address]: field containing the address.
10431   inline Address foreign_address();
10432   inline void set_foreign_address(Address value);
10433
10434   DECLARE_CAST(Foreign)
10435
10436   // Dispatched behavior.
10437   inline void ForeignIterateBody(ObjectVisitor* v);
10438
10439   template<typename StaticVisitor>
10440   inline void ForeignIterateBody();
10441
10442   // Dispatched behavior.
10443   DECLARE_PRINTER(Foreign)
10444   DECLARE_VERIFIER(Foreign)
10445
10446   // Layout description.
10447
10448   static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10449   static const int kSize = kForeignAddressOffset + kPointerSize;
10450
10451   STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10452
10453  private:
10454   DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10455 };
10456
10457
10458 // The JSArray describes JavaScript Arrays
10459 //  Such an array can be in one of two modes:
10460 //    - fast, backing storage is a FixedArray and length <= elements.length();
10461 //       Please note: push and pop can be used to grow and shrink the array.
10462 //    - slow, backing storage is a HashTable with numbers as keys.
10463 class JSArray: public JSObject {
10464  public:
10465   // [length]: The length property.
10466   DECL_ACCESSORS(length, Object)
10467
10468   // Overload the length setter to skip write barrier when the length
10469   // is set to a smi. This matches the set function on FixedArray.
10470   inline void set_length(Smi* length);
10471
10472   static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10473                                            uint32_t index,
10474                                            Handle<Object> value);
10475
10476   static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
10477   static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10478   static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10479
10480   // Initialize the array with the given capacity. The function may
10481   // fail due to out-of-memory situations, but only if the requested
10482   // capacity is non-zero.
10483   static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10484
10485   // Initializes the array to a certain length.
10486   inline bool AllowsSetElementsLength();
10487   // Can cause GC.
10488   MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10489       Handle<JSArray> array,
10490       Handle<Object> length);
10491
10492   // Set the content of the array to the content of storage.
10493   static inline void SetContent(Handle<JSArray> array,
10494                                 Handle<FixedArrayBase> storage);
10495
10496   DECLARE_CAST(JSArray)
10497
10498   // Ensures that the fixed array backing the JSArray has at
10499   // least the stated size.
10500   static inline void EnsureSize(Handle<JSArray> array,
10501                                 int minimum_size_of_backing_fixed_array);
10502
10503   // Expand the fixed array backing of a fast-case JSArray to at least
10504   // the requested size.
10505   static void Expand(Handle<JSArray> array,
10506                      int minimum_size_of_backing_fixed_array);
10507
10508   // Dispatched behavior.
10509   DECLARE_PRINTER(JSArray)
10510   DECLARE_VERIFIER(JSArray)
10511
10512   // Number of element slots to pre-allocate for an empty array.
10513   static const int kPreallocatedArrayElements = 4;
10514
10515   // Layout description.
10516   static const int kLengthOffset = JSObject::kHeaderSize;
10517   static const int kSize = kLengthOffset + kPointerSize;
10518
10519  private:
10520   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10521 };
10522
10523
10524 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10525                                        Handle<Map> initial_map);
10526
10527
10528 // JSRegExpResult is just a JSArray with a specific initial map.
10529 // This initial map adds in-object properties for "index" and "input"
10530 // properties, as assigned by RegExp.prototype.exec, which allows
10531 // faster creation of RegExp exec results.
10532 // This class just holds constants used when creating the result.
10533 // After creation the result must be treated as a JSArray in all regards.
10534 class JSRegExpResult: public JSArray {
10535  public:
10536   // Offsets of object fields.
10537   static const int kIndexOffset = JSArray::kSize;
10538   static const int kInputOffset = kIndexOffset + kPointerSize;
10539   static const int kSize = kInputOffset + kPointerSize;
10540   // Indices of in-object properties.
10541   static const int kIndexIndex = 0;
10542   static const int kInputIndex = 1;
10543  private:
10544   DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10545 };
10546
10547
10548 class AccessorInfo: public Struct {
10549  public:
10550   DECL_ACCESSORS(name, Object)
10551   DECL_ACCESSORS(flag, Smi)
10552   DECL_ACCESSORS(expected_receiver_type, Object)
10553
10554   inline bool all_can_read();
10555   inline void set_all_can_read(bool value);
10556
10557   inline bool all_can_write();
10558   inline void set_all_can_write(bool value);
10559
10560   inline PropertyAttributes property_attributes();
10561   inline void set_property_attributes(PropertyAttributes attributes);
10562
10563   // Checks whether the given receiver is compatible with this accessor.
10564   static bool IsCompatibleReceiverType(Isolate* isolate,
10565                                        Handle<AccessorInfo> info,
10566                                        Handle<HeapType> type);
10567   inline bool IsCompatibleReceiver(Object* receiver);
10568
10569   DECLARE_CAST(AccessorInfo)
10570
10571   // Dispatched behavior.
10572   DECLARE_VERIFIER(AccessorInfo)
10573
10574   // Append all descriptors to the array that are not already there.
10575   // Return number added.
10576   static int AppendUnique(Handle<Object> descriptors,
10577                           Handle<FixedArray> array,
10578                           int valid_descriptors);
10579
10580   static const int kNameOffset = HeapObject::kHeaderSize;
10581   static const int kFlagOffset = kNameOffset + kPointerSize;
10582   static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10583   static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10584
10585  private:
10586   inline bool HasExpectedReceiverType() {
10587     return expected_receiver_type()->IsFunctionTemplateInfo();
10588   }
10589   // Bit positions in flag.
10590   static const int kAllCanReadBit = 0;
10591   static const int kAllCanWriteBit = 1;
10592   class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10593
10594   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10595 };
10596
10597
10598 enum AccessorDescriptorType {
10599   kDescriptorBitmaskCompare,
10600   kDescriptorPointerCompare,
10601   kDescriptorPrimitiveValue,
10602   kDescriptorObjectDereference,
10603   kDescriptorPointerDereference,
10604   kDescriptorPointerShift,
10605   kDescriptorReturnObject
10606 };
10607
10608
10609 struct BitmaskCompareDescriptor {
10610   uint32_t bitmask;
10611   uint32_t compare_value;
10612   uint8_t size;  // Must be in {1,2,4}.
10613 };
10614
10615
10616 struct PointerCompareDescriptor {
10617   void* compare_value;
10618 };
10619
10620
10621 struct PrimitiveValueDescriptor {
10622   v8::DeclaredAccessorDescriptorDataType data_type;
10623   uint8_t bool_offset;  // Must be in [0,7], used for kDescriptorBoolType.
10624 };
10625
10626
10627 struct ObjectDerefenceDescriptor {
10628   uint8_t internal_field;
10629 };
10630
10631
10632 struct PointerShiftDescriptor {
10633   int16_t byte_offset;
10634 };
10635
10636
10637 struct DeclaredAccessorDescriptorData {
10638   AccessorDescriptorType type;
10639   union {
10640     struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10641     struct PointerCompareDescriptor pointer_compare_descriptor;
10642     struct PrimitiveValueDescriptor primitive_value_descriptor;
10643     struct ObjectDerefenceDescriptor object_dereference_descriptor;
10644     struct PointerShiftDescriptor pointer_shift_descriptor;
10645   };
10646 };
10647
10648
10649 class DeclaredAccessorDescriptor;
10650
10651
10652 class DeclaredAccessorDescriptorIterator {
10653  public:
10654   explicit DeclaredAccessorDescriptorIterator(
10655       DeclaredAccessorDescriptor* descriptor);
10656   const DeclaredAccessorDescriptorData* Next();
10657   bool Complete() const { return length_ == offset_; }
10658  private:
10659   uint8_t* array_;
10660   const int length_;
10661   int offset_;
10662   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10663 };
10664
10665
10666 class DeclaredAccessorDescriptor: public Struct {
10667  public:
10668   DECL_ACCESSORS(serialized_data, ByteArray)
10669
10670   DECLARE_CAST(DeclaredAccessorDescriptor)
10671
10672   static Handle<DeclaredAccessorDescriptor> Create(
10673       Isolate* isolate,
10674       const DeclaredAccessorDescriptorData& data,
10675       Handle<DeclaredAccessorDescriptor> previous);
10676
10677   // Dispatched behavior.
10678   DECLARE_PRINTER(DeclaredAccessorDescriptor)
10679   DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10680
10681   static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10682   static const int kSize = kSerializedDataOffset + kPointerSize;
10683
10684  private:
10685   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10686 };
10687
10688
10689 class DeclaredAccessorInfo: public AccessorInfo {
10690  public:
10691   DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10692
10693   DECLARE_CAST(DeclaredAccessorInfo)
10694
10695   // Dispatched behavior.
10696   DECLARE_PRINTER(DeclaredAccessorInfo)
10697   DECLARE_VERIFIER(DeclaredAccessorInfo)
10698
10699   static const int kDescriptorOffset = AccessorInfo::kSize;
10700   static const int kSize = kDescriptorOffset + kPointerSize;
10701
10702  private:
10703   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10704 };
10705
10706
10707 // An accessor must have a getter, but can have no setter.
10708 //
10709 // When setting a property, V8 searches accessors in prototypes.
10710 // If an accessor was found and it does not have a setter,
10711 // the request is ignored.
10712 //
10713 // If the accessor in the prototype has the READ_ONLY property attribute, then
10714 // a new value is added to the derived object when the property is set.
10715 // This shadows the accessor in the prototype.
10716 class ExecutableAccessorInfo: public AccessorInfo {
10717  public:
10718   DECL_ACCESSORS(getter, Object)
10719   DECL_ACCESSORS(setter, Object)
10720   DECL_ACCESSORS(data, Object)
10721
10722   DECLARE_CAST(ExecutableAccessorInfo)
10723
10724   // Dispatched behavior.
10725   DECLARE_PRINTER(ExecutableAccessorInfo)
10726   DECLARE_VERIFIER(ExecutableAccessorInfo)
10727
10728   static const int kGetterOffset = AccessorInfo::kSize;
10729   static const int kSetterOffset = kGetterOffset + kPointerSize;
10730   static const int kDataOffset = kSetterOffset + kPointerSize;
10731   static const int kSize = kDataOffset + kPointerSize;
10732
10733   inline void clear_setter();
10734
10735  private:
10736   DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10737 };
10738
10739
10740 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10741 // accessor can either be
10742 //   * a pointer to a JavaScript function or proxy: a real accessor
10743 //   * undefined: considered an accessor by the spec, too, strangely enough
10744 //   * the hole: an accessor which has not been set
10745 //   * a pointer to a map: a transition used to ensure map sharing
10746 class AccessorPair: public Struct {
10747  public:
10748   DECL_ACCESSORS(getter, Object)
10749   DECL_ACCESSORS(setter, Object)
10750
10751   DECLARE_CAST(AccessorPair)
10752
10753   static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10754
10755   Object* get(AccessorComponent component) {
10756     return component == ACCESSOR_GETTER ? getter() : setter();
10757   }
10758
10759   void set(AccessorComponent component, Object* value) {
10760     if (component == ACCESSOR_GETTER) {
10761       set_getter(value);
10762     } else {
10763       set_setter(value);
10764     }
10765   }
10766
10767   // Note: Returns undefined instead in case of a hole.
10768   Object* GetComponent(AccessorComponent component);
10769
10770   // Set both components, skipping arguments which are a JavaScript null.
10771   void SetComponents(Object* getter, Object* setter) {
10772     if (!getter->IsNull()) set_getter(getter);
10773     if (!setter->IsNull()) set_setter(setter);
10774   }
10775
10776   bool ContainsAccessor() {
10777     return IsJSAccessor(getter()) || IsJSAccessor(setter());
10778   }
10779
10780   // Dispatched behavior.
10781   DECLARE_PRINTER(AccessorPair)
10782   DECLARE_VERIFIER(AccessorPair)
10783
10784   static const int kGetterOffset = HeapObject::kHeaderSize;
10785   static const int kSetterOffset = kGetterOffset + kPointerSize;
10786   static const int kSize = kSetterOffset + kPointerSize;
10787
10788  private:
10789   // Strangely enough, in addition to functions and harmony proxies, the spec
10790   // requires us to consider undefined as a kind of accessor, too:
10791   //    var obj = {};
10792   //    Object.defineProperty(obj, "foo", {get: undefined});
10793   //    assertTrue("foo" in obj);
10794   bool IsJSAccessor(Object* obj) {
10795     return obj->IsSpecFunction() || obj->IsUndefined();
10796   }
10797
10798   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10799 };
10800
10801
10802 class AccessCheckInfo: public Struct {
10803  public:
10804   DECL_ACCESSORS(named_callback, Object)
10805   DECL_ACCESSORS(indexed_callback, Object)
10806   DECL_ACCESSORS(data, Object)
10807
10808   DECLARE_CAST(AccessCheckInfo)
10809
10810   // Dispatched behavior.
10811   DECLARE_PRINTER(AccessCheckInfo)
10812   DECLARE_VERIFIER(AccessCheckInfo)
10813
10814   static const int kNamedCallbackOffset   = HeapObject::kHeaderSize;
10815   static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10816   static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10817   static const int kSize = kDataOffset + kPointerSize;
10818
10819  private:
10820   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10821 };
10822
10823
10824 class InterceptorInfo: public Struct {
10825  public:
10826   DECL_ACCESSORS(getter, Object)
10827   DECL_ACCESSORS(setter, Object)
10828   DECL_ACCESSORS(query, Object)
10829   DECL_ACCESSORS(deleter, Object)
10830   DECL_ACCESSORS(enumerator, Object)
10831   DECL_ACCESSORS(data, Object)
10832
10833   DECLARE_CAST(InterceptorInfo)
10834
10835   // Dispatched behavior.
10836   DECLARE_PRINTER(InterceptorInfo)
10837   DECLARE_VERIFIER(InterceptorInfo)
10838
10839   static const int kGetterOffset = HeapObject::kHeaderSize;
10840   static const int kSetterOffset = kGetterOffset + kPointerSize;
10841   static const int kQueryOffset = kSetterOffset + kPointerSize;
10842   static const int kDeleterOffset = kQueryOffset + kPointerSize;
10843   static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10844   static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10845   static const int kSize = kDataOffset + kPointerSize;
10846
10847  private:
10848   DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10849 };
10850
10851
10852 class CallHandlerInfo: public Struct {
10853  public:
10854   DECL_ACCESSORS(callback, Object)
10855   DECL_ACCESSORS(data, Object)
10856
10857   DECLARE_CAST(CallHandlerInfo)
10858
10859   // Dispatched behavior.
10860   DECLARE_PRINTER(CallHandlerInfo)
10861   DECLARE_VERIFIER(CallHandlerInfo)
10862
10863   static const int kCallbackOffset = HeapObject::kHeaderSize;
10864   static const int kDataOffset = kCallbackOffset + kPointerSize;
10865   static const int kSize = kDataOffset + kPointerSize;
10866
10867  private:
10868   DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10869 };
10870
10871
10872 class TemplateInfo: public Struct {
10873  public:
10874   DECL_ACCESSORS(tag, Object)
10875   DECL_ACCESSORS(property_list, Object)
10876   DECL_ACCESSORS(property_accessors, Object)
10877
10878   DECLARE_VERIFIER(TemplateInfo)
10879
10880   static const int kTagOffset = HeapObject::kHeaderSize;
10881   static const int kPropertyListOffset = kTagOffset + kPointerSize;
10882   static const int kPropertyAccessorsOffset =
10883       kPropertyListOffset + kPointerSize;
10884   static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10885
10886  private:
10887   DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10888 };
10889
10890
10891 class FunctionTemplateInfo: public TemplateInfo {
10892  public:
10893   DECL_ACCESSORS(serial_number, Object)
10894   DECL_ACCESSORS(call_code, Object)
10895   DECL_ACCESSORS(prototype_template, Object)
10896   DECL_ACCESSORS(parent_template, Object)
10897   DECL_ACCESSORS(named_property_handler, Object)
10898   DECL_ACCESSORS(indexed_property_handler, Object)
10899   DECL_ACCESSORS(instance_template, Object)
10900   DECL_ACCESSORS(class_name, Object)
10901   DECL_ACCESSORS(signature, Object)
10902   DECL_ACCESSORS(instance_call_handler, Object)
10903   DECL_ACCESSORS(access_check_info, Object)
10904   DECL_ACCESSORS(flag, Smi)
10905
10906   inline int length() const;
10907   inline void set_length(int value);
10908
10909   // Following properties use flag bits.
10910   DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10911   DECL_BOOLEAN_ACCESSORS(undetectable)
10912   // If the bit is set, object instances created by this function
10913   // requires access check.
10914   DECL_BOOLEAN_ACCESSORS(needs_access_check)
10915   DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10916   DECL_BOOLEAN_ACCESSORS(remove_prototype)
10917   DECL_BOOLEAN_ACCESSORS(do_not_cache)
10918
10919   DECLARE_CAST(FunctionTemplateInfo)
10920
10921   // Dispatched behavior.
10922   DECLARE_PRINTER(FunctionTemplateInfo)
10923   DECLARE_VERIFIER(FunctionTemplateInfo)
10924
10925   static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10926   static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10927   static const int kPrototypeTemplateOffset =
10928       kCallCodeOffset + kPointerSize;
10929   static const int kParentTemplateOffset =
10930       kPrototypeTemplateOffset + kPointerSize;
10931   static const int kNamedPropertyHandlerOffset =
10932       kParentTemplateOffset + kPointerSize;
10933   static const int kIndexedPropertyHandlerOffset =
10934       kNamedPropertyHandlerOffset + kPointerSize;
10935   static const int kInstanceTemplateOffset =
10936       kIndexedPropertyHandlerOffset + kPointerSize;
10937   static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10938   static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10939   static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10940   static const int kAccessCheckInfoOffset =
10941       kInstanceCallHandlerOffset + kPointerSize;
10942   static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10943   static const int kLengthOffset = kFlagOffset + kPointerSize;
10944   static const int kSize = kLengthOffset + kPointerSize;
10945
10946   // Returns true if |object| is an instance of this function template.
10947   bool IsTemplateFor(Object* object);
10948   bool IsTemplateFor(Map* map);
10949
10950  private:
10951   // Bit position in the flag, from least significant bit position.
10952   static const int kHiddenPrototypeBit   = 0;
10953   static const int kUndetectableBit      = 1;
10954   static const int kNeedsAccessCheckBit  = 2;
10955   static const int kReadOnlyPrototypeBit = 3;
10956   static const int kRemovePrototypeBit   = 4;
10957   static const int kDoNotCacheBit        = 5;
10958
10959   DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10960 };
10961
10962
10963 class ObjectTemplateInfo: public TemplateInfo {
10964  public:
10965   DECL_ACCESSORS(constructor, Object)
10966   DECL_ACCESSORS(internal_field_count, Object)
10967
10968   DECLARE_CAST(ObjectTemplateInfo)
10969
10970   // Dispatched behavior.
10971   DECLARE_PRINTER(ObjectTemplateInfo)
10972   DECLARE_VERIFIER(ObjectTemplateInfo)
10973
10974   static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10975   static const int kInternalFieldCountOffset =
10976       kConstructorOffset + kPointerSize;
10977   static const int kSize = kInternalFieldCountOffset + kPointerSize;
10978 };
10979
10980
10981 class SignatureInfo: public Struct {
10982  public:
10983   DECL_ACCESSORS(receiver, Object)
10984   DECL_ACCESSORS(args, Object)
10985
10986   DECLARE_CAST(SignatureInfo)
10987
10988   // Dispatched behavior.
10989   DECLARE_PRINTER(SignatureInfo)
10990   DECLARE_VERIFIER(SignatureInfo)
10991
10992   static const int kReceiverOffset = Struct::kHeaderSize;
10993   static const int kArgsOffset     = kReceiverOffset + kPointerSize;
10994   static const int kSize           = kArgsOffset + kPointerSize;
10995
10996  private:
10997   DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10998 };
10999
11000
11001 class TypeSwitchInfo: public Struct {
11002  public:
11003   DECL_ACCESSORS(types, Object)
11004
11005   DECLARE_CAST(TypeSwitchInfo)
11006
11007   // Dispatched behavior.
11008   DECLARE_PRINTER(TypeSwitchInfo)
11009   DECLARE_VERIFIER(TypeSwitchInfo)
11010
11011   static const int kTypesOffset = Struct::kHeaderSize;
11012   static const int kSize        = kTypesOffset + kPointerSize;
11013 };
11014
11015
11016 // The DebugInfo class holds additional information for a function being
11017 // debugged.
11018 class DebugInfo: public Struct {
11019  public:
11020   // The shared function info for the source being debugged.
11021   DECL_ACCESSORS(shared, SharedFunctionInfo)
11022   // Code object for the original code.
11023   DECL_ACCESSORS(original_code, Code)
11024   // Code object for the patched code. This code object is the code object
11025   // currently active for the function.
11026   DECL_ACCESSORS(code, Code)
11027   // Fixed array holding status information for each active break point.
11028   DECL_ACCESSORS(break_points, FixedArray)
11029
11030   // Check if there is a break point at a code position.
11031   bool HasBreakPoint(int code_position);
11032   // Get the break point info object for a code position.
11033   Object* GetBreakPointInfo(int code_position);
11034   // Clear a break point.
11035   static void ClearBreakPoint(Handle<DebugInfo> debug_info,
11036                               int code_position,
11037                               Handle<Object> break_point_object);
11038   // Set a break point.
11039   static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
11040                             int source_position, int statement_position,
11041                             Handle<Object> break_point_object);
11042   // Get the break point objects for a code position.
11043   Object* GetBreakPointObjects(int code_position);
11044   // Find the break point info holding this break point object.
11045   static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
11046                                     Handle<Object> break_point_object);
11047   // Get the number of break points for this function.
11048   int GetBreakPointCount();
11049
11050   DECLARE_CAST(DebugInfo)
11051
11052   // Dispatched behavior.
11053   DECLARE_PRINTER(DebugInfo)
11054   DECLARE_VERIFIER(DebugInfo)
11055
11056   static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
11057   static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
11058   static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
11059   static const int kActiveBreakPointsCountIndex =
11060       kPatchedCodeIndex + kPointerSize;
11061   static const int kBreakPointsStateIndex =
11062       kActiveBreakPointsCountIndex + kPointerSize;
11063   static const int kSize = kBreakPointsStateIndex + kPointerSize;
11064
11065   static const int kEstimatedNofBreakPointsInFunction = 16;
11066
11067  private:
11068   static const int kNoBreakPointInfo = -1;
11069
11070   // Lookup the index in the break_points array for a code position.
11071   int GetBreakPointInfoIndex(int code_position);
11072
11073   DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
11074 };
11075
11076
11077 // The BreakPointInfo class holds information for break points set in a
11078 // function. The DebugInfo object holds a BreakPointInfo object for each code
11079 // position with one or more break points.
11080 class BreakPointInfo: public Struct {
11081  public:
11082   // The position in the code for the break point.
11083   DECL_ACCESSORS(code_position, Smi)
11084   // The position in the source for the break position.
11085   DECL_ACCESSORS(source_position, Smi)
11086   // The position in the source for the last statement before this break
11087   // position.
11088   DECL_ACCESSORS(statement_position, Smi)
11089   // List of related JavaScript break points.
11090   DECL_ACCESSORS(break_point_objects, Object)
11091
11092   // Removes a break point.
11093   static void ClearBreakPoint(Handle<BreakPointInfo> info,
11094                               Handle<Object> break_point_object);
11095   // Set a break point.
11096   static void SetBreakPoint(Handle<BreakPointInfo> info,
11097                             Handle<Object> break_point_object);
11098   // Check if break point info has this break point object.
11099   static bool HasBreakPointObject(Handle<BreakPointInfo> info,
11100                                   Handle<Object> break_point_object);
11101   // Get the number of break points for this code position.
11102   int GetBreakPointCount();
11103
11104   DECLARE_CAST(BreakPointInfo)
11105
11106   // Dispatched behavior.
11107   DECLARE_PRINTER(BreakPointInfo)
11108   DECLARE_VERIFIER(BreakPointInfo)
11109
11110   static const int kCodePositionIndex = Struct::kHeaderSize;
11111   static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
11112   static const int kStatementPositionIndex =
11113       kSourcePositionIndex + kPointerSize;
11114   static const int kBreakPointObjectsIndex =
11115       kStatementPositionIndex + kPointerSize;
11116   static const int kSize = kBreakPointObjectsIndex + kPointerSize;
11117
11118  private:
11119   DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
11120 };
11121
11122
11123 #undef DECL_BOOLEAN_ACCESSORS
11124 #undef DECL_ACCESSORS
11125 #undef DECLARE_CAST
11126 #undef DECLARE_VERIFIER
11127
11128 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V)                            \
11129   V(kStringTable, "string_table", "(Internalized strings)")             \
11130   V(kExternalStringsTable, "external_strings_table", "(External strings)") \
11131   V(kStrongRootList, "strong_root_list", "(Strong roots)")              \
11132   V(kSmiRootList, "smi_root_list", "(Smi roots)")                       \
11133   V(kInternalizedString, "internalized_string", "(Internal string)")    \
11134   V(kBootstrapper, "bootstrapper", "(Bootstrapper)")                    \
11135   V(kTop, "top", "(Isolate)")                                           \
11136   V(kRelocatable, "relocatable", "(Relocatable)")                       \
11137   V(kDebug, "debug", "(Debugger)")                                      \
11138   V(kCompilationCache, "compilationcache", "(Compilation cache)")       \
11139   V(kHandleScope, "handlescope", "(Handle scope)")                      \
11140   V(kBuiltins, "builtins", "(Builtins)")                                \
11141   V(kGlobalHandles, "globalhandles", "(Global handles)")                \
11142   V(kEternalHandles, "eternalhandles", "(Eternal handles)")             \
11143   V(kThreadManager, "threadmanager", "(Thread manager)")                \
11144   V(kExtensions, "Extensions", "(Extensions)")
11145
11146 class VisitorSynchronization : public AllStatic {
11147  public:
11148 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
11149   enum SyncTag {
11150     VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
11151     kNumberOfSyncTags
11152   };
11153 #undef DECLARE_ENUM
11154
11155   static const char* const kTags[kNumberOfSyncTags];
11156   static const char* const kTagNames[kNumberOfSyncTags];
11157 };
11158
11159 // Abstract base class for visiting, and optionally modifying, the
11160 // pointers contained in Objects. Used in GC and serialization/deserialization.
11161 class ObjectVisitor BASE_EMBEDDED {
11162  public:
11163   virtual ~ObjectVisitor() {}
11164
11165   // Visits a contiguous arrays of pointers in the half-open range
11166   // [start, end). Any or all of the values may be modified on return.
11167   virtual void VisitPointers(Object** start, Object** end) = 0;
11168
11169   // Handy shorthand for visiting a single pointer.
11170   virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
11171
11172   // Visit weak next_code_link in Code object.
11173   virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
11174
11175   // To allow lazy clearing of inline caches the visitor has
11176   // a rich interface for iterating over Code objects..
11177
11178   // Visits a code target in the instruction stream.
11179   virtual void VisitCodeTarget(RelocInfo* rinfo);
11180
11181   // Visits a code entry in a JS function.
11182   virtual void VisitCodeEntry(Address entry_address);
11183
11184   // Visits a global property cell reference in the instruction stream.
11185   virtual void VisitCell(RelocInfo* rinfo);
11186
11187   // Visits a runtime entry in the instruction stream.
11188   virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
11189
11190   // Visits the resource of an one-byte or two-byte string.
11191   virtual void VisitExternalOneByteString(
11192       v8::String::ExternalOneByteStringResource** resource) {}
11193   virtual void VisitExternalTwoByteString(
11194       v8::String::ExternalStringResource** resource) {}
11195
11196   // Visits a debug call target in the instruction stream.
11197   virtual void VisitDebugTarget(RelocInfo* rinfo);
11198
11199   // Visits the byte sequence in a function's prologue that contains information
11200   // about the code's age.
11201   virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11202
11203   // Visit pointer embedded into a code object.
11204   virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11205
11206   // Visits an external reference embedded into a code object.
11207   virtual void VisitExternalReference(RelocInfo* rinfo);
11208
11209   // Visits an external reference. The value may be modified on return.
11210   virtual void VisitExternalReference(Address* p) {}
11211
11212   // Visits a handle that has an embedder-assigned class ID.
11213   virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11214
11215   // Intended for serialization/deserialization checking: insert, or
11216   // check for the presence of, a tag at this position in the stream.
11217   // Also used for marking up GC roots in heap snapshots.
11218   virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11219 };
11220
11221
11222 class StructBodyDescriptor : public
11223   FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11224  public:
11225   static inline int SizeOf(Map* map, HeapObject* object) {
11226     return map->instance_size();
11227   }
11228 };
11229
11230
11231 // BooleanBit is a helper class for setting and getting a bit in an
11232 // integer or Smi.
11233 class BooleanBit : public AllStatic {
11234  public:
11235   static inline bool get(Smi* smi, int bit_position) {
11236     return get(smi->value(), bit_position);
11237   }
11238
11239   static inline bool get(int value, int bit_position) {
11240     return (value & (1 << bit_position)) != 0;
11241   }
11242
11243   static inline Smi* set(Smi* smi, int bit_position, bool v) {
11244     return Smi::FromInt(set(smi->value(), bit_position, v));
11245   }
11246
11247   static inline int set(int value, int bit_position, bool v) {
11248     if (v) {
11249       value |= (1 << bit_position);
11250     } else {
11251       value &= ~(1 << bit_position);
11252     }
11253     return value;
11254   }
11255 };
11256
11257 } }  // namespace v8::internal
11258
11259 #endif  // V8_OBJECTS_H_