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