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