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