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