1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "allocation.h"
32 #include "assert-scope.h"
34 #include "elements-kind.h"
37 #include "property-details.h"
38 #include "smart-pointers.h"
39 #include "unicode-inl.h"
40 #if V8_TARGET_ARCH_ARM64
41 #include "arm64/constants-arm64.h"
42 #elif V8_TARGET_ARCH_ARM
43 #include "arm/constants-arm.h"
44 #elif V8_TARGET_ARCH_MIPS
45 #include "mips/constants-mips.h"
52 // Most object types in the V8 JavaScript are described in this file.
54 // Inheritance hierarchy:
55 // - MaybeObject (an object or a failure)
56 // - Failure (immediate for marking failed operation)
58 // - Smi (immediate small integer)
59 // - HeapObject (superclass for everything allocated in the heap)
60 // - JSReceiver (suitable for property access)
64 // - JSArrayBufferView
74 // - JSGeneratorObject
92 // - CompilationCacheTable
93 // - CodeCacheHashTable
96 // - JSFunctionResultCache
101 // - ExternalUint8ClampedArray
102 // - ExternalInt8Array
103 // - ExternalUint8Array
104 // - ExternalInt16Array
105 // - ExternalUint16Array
106 // - ExternalInt32Array
107 // - ExternalUint32Array
108 // - ExternalFloat32Array
109 // - ExternalFloat32x4Array
110 // - ExternalInt32x4Array
114 // - SeqOneByteString
115 // - SeqTwoByteString
119 // - ExternalAsciiString
120 // - ExternalTwoByteString
121 // - InternalizedString
122 // - SeqInternalizedString
123 // - SeqOneByteInternalizedString
124 // - SeqTwoByteInternalizedString
125 // - ConsInternalizedString
126 // - ExternalInternalizedString
127 // - ExternalAsciiInternalizedString
128 // - ExternalTwoByteInternalizedString
139 // - SharedFunctionInfo
142 // - DeclaredAccessorDescriptor
144 // - DeclaredAccessorInfo
145 // - ExecutableAccessorInfo
151 // - FunctionTemplateInfo
152 // - ObjectTemplateInfo
160 // Formats of Object*:
161 // Smi: [31 bit signed int] 0
162 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
163 // Failure: [30 bit signed int] 11
168 enum KeyedAccessStoreMode {
170 STORE_TRANSITION_SMI_TO_OBJECT,
171 STORE_TRANSITION_SMI_TO_DOUBLE,
172 STORE_TRANSITION_DOUBLE_TO_OBJECT,
173 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
174 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
175 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
176 STORE_AND_GROW_NO_TRANSITION,
177 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
178 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
179 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
180 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
181 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
182 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
183 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
184 STORE_NO_TRANSITION_HANDLE_COW
188 enum ContextualMode {
194 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
196 STATIC_ASSERT(STANDARD_STORE == 0);
197 STATIC_ASSERT(kGrowICDelta ==
198 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
199 STORE_TRANSITION_SMI_TO_OBJECT);
200 STATIC_ASSERT(kGrowICDelta ==
201 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
202 STORE_TRANSITION_SMI_TO_DOUBLE);
203 STATIC_ASSERT(kGrowICDelta ==
204 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
205 STORE_TRANSITION_DOUBLE_TO_OBJECT);
208 static inline KeyedAccessStoreMode GetGrowStoreMode(
209 KeyedAccessStoreMode store_mode) {
210 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
211 store_mode = static_cast<KeyedAccessStoreMode>(
212 static_cast<int>(store_mode) + kGrowICDelta);
218 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
219 return store_mode > STANDARD_STORE &&
220 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
221 store_mode != STORE_AND_GROW_NO_TRANSITION;
225 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
226 KeyedAccessStoreMode store_mode) {
227 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
230 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
231 return STORE_AND_GROW_NO_TRANSITION;
233 return STANDARD_STORE;
237 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
238 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
239 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
243 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
244 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
247 // Indicates whether a value can be loaded as a constant.
254 // PropertyNormalizationMode is used to specify whether to keep
255 // inobject properties when normalizing properties of a JSObject.
256 enum PropertyNormalizationMode {
257 CLEAR_INOBJECT_PROPERTIES,
258 KEEP_INOBJECT_PROPERTIES
262 // NormalizedMapSharingMode is used to specify whether a map may be shared
263 // by different objects with normalized properties.
264 enum NormalizedMapSharingMode {
265 UNIQUE_NORMALIZED_MAP,
266 SHARED_NORMALIZED_MAP
270 // Indicates whether transitions can be added to a source map or not.
271 enum TransitionFlag {
277 enum DebugExtraICState {
279 DEBUG_PREPARE_STEP_IN
283 // Indicates whether the transition is simple: the target map of the transition
284 // either extends the current map with a new property, or it modifies the
285 // property that was added last to the current map.
286 enum SimpleTransitionFlag {
292 // Indicates whether we are only interested in the descriptors of a particular
293 // map, or in all descriptors in the descriptor array.
294 enum DescriptorFlag {
299 // The GC maintains a bit of information, the MarkingParity, which toggles
300 // from odd to even and back every time marking is completed. Incremental
301 // marking can visit an object twice during a marking phase, so algorithms that
302 // that piggy-back on marking can use the parity to ensure that they only
303 // perform an operation on an object once per marking phase: they record the
304 // MarkingParity when they visit an object, and only re-visit the object when it
305 // is marked again and the MarkingParity changes.
312 // ICs store extra state in a Code object. The default extra state is
314 typedef int ExtraICState;
315 static const ExtraICState kNoExtraICState = 0;
317 // Instance size sentinel for objects of variable size.
318 const int kVariableSizeSentinel = 0;
320 const int kStubMajorKeyBits = 7;
321 const int kStubMinorKeyBits = kBitsPerInt - kSmiTagSize - kStubMajorKeyBits;
323 // All Maps have a field instance_type containing a InstanceType.
324 // It describes the type of the instances.
326 // As an example, a JavaScript object is a heap object and its map
327 // instance_type is JS_OBJECT_TYPE.
329 // The names of the string instance types are intended to systematically
330 // mirror their encoding in the instance_type field of the map. The default
331 // encoding is considered TWO_BYTE. It is not mentioned in the name. ASCII
332 // encoding is mentioned explicitly in the name. Likewise, the default
333 // representation is considered sequential. It is not mentioned in the
334 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
335 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
336 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
338 // NOTE: The following things are some that depend on the string types having
339 // instance_types that are less than those of all other types:
340 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
343 // NOTE: Everything following JS_VALUE_TYPE is considered a
344 // JSObject for GC purposes. The first four entries here have typeof
345 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
346 #define INSTANCE_TYPE_LIST(V) \
348 V(ASCII_STRING_TYPE) \
349 V(CONS_STRING_TYPE) \
350 V(CONS_ASCII_STRING_TYPE) \
351 V(SLICED_STRING_TYPE) \
352 V(SLICED_ASCII_STRING_TYPE) \
353 V(EXTERNAL_STRING_TYPE) \
354 V(EXTERNAL_ASCII_STRING_TYPE) \
355 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
356 V(SHORT_EXTERNAL_STRING_TYPE) \
357 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
358 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
360 V(INTERNALIZED_STRING_TYPE) \
361 V(ASCII_INTERNALIZED_STRING_TYPE) \
362 V(CONS_INTERNALIZED_STRING_TYPE) \
363 V(CONS_ASCII_INTERNALIZED_STRING_TYPE) \
364 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
365 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
366 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
367 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
368 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
369 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
377 V(PROPERTY_CELL_TYPE) \
379 V(HEAP_NUMBER_TYPE) \
385 /* Note: the order of these external array */ \
386 /* types is relied upon in */ \
387 /* Object::IsExternalArray(). */ \
388 V(EXTERNAL_INT8_ARRAY_TYPE) \
389 V(EXTERNAL_UINT8_ARRAY_TYPE) \
390 V(EXTERNAL_INT16_ARRAY_TYPE) \
391 V(EXTERNAL_UINT16_ARRAY_TYPE) \
392 V(EXTERNAL_INT32_ARRAY_TYPE) \
393 V(EXTERNAL_UINT32_ARRAY_TYPE) \
394 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
395 V(EXTERNAL_FLOAT32x4_ARRAY_TYPE) \
396 V(EXTERNAL_INT32x4_ARRAY_TYPE) \
397 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
398 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
400 V(FIXED_INT8_ARRAY_TYPE) \
401 V(FIXED_UINT8_ARRAY_TYPE) \
402 V(FIXED_INT16_ARRAY_TYPE) \
403 V(FIXED_UINT16_ARRAY_TYPE) \
404 V(FIXED_INT32_ARRAY_TYPE) \
405 V(FIXED_INT32x4_ARRAY_TYPE) \
406 V(FIXED_UINT32_ARRAY_TYPE) \
407 V(FIXED_FLOAT32_ARRAY_TYPE) \
408 V(FIXED_FLOAT32x4_ARRAY_TYPE) \
409 V(FIXED_FLOAT64_ARRAY_TYPE) \
410 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
414 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
415 V(DECLARED_ACCESSOR_INFO_TYPE) \
416 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
417 V(ACCESSOR_PAIR_TYPE) \
418 V(ACCESS_CHECK_INFO_TYPE) \
419 V(INTERCEPTOR_INFO_TYPE) \
420 V(CALL_HANDLER_INFO_TYPE) \
421 V(FUNCTION_TEMPLATE_INFO_TYPE) \
422 V(OBJECT_TEMPLATE_INFO_TYPE) \
423 V(SIGNATURE_INFO_TYPE) \
424 V(TYPE_SWITCH_INFO_TYPE) \
425 V(ALLOCATION_MEMENTO_TYPE) \
426 V(ALLOCATION_SITE_TYPE) \
429 V(POLYMORPHIC_CODE_CACHE_TYPE) \
430 V(TYPE_FEEDBACK_INFO_TYPE) \
431 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
434 V(FIXED_ARRAY_TYPE) \
435 V(FIXED_DOUBLE_ARRAY_TYPE) \
436 V(CONSTANT_POOL_ARRAY_TYPE) \
437 V(SHARED_FUNCTION_INFO_TYPE) \
439 V(JS_MESSAGE_OBJECT_TYPE) \
444 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
445 V(JS_GENERATOR_OBJECT_TYPE) \
447 V(JS_GLOBAL_OBJECT_TYPE) \
448 V(JS_BUILTINS_OBJECT_TYPE) \
449 V(JS_GLOBAL_PROXY_TYPE) \
451 V(JS_ARRAY_BUFFER_TYPE) \
452 V(JS_TYPED_ARRAY_TYPE) \
453 V(JS_DATA_VIEW_TYPE) \
457 V(JS_WEAK_MAP_TYPE) \
458 V(JS_WEAK_SET_TYPE) \
461 V(JS_FUNCTION_TYPE) \
462 V(JS_FUNCTION_PROXY_TYPE) \
464 V(BREAK_POINT_INFO_TYPE)
467 // Since string types are not consecutive, this macro is used to
468 // iterate over them.
469 #define STRING_TYPE_LIST(V) \
471 kVariableSizeSentinel, \
474 V(ASCII_STRING_TYPE, \
475 kVariableSizeSentinel, \
478 V(CONS_STRING_TYPE, \
482 V(CONS_ASCII_STRING_TYPE, \
486 V(SLICED_STRING_TYPE, \
487 SlicedString::kSize, \
490 V(SLICED_ASCII_STRING_TYPE, \
491 SlicedString::kSize, \
492 sliced_ascii_string, \
494 V(EXTERNAL_STRING_TYPE, \
495 ExternalTwoByteString::kSize, \
498 V(EXTERNAL_ASCII_STRING_TYPE, \
499 ExternalAsciiString::kSize, \
500 external_ascii_string, \
501 ExternalAsciiString) \
502 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
503 ExternalTwoByteString::kSize, \
504 external_string_with_one_byte_data, \
505 ExternalStringWithOneByteData) \
506 V(SHORT_EXTERNAL_STRING_TYPE, \
507 ExternalTwoByteString::kShortSize, \
508 short_external_string, \
509 ShortExternalString) \
510 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
511 ExternalAsciiString::kShortSize, \
512 short_external_ascii_string, \
513 ShortExternalAsciiString) \
514 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
515 ExternalTwoByteString::kShortSize, \
516 short_external_string_with_one_byte_data, \
517 ShortExternalStringWithOneByteData) \
519 V(INTERNALIZED_STRING_TYPE, \
520 kVariableSizeSentinel, \
521 internalized_string, \
522 InternalizedString) \
523 V(ASCII_INTERNALIZED_STRING_TYPE, \
524 kVariableSizeSentinel, \
525 ascii_internalized_string, \
526 AsciiInternalizedString) \
527 V(CONS_INTERNALIZED_STRING_TYPE, \
529 cons_internalized_string, \
530 ConsInternalizedString) \
531 V(CONS_ASCII_INTERNALIZED_STRING_TYPE, \
533 cons_ascii_internalized_string, \
534 ConsAsciiInternalizedString) \
535 V(EXTERNAL_INTERNALIZED_STRING_TYPE, \
536 ExternalTwoByteString::kSize, \
537 external_internalized_string, \
538 ExternalInternalizedString) \
539 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
540 ExternalAsciiString::kSize, \
541 external_ascii_internalized_string, \
542 ExternalAsciiInternalizedString) \
543 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
544 ExternalTwoByteString::kSize, \
545 external_internalized_string_with_one_byte_data, \
546 ExternalInternalizedStringWithOneByteData) \
547 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
548 ExternalTwoByteString::kShortSize, \
549 short_external_internalized_string, \
550 ShortExternalInternalizedString) \
551 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
552 ExternalAsciiString::kShortSize, \
553 short_external_ascii_internalized_string, \
554 ShortExternalAsciiInternalizedString) \
555 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
556 ExternalTwoByteString::kShortSize, \
557 short_external_internalized_string_with_one_byte_data, \
558 ShortExternalInternalizedStringWithOneByteData) \
560 // A struct is a simple object a set of object-valued fields. Including an
561 // object type in this causes the compiler to generate most of the boilerplate
562 // code for the class including allocation and garbage collection routines,
563 // casts and predicates. All you need to define is the class, methods and
564 // object verification routines. Easy, no?
566 // Note that for subtle reasons related to the ordering or numerical values of
567 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
569 #define STRUCT_LIST_ALL(V) \
571 V(DECLARED_ACCESSOR_DESCRIPTOR, \
572 DeclaredAccessorDescriptor, \
573 declared_accessor_descriptor) \
574 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
575 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
576 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
577 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
578 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
579 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
580 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
581 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
582 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
583 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
584 V(SCRIPT, Script, script) \
585 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
586 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
587 V(CODE_CACHE, CodeCache, code_cache) \
588 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
589 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
590 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
592 #ifdef ENABLE_DEBUGGER_SUPPORT
593 #define STRUCT_LIST_DEBUGGER(V) \
594 V(DEBUG_INFO, DebugInfo, debug_info) \
595 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
597 #define STRUCT_LIST_DEBUGGER(V)
600 #define STRUCT_LIST(V) \
602 STRUCT_LIST_DEBUGGER(V)
604 // We use the full 8 bits of the instance_type field to encode heap object
605 // instance types. The high-order bit (bit 7) is set if the object is not a
606 // string, and cleared if it is a string.
607 const uint32_t kIsNotStringMask = 0x80;
608 const uint32_t kStringTag = 0x0;
609 const uint32_t kNotStringTag = 0x80;
611 // Bit 6 indicates that the object is an internalized string (if set) or not.
612 // Bit 7 has to be clear as well.
613 const uint32_t kIsNotInternalizedMask = 0x40;
614 const uint32_t kNotInternalizedTag = 0x40;
615 const uint32_t kInternalizedTag = 0x0;
617 // If bit 7 is clear then bit 2 indicates whether the string consists of
618 // two-byte characters or one-byte characters.
619 const uint32_t kStringEncodingMask = 0x4;
620 const uint32_t kTwoByteStringTag = 0x0;
621 const uint32_t kOneByteStringTag = 0x4;
623 // If bit 7 is clear, the low-order 2 bits indicate the representation
625 const uint32_t kStringRepresentationMask = 0x03;
626 enum StringRepresentationTag {
628 kConsStringTag = 0x1,
629 kExternalStringTag = 0x2,
630 kSlicedStringTag = 0x3
632 const uint32_t kIsIndirectStringMask = 0x1;
633 const uint32_t kIsIndirectStringTag = 0x1;
634 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
635 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
637 (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
639 (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
641 // Use this mask to distinguish between cons and slice only after making
642 // sure that the string is one of the two (an indirect string).
643 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
644 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
646 // If bit 7 is clear, then bit 3 indicates whether this two-byte
647 // string actually contains one byte data.
648 const uint32_t kOneByteDataHintMask = 0x08;
649 const uint32_t kOneByteDataHintTag = 0x08;
651 // If bit 7 is clear and string representation indicates an external string,
652 // then bit 4 indicates whether the data pointer is cached.
653 const uint32_t kShortExternalStringMask = 0x10;
654 const uint32_t kShortExternalStringTag = 0x10;
657 // A ConsString with an empty string as the right side is a candidate
658 // for being shortcut by the garbage collector unless it is internalized.
659 // It's not common to have non-flat internalized strings, so we do not
660 // shortcut them thereby avoiding turning internalized strings into strings.
661 // See heap.cc and mark-compact.cc.
662 const uint32_t kShortcutTypeMask =
664 kIsNotInternalizedMask |
665 kStringRepresentationMask;
666 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
671 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag
673 ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kSeqStringTag
675 CONS_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kConsStringTag
677 CONS_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kConsStringTag
679 EXTERNAL_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kExternalStringTag
681 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag
682 | kExternalStringTag | kInternalizedTag,
683 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
684 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag
686 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE =
687 EXTERNAL_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
689 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE =
690 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
692 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
693 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
694 | kShortExternalStringTag | kInternalizedTag,
696 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
697 ASCII_STRING_TYPE = ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
698 CONS_STRING_TYPE = CONS_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
699 CONS_ASCII_STRING_TYPE =
700 CONS_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
703 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
704 SLICED_ASCII_STRING_TYPE =
705 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
706 EXTERNAL_STRING_TYPE =
707 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
708 EXTERNAL_ASCII_STRING_TYPE =
709 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
710 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
711 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
712 | kNotInternalizedTag,
713 SHORT_EXTERNAL_STRING_TYPE =
714 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
715 SHORT_EXTERNAL_ASCII_STRING_TYPE =
716 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
717 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
718 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
719 | kNotInternalizedTag,
722 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
724 // Objects allocated in their own spaces (never in new space).
731 // "Data", objects that cannot contain non-map-word pointers to heap
740 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
741 EXTERNAL_UINT8_ARRAY_TYPE,
742 EXTERNAL_INT16_ARRAY_TYPE,
743 EXTERNAL_UINT16_ARRAY_TYPE,
744 EXTERNAL_INT32_ARRAY_TYPE,
745 EXTERNAL_UINT32_ARRAY_TYPE,
746 EXTERNAL_FLOAT32_ARRAY_TYPE,
747 EXTERNAL_FLOAT32x4_ARRAY_TYPE,
748 EXTERNAL_INT32x4_ARRAY_TYPE,
749 EXTERNAL_FLOAT64_ARRAY_TYPE,
750 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
752 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
753 FIXED_UINT8_ARRAY_TYPE,
754 FIXED_INT16_ARRAY_TYPE,
755 FIXED_UINT16_ARRAY_TYPE,
756 FIXED_INT32_ARRAY_TYPE,
757 FIXED_INT32x4_ARRAY_TYPE,
758 FIXED_UINT32_ARRAY_TYPE,
759 FIXED_FLOAT32_ARRAY_TYPE,
760 FIXED_FLOAT32x4_ARRAY_TYPE,
761 FIXED_FLOAT64_ARRAY_TYPE,
762 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
764 FIXED_DOUBLE_ARRAY_TYPE,
765 FILLER_TYPE, // LAST_DATA_TYPE
768 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
769 DECLARED_ACCESSOR_INFO_TYPE,
770 EXECUTABLE_ACCESSOR_INFO_TYPE,
772 ACCESS_CHECK_INFO_TYPE,
773 INTERCEPTOR_INFO_TYPE,
774 CALL_HANDLER_INFO_TYPE,
775 FUNCTION_TEMPLATE_INFO_TYPE,
776 OBJECT_TEMPLATE_INFO_TYPE,
778 TYPE_SWITCH_INFO_TYPE,
779 ALLOCATION_SITE_TYPE,
780 ALLOCATION_MEMENTO_TYPE,
783 POLYMORPHIC_CODE_CACHE_TYPE,
784 TYPE_FEEDBACK_INFO_TYPE,
785 ALIASED_ARGUMENTS_ENTRY_TYPE,
787 // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
788 // is defined. However as include/v8.h contain some of the instance type
789 // constants always having them avoids them getting different numbers
790 // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
792 BREAK_POINT_INFO_TYPE,
795 CONSTANT_POOL_ARRAY_TYPE,
796 SHARED_FUNCTION_INFO_TYPE,
798 JS_MESSAGE_OBJECT_TYPE,
800 // All the following types are subtypes of JSReceiver, which corresponds to
801 // objects in the JS sense. The first and the last type in this range are
802 // the two forms of function. This organization enables using the same
803 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
804 // NONCALLABLE_JS_OBJECT range.
805 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
806 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
808 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
811 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
812 JS_GENERATOR_OBJECT_TYPE,
814 JS_GLOBAL_OBJECT_TYPE,
815 JS_BUILTINS_OBJECT_TYPE,
816 JS_GLOBAL_PROXY_TYPE,
818 JS_ARRAY_BUFFER_TYPE,
828 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
832 LAST_TYPE = JS_FUNCTION_TYPE,
833 FIRST_NAME_TYPE = FIRST_TYPE,
834 LAST_NAME_TYPE = SYMBOL_TYPE,
835 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
836 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
837 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
838 // Boundaries for testing for an external array.
839 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
840 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
841 // Boundaries for testing for a fixed typed array.
842 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
843 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
844 // Boundary for promotion to old data space/old pointer space.
845 LAST_DATA_TYPE = FILLER_TYPE,
846 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
847 // Note that there is no range for JSObject or JSProxy, since their subtypes
848 // are not continuous in this enum! The enum ranges instead reflect the
849 // external class names, where proxies are treated as either ordinary objects,
851 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
852 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
853 // Boundaries for testing the types represented as JSObject
854 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
855 LAST_JS_OBJECT_TYPE = LAST_TYPE,
856 // Boundaries for testing the types represented as JSProxy
857 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
858 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
859 // Boundaries for testing whether the type is a JavaScript object.
860 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
861 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
862 // Boundaries for testing the types for which typeof is "object".
863 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
864 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
865 // Note that the types for which typeof is "function" are not continuous.
866 // Define this so that we can put assertions on discrete checks.
867 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
870 const int kExternalArrayTypeCount =
871 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
873 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
874 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
875 STATIC_CHECK(ODDBALL_TYPE == Internals::kOddballType);
876 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
879 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
880 V(FAST_ELEMENTS_SUB_TYPE) \
881 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
882 V(FAST_PROPERTIES_SUB_TYPE) \
883 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
884 V(MAP_CODE_CACHE_SUB_TYPE) \
885 V(SCOPE_INFO_SUB_TYPE) \
886 V(STRING_TABLE_SUB_TYPE) \
887 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
888 V(TRANSITION_ARRAY_SUB_TYPE)
890 enum FixedArraySubInstanceType {
891 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
892 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
893 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
894 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
907 #define DECL_BOOLEAN_ACCESSORS(name) \
908 inline bool name(); \
909 inline void set_##name(bool value); \
912 #define DECL_ACCESSORS(name, type) \
913 inline type* name(); \
914 inline void set_##name(type* value, \
915 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
918 class AllocationSite;
919 class AllocationSiteCreationContext;
920 class AllocationSiteUsageContext;
921 class DictionaryElementsAccessor;
922 class ElementsAccessor;
924 class FixedArrayBase;
928 // We cannot just say "class HeapType;" if it is created from a template... =8-?
929 template<class> class TypeImpl;
930 struct HeapTypeConfig;
931 typedef TypeImpl<HeapTypeConfig> HeapType;
934 // A template-ized version of the IsXXX functions.
935 template <class C> inline bool Is(Object* obj);
938 #define DECLARE_VERIFIER(Name) void Name##Verify();
940 #define DECLARE_VERIFIER(Name)
944 #define DECLARE_PRINTER(Name) void Name##Print(FILE* out = stdout);
946 #define DECLARE_PRINTER(Name)
949 class MaybeObject BASE_EMBEDDED {
951 inline bool IsFailure();
952 inline bool IsRetryAfterGC();
953 inline bool IsException();
954 INLINE(bool IsTheHole());
955 INLINE(bool IsUninitialized());
956 inline bool ToObject(Object** obj) {
957 if (IsFailure()) return false;
958 *obj = reinterpret_cast<Object*>(this);
961 inline Failure* ToFailureUnchecked() {
963 return reinterpret_cast<Failure*>(this);
965 inline Object* ToObjectUnchecked() {
966 // TODO(jkummerow): Turn this back into an ASSERT when we can be certain
967 // that it never fires in Release mode in the wild.
969 return reinterpret_cast<Object*>(this);
971 inline Object* ToObjectChecked() {
973 return reinterpret_cast<Object*>(this);
977 inline bool To(T** obj) {
978 if (IsFailure()) return false;
979 *obj = T::cast(reinterpret_cast<Object*>(this));
984 inline bool ToHandle(Handle<T>* obj, Isolate* isolate) {
985 if (IsFailure()) return false;
986 *obj = handle(T::cast(reinterpret_cast<Object*>(this)), isolate);
991 // Prints this object with details.
993 void Print(FILE* out);
995 void PrintLn(FILE* out);
998 // Verifies the object.
1004 #define OBJECT_TYPE_LIST(V) \
1009 #define HEAP_OBJECT_TYPE_LIST(V) \
1020 V(ExternalTwoByteString) \
1021 V(ExternalAsciiString) \
1022 V(SeqTwoByteString) \
1023 V(SeqOneByteString) \
1024 V(InternalizedString) \
1028 V(ExternalInt8Array) \
1029 V(ExternalUint8Array) \
1030 V(ExternalInt16Array) \
1031 V(ExternalUint16Array) \
1032 V(ExternalInt32Array) \
1033 V(ExternalUint32Array) \
1034 V(ExternalFloat32Array) \
1035 V(ExternalFloat32x4Array) \
1036 V(ExternalInt32x4Array) \
1037 V(ExternalFloat64Array) \
1038 V(ExternalUint8ClampedArray) \
1039 V(FixedTypedArrayBase) \
1040 V(FixedUint8Array) \
1042 V(FixedUint16Array) \
1043 V(FixedInt16Array) \
1044 V(FixedUint32Array) \
1045 V(FixedInt32Array) \
1046 V(FixedFloat32Array) \
1047 V(FixedFloat32x4Array) \
1048 V(FixedInt32x4Array) \
1049 V(FixedFloat64Array) \
1050 V(FixedUint8ClampedArray) \
1055 V(JSContextExtensionObject) \
1056 V(JSGeneratorObject) \
1059 V(DescriptorArray) \
1060 V(TransitionArray) \
1061 V(DeoptimizationInputData) \
1062 V(DeoptimizationOutputData) \
1065 V(FixedDoubleArray) \
1066 V(ConstantPoolArray) \
1073 V(SharedFunctionInfo) \
1076 V(JSMessageObject) \
1082 V(JSArrayBufferView) \
1086 V(JSFunctionProxy) \
1089 V(JSWeakCollection) \
1096 V(JSFunctionResultCache) \
1097 V(NormalizedMapCache) \
1098 V(CompilationCacheTable) \
1099 V(CodeCacheHashTable) \
1100 V(PolymorphicCodeCacheHashTable) \
1105 V(JSBuiltinsObject) \
1107 V(UndetectableObject) \
1108 V(AccessCheckNeeded) \
1111 V(ObjectHashTable) \
1115 #define ERROR_MESSAGES_LIST(V) \
1116 V(kNoReason, "no reason") \
1118 V(k32BitValueInRegisterIsNotZeroExtended, \
1119 "32 bit value in register is not zero-extended") \
1120 V(kAlignmentMarkerExpected, "Alignment marker expected") \
1121 V(kAllocationIsNotDoubleAligned, "Allocation is not double aligned") \
1122 V(kAPICallReturnedInvalidObject, "API call returned invalid object") \
1123 V(kArgumentsObjectValueInATestContext, \
1124 "Arguments object value in a test context") \
1125 V(kArrayBoilerplateCreationFailed, "Array boilerplate creation failed") \
1126 V(kArrayIndexConstantValueTooBig, "Array index constant value too big") \
1127 V(kAssignmentToArguments, "Assignment to arguments") \
1128 V(kAssignmentToLetVariableBeforeInitialization, \
1129 "Assignment to let variable before initialization") \
1130 V(kAssignmentToLOOKUPVariable, "Assignment to LOOKUP variable") \
1131 V(kAssignmentToParameterFunctionUsesArgumentsObject, \
1132 "Assignment to parameter, function uses arguments object") \
1133 V(kAssignmentToParameterInArgumentsObject, \
1134 "Assignment to parameter in arguments object") \
1135 V(kAttemptToUseUndefinedCache, "Attempt to use undefined cache") \
1136 V(kBadValueContextForArgumentsObjectValue, \
1137 "Bad value context for arguments object value") \
1138 V(kBadValueContextForArgumentsValue, \
1139 "Bad value context for arguments value") \
1140 V(kBailedOutDueToDependencyChange, "Bailed out due to dependency change") \
1141 V(kBailoutWasNotPrepared, "Bailout was not prepared") \
1142 V(kBinaryStubGenerateFloatingPointCode, \
1143 "BinaryStub_GenerateFloatingPointCode") \
1144 V(kBothRegistersWereSmisInSelectNonSmi, \
1145 "Both registers were smis in SelectNonSmi") \
1146 V(kCallToAJavaScriptRuntimeFunction, \
1147 "Call to a JavaScript runtime function") \
1148 V(kCannotTranslatePositionInChangedArea, \
1149 "Cannot translate position in changed area") \
1150 V(kCodeGenerationFailed, "Code generation failed") \
1151 V(kCodeObjectNotProperlyPatched, "Code object not properly patched") \
1152 V(kCompoundAssignmentToLookupSlot, "Compound assignment to lookup slot") \
1153 V(kContextAllocatedArguments, "Context-allocated arguments") \
1154 V(kCopyBuffersOverlap, "Copy buffers overlap") \
1155 V(kCouldNotGenerateZero, "Could not generate +0.0") \
1156 V(kCouldNotGenerateNegativeZero, "Could not generate -0.0") \
1157 V(kDebuggerIsActive, "Debugger is active") \
1158 V(kDebuggerStatement, "DebuggerStatement") \
1159 V(kDeclarationInCatchContext, "Declaration in catch context") \
1160 V(kDeclarationInWithContext, "Declaration in with context") \
1161 V(kDefaultNaNModeNotSet, "Default NaN mode not set") \
1162 V(kDeleteWithGlobalVariable, "Delete with global variable") \
1163 V(kDeleteWithNonGlobalVariable, "Delete with non-global variable") \
1164 V(kDestinationOfCopyNotAligned, "Destination of copy not aligned") \
1165 V(kDontDeleteCellsCannotContainTheHole, \
1166 "DontDelete cells can't contain the hole") \
1167 V(kDoPushArgumentNotImplementedForDoubleType, \
1168 "DoPushArgument not implemented for double type") \
1169 V(kEliminatedBoundsCheckFailed, "Eliminated bounds check failed") \
1170 V(kEmitLoadRegisterUnsupportedDoubleImmediate, \
1171 "EmitLoadRegister: Unsupported double immediate") \
1173 V(kExpected0AsASmiSentinel, "Expected 0 as a Smi sentinel") \
1174 V(kExpectedAlignmentMarker, "Expected alignment marker") \
1175 V(kExpectedAllocationSite, "Expected allocation site") \
1176 V(kExpectedFunctionObject, "Expected function object in register") \
1177 V(kExpectedHeapNumber, "Expected HeapNumber") \
1178 V(kExpectedNativeContext, "Expected native context") \
1179 V(kExpectedNonIdenticalObjects, "Expected non-identical objects") \
1180 V(kExpectedNonNullContext, "Expected non-null context") \
1181 V(kExpectedPositiveZero, "Expected +0.0") \
1182 V(kExpectedAllocationSiteInCell, \
1183 "Expected AllocationSite in property cell") \
1184 V(kExpectedFixedArrayInFeedbackVector, \
1185 "Expected fixed array in feedback vector") \
1186 V(kExpectedFixedArrayInRegisterA2, \
1187 "Expected fixed array in register a2") \
1188 V(kExpectedFixedArrayInRegisterEbx, \
1189 "Expected fixed array in register ebx") \
1190 V(kExpectedFixedArrayInRegisterR2, \
1191 "Expected fixed array in register r2") \
1192 V(kExpectedFixedArrayInRegisterRbx, \
1193 "Expected fixed array in register rbx") \
1194 V(kExpectedSmiOrHeapNumber, "Expected smi or HeapNumber") \
1195 V(kExpectedUndefinedOrCell, \
1196 "Expected undefined or cell in register") \
1197 V(kExpectingAlignmentForCopyBytes, \
1198 "Expecting alignment for CopyBytes") \
1199 V(kExportDeclaration, "Export declaration") \
1200 V(kExternalStringExpectedButNotFound, \
1201 "External string expected, but not found") \
1202 V(kFailedBailedOutLastTime, "Failed/bailed out last time") \
1203 V(kForInStatementIsNotFastCase, "ForInStatement is not fast case") \
1204 V(kForInStatementOptimizationIsDisabled, \
1205 "ForInStatement optimization is disabled") \
1206 V(kForInStatementWithNonLocalEachVariable, \
1207 "ForInStatement with non-local each variable") \
1208 V(kForOfStatement, "ForOfStatement") \
1209 V(kFrameIsExpectedToBeAligned, "Frame is expected to be aligned") \
1210 V(kFunctionCallsEval, "Function calls eval") \
1211 V(kFunctionIsAGenerator, "Function is a generator") \
1212 V(kFunctionWithIllegalRedeclaration, "Function with illegal redeclaration") \
1213 V(kGeneratedCodeIsTooLarge, "Generated code is too large") \
1214 V(kGeneratorFailedToResume, "Generator failed to resume") \
1215 V(kGenerator, "Generator") \
1216 V(kGlobalFunctionsMustHaveInitialMap, \
1217 "Global functions must have initial map") \
1218 V(kHeapNumberMapRegisterClobbered, "HeapNumberMap register clobbered") \
1219 V(kHydrogenFilter, "Optimization disabled by filter") \
1220 V(kImportDeclaration, "Import declaration") \
1221 V(kImproperObjectOnPrototypeChainForStore, \
1222 "Improper object on prototype chain for store") \
1223 V(kIndexIsNegative, "Index is negative") \
1224 V(kIndexIsTooLarge, "Index is too large") \
1225 V(kInlinedRuntimeFunctionClassOf, "Inlined runtime function: ClassOf") \
1226 V(kInlinedRuntimeFunctionFastAsciiArrayJoin, \
1227 "Inlined runtime function: FastAsciiArrayJoin") \
1228 V(kInlinedRuntimeFunctionGeneratorNext, \
1229 "Inlined runtime function: GeneratorNext") \
1230 V(kInlinedRuntimeFunctionGeneratorThrow, \
1231 "Inlined runtime function: GeneratorThrow") \
1232 V(kInlinedRuntimeFunctionGetFromCache, \
1233 "Inlined runtime function: GetFromCache") \
1234 V(kInlinedRuntimeFunctionIsNonNegativeSmi, \
1235 "Inlined runtime function: IsNonNegativeSmi") \
1236 V(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf, \
1237 "Inlined runtime function: IsStringWrapperSafeForDefaultValueOf") \
1238 V(kInliningBailedOut, "Inlining bailed out") \
1239 V(kInputGPRIsExpectedToHaveUpper32Cleared, \
1240 "Input GPR is expected to have upper32 cleared") \
1241 V(kInputStringTooLong, "Input string too long") \
1242 V(kInstanceofStubUnexpectedCallSiteCacheCheck, \
1243 "InstanceofStub unexpected call site cache (check)") \
1244 V(kInstanceofStubUnexpectedCallSiteCacheCmp1, \
1245 "InstanceofStub unexpected call site cache (cmp 1)") \
1246 V(kInstanceofStubUnexpectedCallSiteCacheCmp2, \
1247 "InstanceofStub unexpected call site cache (cmp 2)") \
1248 V(kInstanceofStubUnexpectedCallSiteCacheMov, \
1249 "InstanceofStub unexpected call site cache (mov)") \
1250 V(kInteger32ToSmiFieldWritingToNonSmiLocation, \
1251 "Integer32ToSmiField writing to non-smi location") \
1252 V(kInvalidCaptureReferenced, "Invalid capture referenced") \
1253 V(kInvalidElementsKindForInternalArrayOrInternalPackedArray, \
1254 "Invalid ElementsKind for InternalArray or InternalPackedArray") \
1255 V(kInvalidFullCodegenState, "invalid full-codegen state") \
1256 V(kInvalidHandleScopeLevel, "Invalid HandleScope level") \
1257 V(kInvalidLeftHandSideInAssignment, "Invalid left-hand side in assignment") \
1258 V(kInvalidLhsInCompoundAssignment, "Invalid lhs in compound assignment") \
1259 V(kInvalidLhsInCountOperation, "Invalid lhs in count operation") \
1260 V(kInvalidMinLength, "Invalid min_length") \
1261 V(kJSGlobalObjectNativeContextShouldBeANativeContext, \
1262 "JSGlobalObject::native_context should be a native context") \
1263 V(kJSGlobalProxyContextShouldNotBeNull, \
1264 "JSGlobalProxy::context() should not be null") \
1265 V(kJSObjectWithFastElementsMapHasSlowElements, \
1266 "JSObject with fast elements map has slow elements") \
1267 V(kLetBindingReInitialization, "Let binding re-initialization") \
1268 V(kLhsHasBeenClobbered, "lhs has been clobbered") \
1269 V(kLiveBytesCountOverflowChunkSize, "Live Bytes Count overflow chunk size") \
1270 V(kLiveEditFrameDroppingIsNotSupportedOnARM64, \
1271 "LiveEdit frame dropping is not supported on arm64") \
1272 V(kLiveEditFrameDroppingIsNotSupportedOnArm, \
1273 "LiveEdit frame dropping is not supported on arm") \
1274 V(kLiveEditFrameDroppingIsNotSupportedOnMips, \
1275 "LiveEdit frame dropping is not supported on mips") \
1276 V(kLiveEdit, "LiveEdit") \
1277 V(kLookupVariableInCountOperation, \
1278 "Lookup variable in count operation") \
1279 V(kMapIsNoLongerInEax, "Map is no longer in eax") \
1280 V(kModuleDeclaration, "Module declaration") \
1281 V(kModuleLiteral, "Module literal") \
1282 V(kModulePath, "Module path") \
1283 V(kModuleStatement, "Module statement") \
1284 V(kModuleVariable, "Module variable") \
1285 V(kModuleUrl, "Module url") \
1286 V(kNativeFunctionLiteral, "Native function literal") \
1287 V(kNoCasesLeft, "No cases left") \
1288 V(kNoEmptyArraysHereInEmitFastAsciiArrayJoin, \
1289 "No empty arrays here in EmitFastAsciiArrayJoin") \
1290 V(kNonInitializerAssignmentToConst, \
1291 "Non-initializer assignment to const") \
1292 V(kNonSmiIndex, "Non-smi index") \
1293 V(kNonSmiKeyInArrayLiteral, "Non-smi key in array literal") \
1294 V(kNonSmiValue, "Non-smi value") \
1295 V(kNonObject, "Non-object value") \
1296 V(kNotEnoughVirtualRegistersForValues, \
1297 "Not enough virtual registers for values") \
1298 V(kNotEnoughSpillSlotsForOsr, \
1299 "Not enough spill slots for OSR") \
1300 V(kNotEnoughVirtualRegistersRegalloc, \
1301 "Not enough virtual registers (regalloc)") \
1302 V(kObjectFoundInSmiOnlyArray, "Object found in smi-only array") \
1303 V(kObjectLiteralWithComplexProperty, \
1304 "Object literal with complex property") \
1305 V(kOddballInStringTableIsNotUndefinedOrTheHole, \
1306 "Oddball in string table is not undefined or the hole") \
1307 V(kOffsetOutOfRange, "Offset out of range") \
1308 V(kOperandIsASmiAndNotAName, "Operand is a smi and not a name") \
1309 V(kOperandIsASmiAndNotAString, "Operand is a smi and not a string") \
1310 V(kOperandIsASmi, "Operand is a smi") \
1311 V(kOperandIsNotAName, "Operand is not a name") \
1312 V(kOperandIsNotANumber, "Operand is not a number") \
1313 V(kOperandIsNotASmi, "Operand is not a smi") \
1314 V(kOperandIsNotAString, "Operand is not a string") \
1315 V(kOperandIsNotSmi, "Operand is not smi") \
1316 V(kOperandNotANumber, "Operand not a number") \
1317 V(kOptimizationDisabled, "Optimization is disabled") \
1318 V(kOptimizedTooManyTimes, "Optimized too many times") \
1319 V(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister, \
1320 "Out of virtual registers while trying to allocate temp register") \
1321 V(kParseScopeError, "Parse/scope error") \
1322 V(kPossibleDirectCallToEval, "Possible direct call to eval") \
1323 V(kPreconditionsWereNotMet, "Preconditions were not met") \
1324 V(kPropertyAllocationCountFailed, "Property allocation count failed") \
1325 V(kReceivedInvalidReturnAddress, "Received invalid return address") \
1326 V(kReferenceToAVariableWhichRequiresDynamicLookup, \
1327 "Reference to a variable which requires dynamic lookup") \
1328 V(kReferenceToGlobalLexicalVariable, \
1329 "Reference to global lexical variable") \
1330 V(kReferenceToUninitializedVariable, "Reference to uninitialized variable") \
1331 V(kRegisterDidNotMatchExpectedRoot, "Register did not match expected root") \
1332 V(kRegisterWasClobbered, "Register was clobbered") \
1333 V(kRememberedSetPointerInNewSpace, "Remembered set pointer is in new space") \
1334 V(kReturnAddressNotFoundInFrame, "Return address not found in frame") \
1335 V(kRhsHasBeenClobbered, "Rhs has been clobbered") \
1336 V(kScopedBlock, "ScopedBlock") \
1337 V(kSmiAdditionOverflow, "Smi addition overflow") \
1338 V(kSmiSubtractionOverflow, "Smi subtraction overflow") \
1339 V(kStackAccessBelowStackPointer, "Stack access below stack pointer") \
1340 V(kStackFrameTypesMustMatch, "Stack frame types must match") \
1341 V(kSwitchStatementMixedOrNonLiteralSwitchLabels, \
1342 "SwitchStatement: mixed or non-literal switch labels") \
1343 V(kSwitchStatementTooManyClauses, "SwitchStatement: too many clauses") \
1344 V(kTheCurrentStackPointerIsBelowCsp, \
1345 "The current stack pointer is below csp") \
1346 V(kTheInstructionShouldBeALui, "The instruction should be a lui") \
1347 V(kTheInstructionShouldBeAnOri, "The instruction should be an ori") \
1348 V(kTheInstructionToPatchShouldBeALoadFromPc, \
1349 "The instruction to patch should be a load from pc") \
1350 V(kTheInstructionToPatchShouldBeALoadFromPp, \
1351 "The instruction to patch should be a load from pp") \
1352 V(kTheInstructionToPatchShouldBeAnLdrLiteral, \
1353 "The instruction to patch should be a ldr literal") \
1354 V(kTheInstructionToPatchShouldBeALui, \
1355 "The instruction to patch should be a lui") \
1356 V(kTheInstructionToPatchShouldBeAnOri, \
1357 "The instruction to patch should be an ori") \
1358 V(kTheSourceAndDestinationAreTheSame, \
1359 "The source and destination are the same") \
1360 V(kTheStackPointerIsNotAligned, "The stack pointer is not aligned.") \
1361 V(kTheStackWasCorruptedByMacroAssemblerCall, \
1362 "The stack was corrupted by MacroAssembler::Call()") \
1363 V(kTooManyParametersLocals, "Too many parameters/locals") \
1364 V(kTooManyParameters, "Too many parameters") \
1365 V(kTooManySpillSlotsNeededForOSR, "Too many spill slots needed for OSR") \
1366 V(kToOperand32UnsupportedImmediate, "ToOperand32 unsupported immediate.") \
1367 V(kToOperandIsDoubleRegisterUnimplemented, \
1368 "ToOperand IsDoubleRegister unimplemented") \
1369 V(kToOperandUnsupportedDoubleImmediate, \
1370 "ToOperand Unsupported double immediate") \
1371 V(kTryCatchStatement, "TryCatchStatement") \
1372 V(kTryFinallyStatement, "TryFinallyStatement") \
1373 V(kUnableToEncodeValueAsSmi, "Unable to encode value as smi") \
1374 V(kUnalignedAllocationInNewSpace, "Unaligned allocation in new space") \
1375 V(kUnalignedCellInWriteBarrier, "Unaligned cell in write barrier") \
1376 V(kUndefinedValueNotLoaded, "Undefined value not loaded") \
1377 V(kUndoAllocationOfNonAllocatedMemory, \
1378 "Undo allocation of non allocated memory") \
1379 V(kUnexpectedAllocationTop, "Unexpected allocation top") \
1380 V(kUnexpectedColorFound, "Unexpected color bit pattern found") \
1381 V(kUnexpectedElementsKindInArrayConstructor, \
1382 "Unexpected ElementsKind in array constructor") \
1383 V(kUnexpectedFallthroughFromCharCodeAtSlowCase, \
1384 "Unexpected fallthrough from CharCodeAt slow case") \
1385 V(kUnexpectedFallthroughFromCharFromCodeSlowCase, \
1386 "Unexpected fallthrough from CharFromCode slow case") \
1387 V(kUnexpectedFallThroughFromStringComparison, \
1388 "Unexpected fall-through from string comparison") \
1389 V(kUnexpectedFallThroughInBinaryStubGenerateFloatingPointCode, \
1390 "Unexpected fall-through in BinaryStub_GenerateFloatingPointCode") \
1391 V(kUnexpectedFallthroughToCharCodeAtSlowCase, \
1392 "Unexpected fallthrough to CharCodeAt slow case") \
1393 V(kUnexpectedFallthroughToCharFromCodeSlowCase, \
1394 "Unexpected fallthrough to CharFromCode slow case") \
1395 V(kUnexpectedFPUStackDepthAfterInstruction, \
1396 "Unexpected FPU stack depth after instruction") \
1397 V(kUnexpectedInitialMapForArrayFunction1, \
1398 "Unexpected initial map for Array function (1)") \
1399 V(kUnexpectedInitialMapForArrayFunction2, \
1400 "Unexpected initial map for Array function (2)") \
1401 V(kUnexpectedInitialMapForArrayFunction, \
1402 "Unexpected initial map for Array function") \
1403 V(kUnexpectedInitialMapForInternalArrayFunction, \
1404 "Unexpected initial map for InternalArray function") \
1405 V(kUnexpectedLevelAfterReturnFromApiCall, \
1406 "Unexpected level after return from api call") \
1407 V(kUnexpectedNegativeValue, "Unexpected negative value") \
1408 V(kUnexpectedNumberOfPreAllocatedPropertyFields, \
1409 "Unexpected number of pre-allocated property fields") \
1410 V(kUnexpectedSmi, "Unexpected smi value") \
1411 V(kUnexpectedStringFunction, "Unexpected String function") \
1412 V(kUnexpectedStringType, "Unexpected string type") \
1413 V(kUnexpectedStringWrapperInstanceSize, \
1414 "Unexpected string wrapper instance size") \
1415 V(kUnexpectedTypeForRegExpDataFixedArrayExpected, \
1416 "Unexpected type for RegExp data, FixedArray expected") \
1417 V(kUnexpectedValue, "Unexpected value") \
1418 V(kUnexpectedUnusedPropertiesOfStringWrapper, \
1419 "Unexpected unused properties of string wrapper") \
1420 V(kUnimplemented, "unimplemented") \
1421 V(kUninitializedKSmiConstantRegister, "Uninitialized kSmiConstantRegister") \
1422 V(kUnknown, "Unknown") \
1423 V(kUnsupportedConstCompoundAssignment, \
1424 "Unsupported const compound assignment") \
1425 V(kUnsupportedCountOperationWithConst, \
1426 "Unsupported count operation with const") \
1427 V(kUnsupportedDoubleImmediate, "Unsupported double immediate") \
1428 V(kUnsupportedLetCompoundAssignment, "Unsupported let compound assignment") \
1429 V(kUnsupportedLookupSlotInDeclaration, \
1430 "Unsupported lookup slot in declaration") \
1431 V(kUnsupportedNonPrimitiveCompare, "Unsupported non-primitive compare") \
1432 V(kUnsupportedPhiUseOfArguments, "Unsupported phi use of arguments") \
1433 V(kUnsupportedPhiUseOfConstVariable, \
1434 "Unsupported phi use of const variable") \
1435 V(kUnsupportedTaggedImmediate, "Unsupported tagged immediate") \
1436 V(kVariableResolvedToWithContext, "Variable resolved to with context") \
1437 V(kWeShouldNotHaveAnEmptyLexicalContext, \
1438 "We should not have an empty lexical context") \
1439 V(kWithStatement, "WithStatement") \
1440 V(kWrongAddressOrValuePassedToRecordWrite, \
1441 "Wrong address or value passed to RecordWrite") \
1445 #define ERROR_MESSAGES_CONSTANTS(C, T) C,
1446 enum BailoutReason {
1447 ERROR_MESSAGES_LIST(ERROR_MESSAGES_CONSTANTS)
1450 #undef ERROR_MESSAGES_CONSTANTS
1453 const char* GetBailoutReason(BailoutReason reason);
1456 // Object is the abstract superclass for all classes in the
1457 // object hierarchy.
1458 // Object does not use any virtual functions to avoid the
1459 // allocation of the C++ vtable.
1460 // Since Smi and Failure are subclasses of Object no
1461 // data members can be present in Object.
1462 class Object : public MaybeObject {
1465 bool IsObject() { return true; }
1467 #define IS_TYPE_FUNCTION_DECL(type_) inline bool Is##type_();
1468 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1469 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1470 #undef IS_TYPE_FUNCTION_DECL
1472 inline bool IsFixedArrayBase();
1473 inline bool IsExternal();
1474 inline bool IsAccessorInfo();
1476 inline bool IsStruct();
1477 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
1478 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1479 #undef DECLARE_STRUCT_PREDICATE
1481 INLINE(bool IsSpecObject());
1482 INLINE(bool IsSpecFunction());
1486 INLINE(bool IsUndefined());
1487 INLINE(bool IsNull());
1488 INLINE(bool IsTheHole()); // Shadows MaybeObject's implementation.
1489 INLINE(bool IsUninitialized());
1490 INLINE(bool IsTrue());
1491 INLINE(bool IsFalse());
1492 inline bool IsArgumentsMarker();
1493 inline bool NonFailureIsHeapObject();
1495 // Filler objects (fillers and free space objects).
1496 inline bool IsFiller();
1498 // Extract the number.
1499 inline double Number();
1500 inline bool IsNaN();
1501 bool ToInt32(int32_t* value);
1502 bool ToUint32(uint32_t* value);
1504 // Indicates whether OptimalRepresentation can do its work, or whether it
1505 // always has to return Representation::Tagged().
1507 OPTIMAL_REPRESENTATION,
1511 inline Representation OptimalRepresentation(
1512 ValueType type = OPTIMAL_REPRESENTATION) {
1513 if (!FLAG_track_fields) return Representation::Tagged();
1514 if (type == FORCE_TAGGED) return Representation::Tagged();
1516 return Representation::Smi();
1517 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1518 return Representation::Double();
1519 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1520 return Representation::None();
1521 } else if (FLAG_track_heap_object_fields) {
1522 ASSERT(IsHeapObject());
1523 return Representation::HeapObject();
1525 return Representation::Tagged();
1529 inline bool FitsRepresentation(Representation representation) {
1530 if (FLAG_track_fields && representation.IsNone()) {
1532 } else if (FLAG_track_fields && representation.IsSmi()) {
1534 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1536 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1537 return IsHeapObject();
1542 inline MaybeObject* AllocateNewStorageFor(Heap* heap,
1543 Representation representation);
1545 // Returns true if the object is of the correct type to be used as a
1546 // implementation of a JSObject's elements.
1547 inline bool HasValidElements();
1549 inline bool HasSpecificClassOf(String* name);
1551 MUST_USE_RESULT MaybeObject* ToObject(Isolate* isolate); // ECMA-262 9.9.
1552 bool BooleanValue(); // ECMA-262 9.2.
1554 // Convert to a JSObject if needed.
1555 // native_context is used when creating wrapper object.
1556 MUST_USE_RESULT MaybeObject* ToObject(Context* native_context);
1558 // Converts this to a Smi if possible.
1559 // Failure is returned otherwise.
1560 static MUST_USE_RESULT inline Handle<Object> ToSmi(Isolate* isolate,
1561 Handle<Object> object);
1562 MUST_USE_RESULT inline MaybeObject* ToSmi();
1564 void Lookup(Name* name, LookupResult* result);
1567 MUST_USE_RESULT inline MaybeObject* GetProperty(Name* key);
1568 MUST_USE_RESULT inline MaybeObject* GetProperty(
1570 PropertyAttributes* attributes);
1572 // TODO(yangguo): this should eventually replace the non-handlified version.
1573 static Handle<Object> GetPropertyWithReceiver(Handle<Object> object,
1574 Handle<Object> receiver,
1576 PropertyAttributes* attributes);
1577 MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
1580 PropertyAttributes* attributes);
1582 static Handle<Object> GetProperty(Handle<Object> object,
1584 static Handle<Object> GetProperty(Handle<Object> object,
1585 Handle<Object> receiver,
1586 LookupResult* result,
1588 PropertyAttributes* attributes);
1590 MUST_USE_RESULT static MaybeObject* GetPropertyOrFail(
1591 Handle<Object> object,
1592 Handle<Object> receiver,
1593 LookupResult* result,
1595 PropertyAttributes* attributes);
1597 MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
1598 LookupResult* result,
1600 PropertyAttributes* attributes);
1602 MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
1603 JSReceiver* getter);
1605 static inline Handle<Object> GetElement(Isolate* isolate,
1606 Handle<Object> object,
1609 // For use when we know that no exception can be thrown.
1610 static inline Handle<Object> GetElementNoExceptionThrown(
1612 Handle<Object> object,
1615 static Handle<Object> GetElementWithReceiver(Isolate* isolate,
1616 Handle<Object> object,
1617 Handle<Object> receiver,
1620 // Return the object's prototype (might be Heap::null_value()).
1621 Object* GetPrototype(Isolate* isolate);
1622 Map* GetMarkerMap(Isolate* isolate);
1624 // Returns the permanent hash code associated with this object. May return
1625 // undefined if not yet created.
1628 // Returns the permanent hash code associated with this object depending on
1629 // the actual object type. May create and store a hash code if needed and none
1631 // TODO(rafaelw): Remove isolate parameter when objects.cc is fully
1633 static Handle<Object> GetOrCreateHash(Handle<Object> object,
1636 // Checks whether this object has the same value as the given one. This
1637 // function is implemented according to ES5, section 9.12 and can be used
1638 // to implement the Harmony "egal" function.
1639 bool SameValue(Object* other);
1641 // Tries to convert an object to an array index. Returns true and sets
1642 // the output parameter if it succeeds.
1643 inline bool ToArrayIndex(uint32_t* index);
1645 // Returns true if this is a JSValue containing a string and the index is
1646 // < the length of the string. Used to implement [] on strings.
1647 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1650 // Verify a pointer is a valid object pointer.
1651 static void VerifyPointer(Object* p);
1654 inline void VerifyApiCallResultType();
1656 // Prints this object without details.
1657 void ShortPrint(FILE* out = stdout);
1659 // Prints this object without details to a message accumulator.
1660 void ShortPrint(StringStream* accumulator);
1662 // Casting: This cast is only needed to satisfy macros in objects-inl.h.
1663 static Object* cast(Object* value) { return value; }
1665 // Layout description.
1666 static const int kHeaderSize = 0; // Object does not take up any space.
1669 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1673 // Smi represents integer Numbers that can be stored in 31 bits.
1674 // Smis are immediate which means they are NOT allocated in the heap.
1675 // The this pointer has the following format: [31 bit signed int] 0
1676 // For long smis it has the following format:
1677 // [32 bit signed int] [31 bits zero padding] 0
1678 // Smi stands for small integer.
1679 class Smi: public Object {
1681 // Returns the integer value.
1684 // Convert a value to a Smi object.
1685 static inline Smi* FromInt(int value);
1687 static inline Smi* FromIntptr(intptr_t value);
1689 // Returns whether value can be represented in a Smi.
1690 static inline bool IsValid(intptr_t value);
1693 static inline Smi* cast(Object* object);
1695 // Dispatched behavior.
1696 void SmiPrint(FILE* out = stdout);
1697 void SmiPrint(StringStream* accumulator);
1699 DECLARE_VERIFIER(Smi)
1701 static const int kMinValue =
1702 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1703 static const int kMaxValue = -(kMinValue + 1);
1706 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1710 // Failure is used for reporting out of memory situations and
1711 // propagating exceptions through the runtime system. Failure objects
1712 // are transient and cannot occur as part of the object graph.
1714 // Failures are a single word, encoded as follows:
1715 // +-------------------------+---+--+--+
1716 // |.........unused..........|sss|tt|11|
1717 // +-------------------------+---+--+--+
1721 // The low two bits, 0-1, are the failure tag, 11. The next two bits,
1722 // 2-3, are a failure type tag 'tt' with possible values:
1723 // 00 RETRY_AFTER_GC
1725 // 10 INTERNAL_ERROR
1726 // 11 OUT_OF_MEMORY_EXCEPTION
1728 // The next three bits, 4-6, are an allocation space tag 'sss'. The
1729 // allocation space tag is 000 for all failure types except
1730 // RETRY_AFTER_GC. For RETRY_AFTER_GC, the possible values are the
1731 // allocation spaces (the encoding is found in globals.h).
1733 // Failure type tag info.
1734 const int kFailureTypeTagSize = 2;
1735 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1737 class Failure: public MaybeObject {
1739 // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1742 EXCEPTION = 1, // Returning this marker tells the real exception
1743 // is in Isolate::pending_exception.
1745 OUT_OF_MEMORY_EXCEPTION = 3
1748 inline Type type() const;
1750 // Returns the space that needs to be collected for RetryAfterGC failures.
1751 inline AllocationSpace allocation_space() const;
1753 inline bool IsInternalError() const;
1755 static inline Failure* RetryAfterGC(AllocationSpace space);
1756 static inline Failure* RetryAfterGC(); // NEW_SPACE
1757 static inline Failure* Exception();
1758 static inline Failure* InternalError();
1760 static inline Failure* cast(MaybeObject* object);
1762 // Dispatched behavior.
1763 void FailurePrint(FILE* out = stdout);
1764 void FailurePrint(StringStream* accumulator);
1766 DECLARE_VERIFIER(Failure)
1769 inline intptr_t value() const;
1770 static inline Failure* Construct(Type type, intptr_t value = 0);
1772 DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1776 // Heap objects typically have a map pointer in their first word. However,
1777 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1778 // encoded in the first word. The class MapWord is an abstraction of the
1779 // value in a heap object's first word.
1780 class MapWord BASE_EMBEDDED {
1782 // Normal state: the map word contains a map pointer.
1784 // Create a map word from a map pointer.
1785 static inline MapWord FromMap(Map* map);
1787 // View this map word as a map pointer.
1788 inline Map* ToMap();
1791 // Scavenge collection: the map word of live objects in the from space
1792 // contains a forwarding address (a heap object pointer in the to space).
1794 // True if this map word is a forwarding address for a scavenge
1795 // collection. Only valid during a scavenge collection (specifically,
1796 // when all map words are heap object pointers, i.e. not during a full GC).
1797 inline bool IsForwardingAddress();
1799 // Create a map word from a forwarding address.
1800 static inline MapWord FromForwardingAddress(HeapObject* object);
1802 // View this map word as a forwarding address.
1803 inline HeapObject* ToForwardingAddress();
1805 static inline MapWord FromRawValue(uintptr_t value) {
1806 return MapWord(value);
1809 inline uintptr_t ToRawValue() {
1814 // HeapObject calls the private constructor and directly reads the value.
1815 friend class HeapObject;
1817 explicit MapWord(uintptr_t value) : value_(value) {}
1823 // HeapObject is the superclass for all classes describing heap allocated
1825 class HeapObject: public Object {
1827 // [map]: Contains a map which contains the object's reflective
1830 inline void set_map(Map* value);
1831 // The no-write-barrier version. This is OK if the object is white and in
1832 // new space, or if the value is an immortal immutable object, like the maps
1833 // of primitive (non-JS) objects like strings, heap numbers etc.
1834 inline void set_map_no_write_barrier(Map* value);
1836 // During garbage collection, the map word of a heap object does not
1837 // necessarily contain a map pointer.
1838 inline MapWord map_word();
1839 inline void set_map_word(MapWord map_word);
1841 // The Heap the object was allocated in. Used also to access Isolate.
1842 inline Heap* GetHeap();
1844 // Convenience method to get current isolate.
1845 inline Isolate* GetIsolate();
1847 // Converts an address to a HeapObject pointer.
1848 static inline HeapObject* FromAddress(Address address);
1850 // Returns the address of this HeapObject.
1851 inline Address address();
1853 // Iterates over pointers contained in the object (including the Map)
1854 void Iterate(ObjectVisitor* v);
1856 // Iterates over all pointers contained in the object except the
1857 // first map pointer. The object type is given in the first
1858 // parameter. This function does not access the map pointer in the
1859 // object, and so is safe to call while the map pointer is modified.
1860 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1862 // Returns the heap object's size in bytes
1865 // Given a heap object's map pointer, returns the heap size in bytes
1866 // Useful when the map pointer field is used for other purposes.
1868 inline int SizeFromMap(Map* map);
1870 // Returns the field at offset in obj, as a read/write Object* reference.
1871 // Does no checking, and is safe to use during GC, while maps are invalid.
1872 // Does not invoke write barrier, so should only be assigned to
1873 // during marking GC.
1874 static inline Object** RawField(HeapObject* obj, int offset);
1876 // Adds the |code| object related to |name| to the code cache of this map. If
1877 // this map is a dictionary map that is shared, the map copied and installed
1879 static void UpdateMapCodeCache(Handle<HeapObject> object,
1884 static inline HeapObject* cast(Object* obj);
1886 // Return the write barrier mode for this. Callers of this function
1887 // must be able to present a reference to an DisallowHeapAllocation
1888 // object as a sign that they are not going to use this function
1889 // from code that allocates and thus invalidates the returned write
1891 inline WriteBarrierMode GetWriteBarrierMode(
1892 const DisallowHeapAllocation& promise);
1894 // Dispatched behavior.
1895 void HeapObjectShortPrint(StringStream* accumulator);
1897 void PrintHeader(FILE* out, const char* id);
1899 DECLARE_PRINTER(HeapObject)
1900 DECLARE_VERIFIER(HeapObject)
1902 inline void VerifyObjectField(int offset);
1903 inline void VerifySmiField(int offset);
1905 // Verify a pointer is a valid HeapObject pointer that points to object
1906 // areas in the heap.
1907 static void VerifyHeapPointer(Object* p);
1910 // Layout description.
1911 // First field in a heap object is map.
1912 static const int kMapOffset = Object::kHeaderSize;
1913 static const int kHeaderSize = kMapOffset + kPointerSize;
1915 STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1918 // helpers for calling an ObjectVisitor to iterate over pointers in the
1919 // half-open range [start, end) specified as integer offsets
1920 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1921 // as above, for the single element at "offset"
1922 inline void IteratePointer(ObjectVisitor* v, int offset);
1923 // as above, for the next code link of a code object.
1924 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1927 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1931 // This class describes a body of an object of a fixed size
1932 // in which all pointer fields are located in the [start_offset, end_offset)
1934 template<int start_offset, int end_offset, int size>
1935 class FixedBodyDescriptor {
1937 static const int kStartOffset = start_offset;
1938 static const int kEndOffset = end_offset;
1939 static const int kSize = size;
1941 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1943 template<typename StaticVisitor>
1944 static inline void IterateBody(HeapObject* obj) {
1945 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1946 HeapObject::RawField(obj, end_offset));
1951 // This class describes a body of an object of a variable size
1952 // in which all pointer fields are located in the [start_offset, object_size)
1954 template<int start_offset>
1955 class FlexibleBodyDescriptor {
1957 static const int kStartOffset = start_offset;
1959 static inline void IterateBody(HeapObject* obj,
1963 template<typename StaticVisitor>
1964 static inline void IterateBody(HeapObject* obj, int object_size) {
1965 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1966 HeapObject::RawField(obj, object_size));
1971 // The HeapNumber class describes heap allocated numbers that cannot be
1972 // represented in a Smi (small integer)
1973 class HeapNumber: public HeapObject {
1975 // [value]: number value.
1976 inline double value();
1977 inline void set_value(double value);
1980 static inline HeapNumber* cast(Object* obj);
1982 // Dispatched behavior.
1983 bool HeapNumberBooleanValue();
1985 void HeapNumberPrint(FILE* out = stdout);
1986 void HeapNumberPrint(StringStream* accumulator);
1987 DECLARE_VERIFIER(HeapNumber)
1989 inline int get_exponent();
1990 inline int get_sign();
1992 // Layout description.
1993 static const int kValueOffset = HeapObject::kHeaderSize;
1994 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1995 // is a mixture of sign, exponent and mantissa. Our current platforms are all
1996 // little endian apart from non-EABI arm which is little endian with big
1997 // endian floating point word ordering!
1998 static const int kMantissaOffset = kValueOffset;
1999 static const int kExponentOffset = kValueOffset + 4;
2001 static const int kSize = kValueOffset + kDoubleSize;
2002 static const uint32_t kSignMask = 0x80000000u;
2003 static const uint32_t kExponentMask = 0x7ff00000u;
2004 static const uint32_t kMantissaMask = 0xfffffu;
2005 static const int kMantissaBits = 52;
2006 static const int kExponentBits = 11;
2007 static const int kExponentBias = 1023;
2008 static const int kExponentShift = 20;
2009 static const int kInfinityOrNanExponent =
2010 (kExponentMask >> kExponentShift) - kExponentBias;
2011 static const int kMantissaBitsInTopWord = 20;
2012 static const int kNonMantissaBitsInTopWord = 12;
2015 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
2019 class Float32x4: public HeapObject {
2021 typedef float32x4_value_t value_t;
2022 static const int kLanes = 4;
2023 static const int kValueSize = kFloat32x4Size;
2024 static const InstanceType kInstanceType = FLOAT32x4_TYPE;
2025 static inline const char* Name();
2026 static inline int kRuntimeAllocatorId();
2027 static inline int kMapRootIndex();
2029 // [value]: float32x4 value.
2030 inline float32x4_value_t value();
2031 inline void set_value(float32x4_value_t value);
2034 static inline Float32x4* cast(Object* obj);
2036 inline void Float32x4Print() {
2037 Float32x4Print(stdout);
2039 void Float32x4Print(FILE* out);
2040 void Float32x4Print(StringStream* accumulator);
2041 DECLARE_VERIFIER(Float32x4)
2043 inline float getAt(int index);
2044 inline float x() { return getAt(0); }
2045 inline float y() { return getAt(1); }
2046 inline float z() { return getAt(2); }
2047 inline float w() { return getAt(3); }
2049 // Layout description.
2050 static const int kValueOffset = HeapObject::kHeaderSize;
2051 static const int kSize = kValueOffset + kValueSize;
2054 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
2058 class Int32x4: public HeapObject {
2060 typedef int32x4_value_t value_t;
2061 static const int kValueSize = kInt32x4Size;
2062 static const InstanceType kInstanceType = INT32x4_TYPE;
2063 static inline const char* Name();
2064 static inline int kRuntimeAllocatorId();
2065 static inline int kMapRootIndex();
2067 // [value]: int32x4 value.
2068 inline int32x4_value_t value();
2069 inline void set_value(int32x4_value_t value);
2072 static inline Int32x4* cast(Object* obj);
2074 inline void Int32x4Print() {
2075 Int32x4Print(stdout);
2077 void Int32x4Print(FILE* out);
2078 void Int32x4Print(StringStream* accumulator);
2079 DECLARE_VERIFIER(Int32x4)
2081 static const int kLanes = 4;
2082 inline int32_t getAt(int32_t index);
2083 inline int32_t x() { return getAt(0); }
2084 inline int32_t y() { return getAt(1); }
2085 inline int32_t z() { return getAt(2); }
2086 inline int32_t w() { return getAt(3); }
2088 // Layout description.
2089 static const int kValueOffset = HeapObject::kHeaderSize;
2090 static const int kSize = kValueOffset + kValueSize;
2093 DISALLOW_IMPLICIT_CONSTRUCTORS(Int32x4);
2097 enum EnsureElementsMode {
2098 DONT_ALLOW_DOUBLE_ELEMENTS,
2099 ALLOW_COPIED_DOUBLE_ELEMENTS,
2100 ALLOW_CONVERTED_DOUBLE_ELEMENTS
2104 // Indicates whether a property should be set or (re)defined. Setting of a
2105 // property causes attributes to remain unchanged, writability to be checked
2106 // and callbacks to be called. Defining of a property causes attributes to
2107 // be updated and callbacks to be overridden.
2108 enum SetPropertyMode {
2114 // Indicator for one component of an AccessorPair.
2115 enum AccessorComponent {
2121 // JSReceiver includes types on which properties can be defined, i.e.,
2122 // JSObject and JSProxy.
2123 class JSReceiver: public HeapObject {
2131 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
2132 // a keyed store is of the form a[expression] = foo.
2133 enum StoreFromKeyed {
2134 MAY_BE_STORE_FROM_KEYED,
2135 CERTAINLY_NOT_STORE_FROM_KEYED
2138 // Internal properties (e.g. the hidden properties dictionary) might
2139 // be added even though the receiver is non-extensible.
2140 enum ExtensibilityCheck {
2141 PERFORM_EXTENSIBILITY_CHECK,
2142 OMIT_EXTENSIBILITY_CHECK
2146 static inline JSReceiver* cast(Object* obj);
2148 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
2149 static Handle<Object> SetProperty(Handle<JSReceiver> object,
2151 Handle<Object> value,
2152 PropertyAttributes attributes,
2153 StrictMode strict_mode,
2154 StoreFromKeyed store_mode =
2155 MAY_BE_STORE_FROM_KEYED);
2156 static Handle<Object> SetElement(Handle<JSReceiver> object,
2158 Handle<Object> value,
2159 PropertyAttributes attributes,
2160 StrictMode strict_mode);
2162 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
2163 static inline bool HasProperty(Handle<JSReceiver> object, Handle<Name> name);
2164 static inline bool HasLocalProperty(Handle<JSReceiver>, Handle<Name> name);
2165 static inline bool HasElement(Handle<JSReceiver> object, uint32_t index);
2166 static inline bool HasLocalElement(Handle<JSReceiver> object, uint32_t index);
2168 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
2169 static Handle<Object> DeleteProperty(Handle<JSReceiver> object,
2171 DeleteMode mode = NORMAL_DELETION);
2172 static Handle<Object> DeleteElement(Handle<JSReceiver> object,
2174 DeleteMode mode = NORMAL_DELETION);
2176 // Tests for the fast common case for property enumeration.
2177 bool IsSimpleEnum();
2179 // Returns the class name ([[Class]] property in the specification).
2180 String* class_name();
2182 // Returns the constructor name (the name (possibly, inferred name) of the
2183 // function that was used to instantiate the object).
2184 String* constructor_name();
2186 static inline PropertyAttributes GetPropertyAttribute(
2187 Handle<JSReceiver> object,
2189 static PropertyAttributes GetPropertyAttributeWithReceiver(
2190 Handle<JSReceiver> object,
2191 Handle<JSReceiver> receiver,
2193 static PropertyAttributes GetLocalPropertyAttribute(
2194 Handle<JSReceiver> object,
2197 static inline PropertyAttributes GetElementAttribute(
2198 Handle<JSReceiver> object,
2200 static inline PropertyAttributes GetLocalElementAttribute(
2201 Handle<JSReceiver> object,
2204 // Return the object's prototype (might be Heap::null_value()).
2205 inline Object* GetPrototype();
2207 // Return the constructor function (may be Heap::null_value()).
2208 inline Object* GetConstructor();
2210 // Retrieves a permanent object identity hash code. The undefined value might
2211 // be returned in case no hash was created yet.
2212 inline Object* GetIdentityHash();
2214 // Retrieves a permanent object identity hash code. May create and store a
2215 // hash code if needed and none exists.
2216 inline static Handle<Object> GetOrCreateIdentityHash(
2217 Handle<JSReceiver> object);
2219 // Lookup a property. If found, the result is valid and has
2220 // detailed information.
2221 void LocalLookup(Name* name, LookupResult* result,
2222 bool search_hidden_prototypes = false);
2223 void Lookup(Name* name, LookupResult* result);
2226 Smi* GenerateIdentityHash();
2228 static Handle<Object> SetPropertyWithDefinedSetter(Handle<JSReceiver> object,
2229 Handle<JSReceiver> setter,
2230 Handle<Object> value);
2233 static PropertyAttributes GetPropertyAttributeForResult(
2234 Handle<JSReceiver> object,
2235 Handle<JSReceiver> receiver,
2236 LookupResult* result,
2238 bool continue_search);
2240 static Handle<Object> SetProperty(Handle<JSReceiver> receiver,
2241 LookupResult* result,
2243 Handle<Object> value,
2244 PropertyAttributes attributes,
2245 StrictMode strict_mode,
2246 StoreFromKeyed store_from_keyed);
2248 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
2251 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
2252 class ObjectHashTable;
2254 // The JSObject describes real heap allocated JavaScript objects with
2256 // Note that the map of JSObject changes during execution to enable inline
2258 class JSObject: public JSReceiver {
2260 // [properties]: Backing storage for properties.
2261 // properties is a FixedArray in the fast case and a Dictionary in the
2263 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
2264 inline void initialize_properties();
2265 inline bool HasFastProperties();
2266 inline NameDictionary* property_dictionary(); // Gets slow properties.
2268 // [elements]: The elements (properties with names that are integers).
2270 // Elements can be in two general modes: fast and slow. Each mode
2271 // corrensponds to a set of object representations of elements that
2272 // have something in common.
2274 // In the fast mode elements is a FixedArray and so each element can
2275 // be quickly accessed. This fact is used in the generated code. The
2276 // elements array can have one of three maps in this mode:
2277 // fixed_array_map, sloppy_arguments_elements_map or
2278 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
2279 // the elements array may be shared by a few objects and so before
2280 // writing to any element the array must be copied. Use
2281 // EnsureWritableFastElements in this case.
2283 // In the slow mode the elements is either a NumberDictionary, an
2284 // ExternalArray, or a FixedArray parameter map for a (sloppy)
2285 // arguments object.
2286 DECL_ACCESSORS(elements, FixedArrayBase)
2287 inline void initialize_elements();
2288 MUST_USE_RESULT inline MaybeObject* ResetElements();
2289 inline ElementsKind GetElementsKind();
2290 inline ElementsAccessor* GetElementsAccessor();
2291 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
2292 inline bool HasFastSmiElements();
2293 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
2294 inline bool HasFastObjectElements();
2295 // Returns true if an object has elements of FAST_ELEMENTS or
2296 // FAST_SMI_ONLY_ELEMENTS.
2297 inline bool HasFastSmiOrObjectElements();
2298 // Returns true if an object has any of the fast elements kinds.
2299 inline bool HasFastElements();
2300 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
2302 inline bool HasFastDoubleElements();
2303 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
2305 inline bool HasFastHoleyElements();
2306 inline bool HasSloppyArgumentsElements();
2307 inline bool HasDictionaryElements();
2309 inline bool HasExternalUint8ClampedElements();
2310 inline bool HasExternalArrayElements();
2311 inline bool HasExternalInt8Elements();
2312 inline bool HasExternalUint8Elements();
2313 inline bool HasExternalInt16Elements();
2314 inline bool HasExternalUint16Elements();
2315 inline bool HasExternalInt32Elements();
2316 inline bool HasExternalUint32Elements();
2317 inline bool HasExternalFloat32Elements();
2318 inline bool HasExternalFloat32x4Elements();
2319 inline bool HasExternalInt32x4Elements();
2320 inline bool HasExternalFloat64Elements();
2322 inline bool HasFixedTypedArrayElements();
2324 inline bool HasFixedUint8ClampedElements();
2325 inline bool HasFixedArrayElements();
2326 inline bool HasFixedInt8Elements();
2327 inline bool HasFixedUint8Elements();
2328 inline bool HasFixedInt16Elements();
2329 inline bool HasFixedUint16Elements();
2330 inline bool HasFixedInt32Elements();
2331 inline bool HasFixedUint32Elements();
2332 inline bool HasFixedFloat32Elements();
2333 inline bool HasFixedFloat64Elements();
2334 inline bool HasFixedFloat32x4Elements();
2335 inline bool HasFixedInt32x4Elements();
2337 bool HasFastArgumentsElements();
2338 bool HasDictionaryArgumentsElements();
2339 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
2341 inline void set_map_and_elements(
2343 FixedArrayBase* value,
2344 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
2346 // Requires: HasFastElements().
2347 static Handle<FixedArray> EnsureWritableFastElements(
2348 Handle<JSObject> object);
2349 MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
2351 // Collects elements starting at index 0.
2352 // Undefined values are placed after non-undefined values.
2353 // Returns the number of non-undefined values.
2354 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
2356 // As PrepareElementsForSort, but only on objects where elements is
2357 // a dictionary, and it will stay a dictionary.
2358 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
2360 MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
2362 static Handle<Object> GetPropertyWithCallback(Handle<JSObject> object,
2363 Handle<Object> receiver,
2364 Handle<Object> structure,
2367 static Handle<Object> SetPropertyWithCallback(
2368 Handle<JSObject> object,
2369 Handle<Object> structure,
2371 Handle<Object> value,
2372 Handle<JSObject> holder,
2373 StrictMode strict_mode);
2375 static Handle<Object> SetPropertyWithInterceptor(
2376 Handle<JSObject> object,
2378 Handle<Object> value,
2379 PropertyAttributes attributes,
2380 StrictMode strict_mode);
2382 static Handle<Object> SetPropertyForResult(
2383 Handle<JSObject> object,
2384 LookupResult* result,
2386 Handle<Object> value,
2387 PropertyAttributes attributes,
2388 StrictMode strict_mode,
2389 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2391 static Handle<Object> SetLocalPropertyIgnoreAttributes(
2392 Handle<JSObject> object,
2394 Handle<Object> value,
2395 PropertyAttributes attributes,
2396 ValueType value_type = OPTIMAL_REPRESENTATION,
2397 StoreMode mode = ALLOW_AS_CONSTANT,
2398 ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK);
2400 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
2401 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
2403 // Try to follow an existing transition to a field with attributes NONE. The
2404 // return value indicates whether the transition was successful.
2405 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
2408 // Extend the receiver with a single fast property appeared first in the
2409 // passed map. This also extends the property backing store if necessary.
2410 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
2412 // Migrates the given object to a map whose field representations are the
2413 // lowest upper bound of all known representations for that field.
2414 static void MigrateInstance(Handle<JSObject> instance);
2416 // Migrates the given object only if the target map is already available,
2417 // or returns an empty handle if such a map is not yet available.
2418 static Handle<Object> TryMigrateInstance(Handle<JSObject> instance);
2420 // Retrieve a value in a normalized object given a lookup result.
2421 // Handles the special representation of JS global objects.
2422 Object* GetNormalizedProperty(const LookupResult* result);
2424 // Sets the property value in a normalized object given a lookup result.
2425 // Handles the special representation of JS global objects.
2426 static void SetNormalizedProperty(Handle<JSObject> object,
2427 const LookupResult* result,
2428 Handle<Object> value);
2430 // Sets the property value in a normalized object given (key, value, details).
2431 // Handles the special representation of JS global objects.
2432 static void SetNormalizedProperty(Handle<JSObject> object,
2434 Handle<Object> value,
2435 PropertyDetails details);
2437 static void OptimizeAsPrototype(Handle<JSObject> object);
2439 // Retrieve interceptors.
2440 InterceptorInfo* GetNamedInterceptor();
2441 InterceptorInfo* GetIndexedInterceptor();
2443 // Used from JSReceiver.
2444 static PropertyAttributes GetPropertyAttributePostInterceptor(
2445 Handle<JSObject> object,
2446 Handle<JSObject> receiver,
2448 bool continue_search);
2449 static PropertyAttributes GetPropertyAttributeWithInterceptor(
2450 Handle<JSObject> object,
2451 Handle<JSObject> receiver,
2453 bool continue_search);
2454 static PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
2455 Handle<JSObject> object,
2456 LookupResult* result,
2458 bool continue_search);
2459 static PropertyAttributes GetElementAttributeWithReceiver(
2460 Handle<JSObject> object,
2461 Handle<JSReceiver> receiver,
2463 bool continue_search);
2465 // Retrieves an AccessorPair property from the given object. Might return
2466 // undefined if the property doesn't exist or is of a different kind.
2467 static Handle<Object> GetAccessor(Handle<JSObject> object,
2469 AccessorComponent component);
2471 // Defines an AccessorPair property on the given object.
2472 // TODO(mstarzinger): Rename to SetAccessor() and return empty handle on
2473 // exception instead of letting callers check for scheduled exception.
2474 static void DefineAccessor(Handle<JSObject> object,
2476 Handle<Object> getter,
2477 Handle<Object> setter,
2478 PropertyAttributes attributes,
2479 v8::AccessControl access_control = v8::DEFAULT);
2481 // Defines an AccessorInfo property on the given object.
2482 static Handle<Object> SetAccessor(Handle<JSObject> object,
2483 Handle<AccessorInfo> info);
2485 static Handle<Object> GetPropertyWithInterceptor(
2486 Handle<JSObject> object,
2487 Handle<Object> receiver,
2489 PropertyAttributes* attributes);
2490 static Handle<Object> GetPropertyPostInterceptor(
2491 Handle<JSObject> object,
2492 Handle<Object> receiver,
2494 PropertyAttributes* attributes);
2495 MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
2498 PropertyAttributes* attributes);
2500 // Returns true if this is an instance of an api function and has
2501 // been modified since it was created. May give false positives.
2504 // Accessors for hidden properties object.
2506 // Hidden properties are not local properties of the object itself.
2507 // Instead they are stored in an auxiliary structure kept as a local
2508 // property with a special name Heap::hidden_string(). But if the
2509 // receiver is a JSGlobalProxy then the auxiliary object is a property
2510 // of its prototype, and if it's a detached proxy, then you can't have
2511 // hidden properties.
2513 // Sets a hidden property on this object. Returns this object if successful,
2514 // undefined if called on a detached proxy.
2515 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2517 Handle<Object> value);
2518 // Gets the value of a hidden property with the given key. Returns the hole
2519 // if the property doesn't exist (or if called on a detached proxy),
2520 // otherwise returns the value set for the key.
2521 Object* GetHiddenProperty(Name* key);
2522 // Deletes a hidden property. Deleting a non-existing property is
2523 // considered successful.
2524 static void DeleteHiddenProperty(Handle<JSObject> object,
2526 // Returns true if the object has a property with the hidden string as name.
2527 static bool HasHiddenProperties(Handle<JSObject> object);
2529 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2531 inline void ValidateElements();
2533 // Makes sure that this object can contain HeapObject as elements.
2534 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2536 // Makes sure that this object can contain the specified elements.
2537 static inline void EnsureCanContainElements(
2538 Handle<JSObject> object,
2541 EnsureElementsMode mode);
2542 static inline void EnsureCanContainElements(
2543 Handle<JSObject> object,
2544 Handle<FixedArrayBase> elements,
2546 EnsureElementsMode mode);
2547 static void EnsureCanContainElements(
2548 Handle<JSObject> object,
2549 Arguments* arguments,
2552 EnsureElementsMode mode);
2554 // Would we convert a fast elements array to dictionary mode given
2555 // an access at key?
2556 bool WouldConvertToSlowElements(Handle<Object> key);
2557 // Do we want to keep the elements in fast case when increasing the
2559 bool ShouldConvertToSlowElements(int new_capacity);
2560 // Returns true if the backing storage for the slow-case elements of
2561 // this object takes up nearly as much space as a fast-case backing
2562 // storage would. In that case the JSObject should have fast
2564 bool ShouldConvertToFastElements();
2565 // Returns true if the elements of JSObject contains only values that can be
2566 // represented in a FixedDoubleArray and has at least one value that can only
2567 // be represented as a double and not a Smi.
2568 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
2570 // Computes the new capacity when expanding the elements of a JSObject.
2571 static int NewElementsCapacity(int old_capacity) {
2572 // (old_capacity + 50%) + 16
2573 return old_capacity + (old_capacity >> 1) + 16;
2576 // These methods do not perform access checks!
2577 AccessorPair* GetLocalPropertyAccessorPair(Name* name);
2578 AccessorPair* GetLocalElementAccessorPair(uint32_t index);
2580 static Handle<Object> SetFastElement(Handle<JSObject> object, uint32_t index,
2581 Handle<Object> value,
2582 StrictMode strict_mode,
2583 bool check_prototype);
2585 static Handle<Object> SetOwnElement(Handle<JSObject> object,
2587 Handle<Object> value,
2588 StrictMode strict_mode);
2590 // Empty handle is returned if the element cannot be set to the given value.
2591 static Handle<Object> SetElement(
2592 Handle<JSObject> object,
2594 Handle<Object> value,
2595 PropertyAttributes attributes,
2596 StrictMode strict_mode,
2597 bool check_prototype = true,
2598 SetPropertyMode set_mode = SET_PROPERTY);
2600 // Returns the index'th element.
2601 // The undefined object if index is out of bounds.
2602 static Handle<Object> GetElementWithInterceptor(Handle<JSObject> object,
2603 Handle<Object> receiver,
2606 enum SetFastElementsCapacitySmiMode {
2609 kDontAllowSmiElements
2612 // Replace the elements' backing store with fast elements of the given
2613 // capacity. Update the length for JSArrays. Returns the new backing
2615 static Handle<FixedArray> SetFastElementsCapacityAndLength(
2616 Handle<JSObject> object,
2619 SetFastElementsCapacitySmiMode smi_mode);
2620 static void SetFastDoubleElementsCapacityAndLength(
2621 Handle<JSObject> object,
2624 MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
2628 // Lookup interceptors are used for handling properties controlled by host
2630 inline bool HasNamedInterceptor();
2631 inline bool HasIndexedInterceptor();
2633 // Support functions for v8 api (needed for correct interceptor behavior).
2634 static bool HasRealNamedProperty(Handle<JSObject> object,
2636 static bool HasRealElementProperty(Handle<JSObject> object, uint32_t index);
2637 static bool HasRealNamedCallbackProperty(Handle<JSObject> object,
2640 // Get the header size for a JSObject. Used to compute the index of
2641 // internal fields as well as the number of internal fields.
2642 inline int GetHeaderSize();
2644 inline int GetInternalFieldCount();
2645 inline int GetInternalFieldOffset(int index);
2646 inline Object* GetInternalField(int index);
2647 inline void SetInternalField(int index, Object* value);
2648 inline void SetInternalField(int index, Smi* value);
2650 // The following lookup functions skip interceptors.
2651 void LocalLookupRealNamedProperty(Name* name, LookupResult* result);
2652 void LookupRealNamedProperty(Name* name, LookupResult* result);
2653 void LookupRealNamedPropertyInPrototypes(Name* name, LookupResult* result);
2654 void LookupCallbackProperty(Name* name, LookupResult* result);
2656 // Returns the number of properties on this object filtering out properties
2657 // with the specified attributes (ignoring interceptors).
2658 int NumberOfLocalProperties(PropertyAttributes filter = NONE);
2659 // Fill in details for properties into storage starting at the specified
2661 void GetLocalPropertyNames(
2662 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2664 // Returns the number of properties on this object filtering out properties
2665 // with the specified attributes (ignoring interceptors).
2666 int NumberOfLocalElements(PropertyAttributes filter);
2667 // Returns the number of enumerable elements (ignoring interceptors).
2668 int NumberOfEnumElements();
2669 // Returns the number of elements on this object filtering out elements
2670 // with the specified attributes (ignoring interceptors).
2671 int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
2672 // Count and fill in the enumerable elements into storage.
2673 // (storage->length() == NumberOfEnumElements()).
2674 // If storage is NULL, will count the elements without adding
2675 // them to any storage.
2676 // Returns the number of enumerable elements.
2677 int GetEnumElementKeys(FixedArray* storage);
2679 // Returns a new map with all transitions dropped from the object's current
2680 // map and the ElementsKind set.
2681 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2682 ElementsKind to_kind);
2683 inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
2685 ElementsKind elements_kind);
2686 MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
2687 ElementsKind elements_kind);
2689 static void TransitionElementsKind(Handle<JSObject> object,
2690 ElementsKind to_kind);
2692 // TODO(mstarzinger): Both public because of ConvertAnsSetLocalProperty().
2693 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2694 static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2696 Representation new_representation,
2697 StoreMode store_mode);
2699 // Convert the object to use the canonical dictionary
2700 // representation. If the object is expected to have additional properties
2701 // added this number can be indicated to have the backing store allocated to
2702 // an initial capacity for holding these properties.
2703 static void NormalizeProperties(Handle<JSObject> object,
2704 PropertyNormalizationMode mode,
2705 int expected_additional_properties);
2707 // Convert and update the elements backing store to be a
2708 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2709 static Handle<SeededNumberDictionary> NormalizeElements(
2710 Handle<JSObject> object);
2712 // Transform slow named properties to fast variants.
2713 static void TransformToFastProperties(Handle<JSObject> object,
2714 int unused_property_fields);
2716 // Access fast-case object properties at index.
2717 MUST_USE_RESULT inline MaybeObject* FastPropertyAt(
2718 Representation representation,
2720 inline Object* RawFastPropertyAt(int index);
2721 inline void FastPropertyAtPut(int index, Object* value);
2723 // Access to in object properties.
2724 inline int GetInObjectPropertyOffset(int index);
2725 inline Object* InObjectPropertyAt(int index);
2726 inline Object* InObjectPropertyAtPut(int index,
2728 WriteBarrierMode mode
2729 = UPDATE_WRITE_BARRIER);
2731 // Set the object's prototype (only JSReceiver and null are allowed values).
2732 static Handle<Object> SetPrototype(Handle<JSObject> object,
2733 Handle<Object> value,
2734 bool skip_hidden_prototypes = false);
2736 // Initializes the body after properties slot, properties slot is
2737 // initialized by set_properties. Fill the pre-allocated fields with
2738 // pre_allocated_value and the rest with filler_value.
2739 // Note: this call does not update write barrier, the caller is responsible
2740 // to ensure that |filler_value| can be collected without WB here.
2741 inline void InitializeBody(Map* map,
2742 Object* pre_allocated_value,
2743 Object* filler_value);
2745 // Check whether this object references another object
2746 bool ReferencesObject(Object* obj);
2748 // Disalow further properties to be added to the object.
2749 static Handle<Object> PreventExtensions(Handle<JSObject> object);
2751 // ES5 Object.freeze
2752 static Handle<Object> Freeze(Handle<JSObject> object);
2754 // Called the first time an object is observed with ES7 Object.observe.
2755 static void SetObserved(Handle<JSObject> object);
2758 enum DeepCopyHints {
2760 kObjectIsShallowArray = 1
2763 static Handle<JSObject> Copy(Handle<JSObject> object);
2764 static Handle<JSObject> DeepCopy(Handle<JSObject> object,
2765 AllocationSiteUsageContext* site_context,
2766 DeepCopyHints hints = kNoHints);
2767 static Handle<JSObject> DeepWalk(Handle<JSObject> object,
2768 AllocationSiteCreationContext* site_context);
2771 static inline JSObject* cast(Object* obj);
2773 // Dispatched behavior.
2774 void JSObjectShortPrint(StringStream* accumulator);
2775 DECLARE_PRINTER(JSObject)
2776 DECLARE_VERIFIER(JSObject)
2778 void PrintProperties(FILE* out = stdout);
2779 void PrintElements(FILE* out = stdout);
2780 void PrintTransitions(FILE* out = stdout);
2783 static void PrintElementsTransition(
2784 FILE* file, Handle<JSObject> object,
2785 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2786 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2788 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2791 // Structure for collecting spill information about JSObjects.
2792 class SpillInformation {
2796 int number_of_objects_;
2797 int number_of_objects_with_fast_properties_;
2798 int number_of_objects_with_fast_elements_;
2799 int number_of_fast_used_fields_;
2800 int number_of_fast_unused_fields_;
2801 int number_of_slow_used_properties_;
2802 int number_of_slow_unused_properties_;
2803 int number_of_fast_used_elements_;
2804 int number_of_fast_unused_elements_;
2805 int number_of_slow_used_elements_;
2806 int number_of_slow_unused_elements_;
2809 void IncrementSpillStatistics(SpillInformation* info);
2813 // If a GC was caused while constructing this object, the elements pointer
2814 // may point to a one pointer filler map. The object won't be rooted, but
2815 // our heap verification code could stumble across it.
2816 bool ElementsAreSafeToExamine();
2819 Object* SlowReverseLookup(Object* value);
2821 // Maximal number of fast properties for the JSObject. Used to
2822 // restrict the number of map transitions to avoid an explosion in
2823 // the number of maps for objects used as dictionaries.
2824 inline bool TooManyFastProperties(
2825 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2827 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2828 // Also maximal value of JSArray's length property.
2829 static const uint32_t kMaxElementCount = 0xffffffffu;
2831 // Constants for heuristics controlling conversion of fast elements
2832 // to slow elements.
2834 // Maximal gap that can be introduced by adding an element beyond
2835 // the current elements length.
2836 static const uint32_t kMaxGap = 1024;
2838 // Maximal length of fast elements array that won't be checked for
2839 // being dense enough on expansion.
2840 static const int kMaxUncheckedFastElementsLength = 5000;
2842 // Same as above but for old arrays. This limit is more strict. We
2843 // don't want to be wasteful with long lived objects.
2844 static const int kMaxUncheckedOldFastElementsLength = 500;
2846 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2847 // permissible values (see the ASSERT in heap.cc).
2848 static const int kInitialMaxFastElementArray = 100000;
2850 static const int kFastPropertiesSoftLimit = 12;
2851 static const int kMaxFastProperties = 64;
2852 static const int kMaxInstanceSize = 255 * kPointerSize;
2853 // When extending the backing storage for property values, we increase
2854 // its size by more than the 1 entry necessary, so sequentially adding fields
2855 // to the same object requires fewer allocations and copies.
2856 static const int kFieldsAdded = 3;
2858 // Layout description.
2859 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2860 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2861 static const int kHeaderSize = kElementsOffset + kPointerSize;
2863 STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2865 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2867 static inline int SizeOf(Map* map, HeapObject* object);
2870 // Enqueue change record for Object.observe. May cause GC.
2871 static void EnqueueChangeRecord(Handle<JSObject> object,
2874 Handle<Object> old_value);
2877 friend class DictionaryElementsAccessor;
2878 friend class JSReceiver;
2879 friend class Object;
2881 static void UpdateAllocationSite(Handle<JSObject> object,
2882 ElementsKind to_kind);
2884 // Used from Object::GetProperty().
2885 static Handle<Object> GetPropertyWithFailedAccessCheck(
2886 Handle<JSObject> object,
2887 Handle<Object> receiver,
2888 LookupResult* result,
2890 PropertyAttributes* attributes);
2892 MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2896 static PropertyAttributes GetElementAttributeWithInterceptor(
2897 Handle<JSObject> object,
2898 Handle<JSReceiver> receiver,
2900 bool continue_search);
2901 static PropertyAttributes GetElementAttributeWithoutInterceptor(
2902 Handle<JSObject> object,
2903 Handle<JSReceiver> receiver,
2905 bool continue_search);
2906 static Handle<Object> SetElementWithCallback(
2907 Handle<JSObject> object,
2908 Handle<Object> structure,
2910 Handle<Object> value,
2911 Handle<JSObject> holder,
2912 StrictMode strict_mode);
2913 static Handle<Object> SetElementWithInterceptor(
2914 Handle<JSObject> object,
2916 Handle<Object> value,
2917 PropertyAttributes attributes,
2918 StrictMode strict_mode,
2919 bool check_prototype,
2920 SetPropertyMode set_mode);
2921 static Handle<Object> SetElementWithoutInterceptor(
2922 Handle<JSObject> object,
2924 Handle<Object> value,
2925 PropertyAttributes attributes,
2926 StrictMode strict_mode,
2927 bool check_prototype,
2928 SetPropertyMode set_mode);
2929 static Handle<Object> SetElementWithCallbackSetterInPrototypes(
2930 Handle<JSObject> object,
2932 Handle<Object> value,
2934 StrictMode strict_mode);
2935 static Handle<Object> SetDictionaryElement(
2936 Handle<JSObject> object,
2938 Handle<Object> value,
2939 PropertyAttributes attributes,
2940 StrictMode strict_mode,
2941 bool check_prototype,
2942 SetPropertyMode set_mode = SET_PROPERTY);
2943 static Handle<Object> SetFastDoubleElement(
2944 Handle<JSObject> object,
2946 Handle<Object> value,
2947 StrictMode strict_mode,
2948 bool check_prototype = true);
2950 // Searches the prototype chain for property 'name'. If it is found and
2951 // has a setter, invoke it and set '*done' to true. If it is found and is
2952 // read-only, reject and set '*done' to true. Otherwise, set '*done' to
2953 // false. Can throw and return an empty handle with '*done==true'.
2954 static Handle<Object> SetPropertyViaPrototypes(
2955 Handle<JSObject> object,
2957 Handle<Object> value,
2958 PropertyAttributes attributes,
2959 StrictMode strict_mode,
2961 static Handle<Object> SetPropertyPostInterceptor(
2962 Handle<JSObject> object,
2964 Handle<Object> value,
2965 PropertyAttributes attributes,
2966 StrictMode strict_mode);
2967 static Handle<Object> SetPropertyUsingTransition(
2968 Handle<JSObject> object,
2969 LookupResult* lookup,
2971 Handle<Object> value,
2972 PropertyAttributes attributes);
2973 static Handle<Object> SetPropertyWithFailedAccessCheck(
2974 Handle<JSObject> object,
2975 LookupResult* result,
2977 Handle<Object> value,
2978 bool check_prototype,
2979 StrictMode strict_mode);
2981 // Add a property to an object.
2982 static Handle<Object> AddProperty(
2983 Handle<JSObject> object,
2985 Handle<Object> value,
2986 PropertyAttributes attributes,
2987 StrictMode strict_mode,
2988 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED,
2989 ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK,
2990 ValueType value_type = OPTIMAL_REPRESENTATION,
2991 StoreMode mode = ALLOW_AS_CONSTANT,
2992 TransitionFlag flag = INSERT_TRANSITION);
2994 // Add a constant function property to a fast-case object.
2995 // This leaves a CONSTANT_TRANSITION in the old map, and
2996 // if it is called on a second object with this map, a
2997 // normal property is added instead, with a map transition.
2998 // This avoids the creation of many maps with the same constant
2999 // function, all orphaned.
3000 static void AddConstantProperty(Handle<JSObject> object,
3002 Handle<Object> constant,
3003 PropertyAttributes attributes,
3004 TransitionFlag flag);
3006 // Add a property to a fast-case object.
3007 static void AddFastProperty(Handle<JSObject> object,
3009 Handle<Object> value,
3010 PropertyAttributes attributes,
3011 StoreFromKeyed store_mode,
3012 ValueType value_type,
3013 TransitionFlag flag);
3015 // Add a property to a slow-case object.
3016 static void AddSlowProperty(Handle<JSObject> object,
3018 Handle<Object> value,
3019 PropertyAttributes attributes);
3021 static Handle<Object> DeleteProperty(Handle<JSObject> object,
3024 static Handle<Object> DeletePropertyPostInterceptor(Handle<JSObject> object,
3027 static Handle<Object> DeletePropertyWithInterceptor(Handle<JSObject> object,
3030 // Deletes the named property in a normalized object.
3031 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
3035 static Handle<Object> DeleteElement(Handle<JSObject> object,
3038 static Handle<Object> DeleteElementWithInterceptor(Handle<JSObject> object,
3041 bool ReferencesObjectFromElements(FixedArray* elements,
3045 // Returns true if most of the elements backing storage is used.
3046 bool HasDenseElements();
3048 // Gets the current elements capacity and the number of used elements.
3049 void GetElementsCapacityAndUsage(int* capacity, int* used);
3051 static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
3052 static void SetElementCallback(Handle<JSObject> object,
3054 Handle<Object> structure,
3055 PropertyAttributes attributes);
3056 static void SetPropertyCallback(Handle<JSObject> object,
3058 Handle<Object> structure,
3059 PropertyAttributes attributes);
3060 static void DefineElementAccessor(Handle<JSObject> object,
3062 Handle<Object> getter,
3063 Handle<Object> setter,
3064 PropertyAttributes attributes,
3065 v8::AccessControl access_control);
3066 static Handle<AccessorPair> CreateAccessorPairFor(Handle<JSObject> object,
3068 static void DefinePropertyAccessor(Handle<JSObject> object,
3070 Handle<Object> getter,
3071 Handle<Object> setter,
3072 PropertyAttributes attributes,
3073 v8::AccessControl access_control);
3075 // Try to define a single accessor paying attention to map transitions.
3076 // Returns false if this was not possible and we have to use the slow case.
3077 static bool DefineFastAccessor(Handle<JSObject> object,
3079 AccessorComponent component,
3080 Handle<Object> accessor,
3081 PropertyAttributes attributes);
3084 // Return the hash table backing store or the inline stored identity hash,
3085 // whatever is found.
3086 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
3088 // Return the hash table backing store for hidden properties. If there is no
3089 // backing store, allocate one.
3090 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
3091 Handle<JSObject> object);
3093 // Set the hidden property backing store to either a hash table or
3094 // the inline-stored identity hash.
3095 static Handle<Object> SetHiddenPropertiesHashTable(
3096 Handle<JSObject> object,
3097 Handle<Object> value);
3099 MUST_USE_RESULT Object* GetIdentityHash();
3101 static Handle<Object> GetOrCreateIdentityHash(Handle<JSObject> object);
3103 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
3107 // Common superclass for FixedArrays that allow implementations to share
3108 // common accessors and some code paths.
3109 class FixedArrayBase: public HeapObject {
3111 // [length]: length of the array.
3112 inline int length();
3113 inline void set_length(int value);
3115 inline static FixedArrayBase* cast(Object* object);
3117 // Layout description.
3118 // Length is smi tagged when it is stored.
3119 static const int kLengthOffset = HeapObject::kHeaderSize;
3120 static const int kHeaderSize = kLengthOffset + kPointerSize;
3124 class FixedDoubleArray;
3125 class IncrementalMarking;
3128 // FixedArray describes fixed-sized arrays with element type Object*.
3129 class FixedArray: public FixedArrayBase {
3131 // Setter and getter for elements.
3132 inline Object* get(int index);
3133 // Setter that uses write barrier.
3134 inline void set(int index, Object* value);
3135 inline bool is_the_hole(int index);
3137 // Setter that doesn't need write barrier.
3138 inline void set(int index, Smi* value);
3139 // Setter with explicit barrier mode.
3140 inline void set(int index, Object* value, WriteBarrierMode mode);
3142 // Setters for frequently used oddballs located in old space.
3143 inline void set_undefined(int index);
3144 inline void set_null(int index);
3145 inline void set_the_hole(int index);
3147 inline Object** GetFirstElementAddress();
3148 inline bool ContainsOnlySmisOrHoles();
3150 // Gives access to raw memory which stores the array's data.
3151 inline Object** data_start();
3153 // Shrink length and insert filler objects.
3154 void Shrink(int length);
3157 MUST_USE_RESULT inline MaybeObject* Copy();
3158 MUST_USE_RESULT MaybeObject* CopySize(int new_length,
3159 PretenureFlag pretenure = NOT_TENURED);
3161 // Add the elements of a JSArray to this FixedArray.
3162 MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
3164 // Compute the union of this and other.
3165 MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
3167 // Copy a sub array from the receiver to dest.
3168 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
3170 // Garbage collection support.
3171 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
3173 // Code Generation support.
3174 static int OffsetOfElementAt(int index) { return SizeFor(index); }
3176 // Garbage collection support.
3177 Object** RawFieldOfElementAt(int index) {
3178 return HeapObject::RawField(this, OffsetOfElementAt(index));
3182 static inline FixedArray* cast(Object* obj);
3184 // Maximal allowed size, in bytes, of a single FixedArray.
3185 // Prevents overflowing size computations, as well as extreme memory
3187 static const int kMaxSize = 128 * MB * kPointerSize;
3188 // Maximally allowed length of a FixedArray.
3189 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
3191 // Dispatched behavior.
3192 DECLARE_PRINTER(FixedArray)
3193 DECLARE_VERIFIER(FixedArray)
3195 // Checks if two FixedArrays have identical contents.
3196 bool IsEqualTo(FixedArray* other);
3199 // Swap two elements in a pair of arrays. If this array and the
3200 // numbers array are the same object, the elements are only swapped
3202 void SwapPairs(FixedArray* numbers, int i, int j);
3204 // Sort prefix of this array and the numbers array as pairs wrt. the
3205 // numbers. If the numbers array and the this array are the same
3206 // object, the prefix of this array is sorted.
3207 void SortPairs(FixedArray* numbers, uint32_t len);
3209 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
3211 static inline int SizeOf(Map* map, HeapObject* object) {
3212 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
3217 // Set operation on FixedArray without using write barriers. Can
3218 // only be used for storing old space objects or smis.
3219 static inline void NoWriteBarrierSet(FixedArray* array,
3223 // Set operation on FixedArray without incremental write barrier. Can
3224 // only be used if the object is guaranteed to be white (whiteness witness
3226 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
3231 STATIC_CHECK(kHeaderSize == Internals::kFixedArrayHeaderSize);
3233 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
3237 // FixedDoubleArray describes fixed-sized arrays with element type double.
3238 class FixedDoubleArray: public FixedArrayBase {
3240 // Setter and getter for elements.
3241 inline double get_scalar(int index);
3242 inline int64_t get_representation(int index);
3243 MUST_USE_RESULT inline MaybeObject* get(int index);
3244 inline void set(int index, double value);
3245 inline void set_the_hole(int index);
3247 // Checking for the hole.
3248 inline bool is_the_hole(int index);
3251 MUST_USE_RESULT inline MaybeObject* Copy();
3253 // Garbage collection support.
3254 inline static int SizeFor(int length) {
3255 return kHeaderSize + length * kDoubleSize;
3258 // Gives access to raw memory which stores the array's data.
3259 inline double* data_start();
3261 // Code Generation support.
3262 static int OffsetOfElementAt(int index) { return SizeFor(index); }
3264 inline static bool is_the_hole_nan(double value);
3265 inline static double hole_nan_as_double();
3266 inline static double canonical_not_the_hole_nan_as_double();
3269 static inline FixedDoubleArray* cast(Object* obj);
3271 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
3272 // Prevents overflowing size computations, as well as extreme memory
3274 static const int kMaxSize = 512 * MB;
3275 // Maximally allowed length of a FixedArray.
3276 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
3278 // Dispatched behavior.
3279 DECLARE_PRINTER(FixedDoubleArray)
3280 DECLARE_VERIFIER(FixedDoubleArray)
3283 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
3287 // ConstantPoolArray describes a fixed-sized array containing constant pool
3289 // The format of the pool is:
3290 // [0]: Field holding the first index which is a raw code target pointer entry
3291 // [1]: Field holding the first index which is a heap pointer entry
3292 // [2]: Field holding the first index which is a int32 entry
3293 // [3] ... [first_code_ptr_index() - 1] : 64 bit entries
3294 // [first_code_ptr_index()] ... [first_heap_ptr_index() - 1] : code pointers
3295 // [first_heap_ptr_index()] ... [first_int32_index() - 1] : heap pointers
3296 // [first_int32_index()] ... [length - 1] : 32 bit entries
3297 class ConstantPoolArray: public FixedArrayBase {
3299 // Getters for the field storing the first index for different type entries.
3300 inline int first_code_ptr_index();
3301 inline int first_heap_ptr_index();
3302 inline int first_int64_index();
3303 inline int first_int32_index();
3305 // Getters for counts of different type entries.
3306 inline int count_of_code_ptr_entries();
3307 inline int count_of_heap_ptr_entries();
3308 inline int count_of_int64_entries();
3309 inline int count_of_int32_entries();
3311 // Setter and getter for pool elements.
3312 inline Address get_code_ptr_entry(int index);
3313 inline Object* get_heap_ptr_entry(int index);
3314 inline int64_t get_int64_entry(int index);
3315 inline int32_t get_int32_entry(int index);
3316 inline double get_int64_entry_as_double(int index);
3318 inline void set(int index, Address value);
3319 inline void set(int index, Object* value);
3320 inline void set(int index, int64_t value);
3321 inline void set(int index, double value);
3322 inline void set(int index, int32_t value);
3324 // Set up initial state.
3325 inline void SetEntryCounts(int number_of_int64_entries,
3326 int number_of_code_ptr_entries,
3327 int number_of_heap_ptr_entries,
3328 int number_of_int32_entries);
3331 MUST_USE_RESULT inline MaybeObject* Copy();
3333 // Garbage collection support.
3334 inline static int SizeFor(int number_of_int64_entries,
3335 int number_of_code_ptr_entries,
3336 int number_of_heap_ptr_entries,
3337 int number_of_int32_entries) {
3338 return RoundUp(OffsetAt(number_of_int64_entries,
3339 number_of_code_ptr_entries,
3340 number_of_heap_ptr_entries,
3341 number_of_int32_entries),
3345 // Code Generation support.
3346 inline int OffsetOfElementAt(int index) {
3347 ASSERT(index < length());
3348 if (index >= first_int32_index()) {
3349 return OffsetAt(count_of_int64_entries(), count_of_code_ptr_entries(),
3350 count_of_heap_ptr_entries(), index - first_int32_index());
3351 } else if (index >= first_heap_ptr_index()) {
3352 return OffsetAt(count_of_int64_entries(), count_of_code_ptr_entries(),
3353 index - first_heap_ptr_index(), 0);
3354 } else if (index >= first_code_ptr_index()) {
3355 return OffsetAt(count_of_int64_entries(), index - first_code_ptr_index(),
3358 return OffsetAt(index, 0, 0, 0);
3363 static inline ConstantPoolArray* cast(Object* obj);
3365 // Garbage collection support.
3366 Object** RawFieldOfElementAt(int index) {
3367 return HeapObject::RawField(this, OffsetOfElementAt(index));
3370 // Layout description.
3371 static const int kFirstCodePointerIndexOffset = FixedArray::kHeaderSize;
3372 static const int kFirstHeapPointerIndexOffset =
3373 kFirstCodePointerIndexOffset + kPointerSize;
3374 static const int kFirstInt32IndexOffset =
3375 kFirstHeapPointerIndexOffset + kPointerSize;
3376 static const int kFirstOffset = kFirstInt32IndexOffset + kPointerSize;
3378 // Dispatched behavior.
3379 void ConstantPoolIterateBody(ObjectVisitor* v);
3381 DECLARE_PRINTER(ConstantPoolArray)
3382 DECLARE_VERIFIER(ConstantPoolArray)
3385 inline void set_first_code_ptr_index(int value);
3386 inline void set_first_heap_ptr_index(int value);
3387 inline void set_first_int32_index(int value);
3389 inline static int OffsetAt(int number_of_int64_entries,
3390 int number_of_code_ptr_entries,
3391 int number_of_heap_ptr_entries,
3392 int number_of_int32_entries) {
3394 + (number_of_int64_entries * kInt64Size)
3395 + (number_of_code_ptr_entries * kPointerSize)
3396 + (number_of_heap_ptr_entries * kPointerSize)
3397 + (number_of_int32_entries * kInt32Size);
3400 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
3404 // DescriptorArrays are fixed arrays used to hold instance descriptors.
3405 // The format of the these objects is:
3406 // [0]: Number of descriptors
3407 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
3408 // [0]: pointer to fixed array with enum cache
3409 // [1]: either Smi(0) or pointer to fixed array with indices
3411 // [2 + number of descriptors * kDescriptorSize]: start of slack
3412 class DescriptorArray: public FixedArray {
3414 // WhitenessWitness is used to prove that a descriptor array is white
3415 // (unmarked), so incremental write barriers can be skipped because the
3416 // marking invariant cannot be broken and slots pointing into evacuation
3417 // candidates will be discovered when the object is scanned. A witness is
3418 // always stack-allocated right after creating an array. By allocating a
3419 // witness, incremental marking is globally disabled. The witness is then
3420 // passed along wherever needed to statically prove that the array is known to
3422 class WhitenessWitness {
3424 inline explicit WhitenessWitness(FixedArray* array);
3425 inline ~WhitenessWitness();
3428 IncrementalMarking* marking_;
3431 // Returns true for both shared empty_descriptor_array and for smis, which the
3432 // map uses to encode additional bit fields when the descriptor array is not
3434 inline bool IsEmpty();
3436 // Returns the number of descriptors in the array.
3437 int number_of_descriptors() {
3438 ASSERT(length() >= kFirstIndex || IsEmpty());
3440 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
3443 int number_of_descriptors_storage() {
3445 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
3448 int NumberOfSlackDescriptors() {
3449 return number_of_descriptors_storage() - number_of_descriptors();
3452 inline void SetNumberOfDescriptors(int number_of_descriptors);
3453 inline int number_of_entries() { return number_of_descriptors(); }
3455 bool HasEnumCache() {
3456 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
3459 void CopyEnumCacheFrom(DescriptorArray* array) {
3460 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
3463 FixedArray* GetEnumCache() {
3464 ASSERT(HasEnumCache());
3465 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3466 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
3469 bool HasEnumIndicesCache() {
3470 if (IsEmpty()) return false;
3471 Object* object = get(kEnumCacheIndex);
3472 if (object->IsSmi()) return false;
3473 FixedArray* bridge = FixedArray::cast(object);
3474 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
3477 FixedArray* GetEnumIndicesCache() {
3478 ASSERT(HasEnumIndicesCache());
3479 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3480 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
3483 Object** GetEnumCacheSlot() {
3484 ASSERT(HasEnumCache());
3485 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
3489 void ClearEnumCache();
3491 // Initialize or change the enum cache,
3492 // using the supplied storage for the small "bridge".
3493 void SetEnumCache(FixedArray* bridge_storage,
3494 FixedArray* new_cache,
3495 Object* new_index_cache);
3497 // Accessors for fetching instance descriptor at descriptor number.
3498 inline Name* GetKey(int descriptor_number);
3499 inline Object** GetKeySlot(int descriptor_number);
3500 inline Object* GetValue(int descriptor_number);
3501 inline Object** GetValueSlot(int descriptor_number);
3502 inline Object** GetDescriptorStartSlot(int descriptor_number);
3503 inline Object** GetDescriptorEndSlot(int descriptor_number);
3504 inline PropertyDetails GetDetails(int descriptor_number);
3505 inline PropertyType GetType(int descriptor_number);
3506 inline int GetFieldIndex(int descriptor_number);
3507 inline Object* GetConstant(int descriptor_number);
3508 inline Object* GetCallbacksObject(int descriptor_number);
3509 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3511 inline Name* GetSortedKey(int descriptor_number);
3512 inline int GetSortedKeyIndex(int descriptor_number);
3513 inline void SetSortedKey(int pointer, int descriptor_number);
3514 inline void InitializeRepresentations(Representation representation);
3515 inline void SetRepresentation(int descriptor_number,
3516 Representation representation);
3518 // Accessor for complete descriptor.
3519 inline void Get(int descriptor_number, Descriptor* desc);
3520 inline void Set(int descriptor_number,
3522 const WhitenessWitness&);
3523 inline void Set(int descriptor_number, Descriptor* desc);
3525 // Append automatically sets the enumeration index. This should only be used
3526 // to add descriptors in bulk at the end, followed by sorting the descriptor
3528 inline void Append(Descriptor* desc, const WhitenessWitness&);
3529 inline void Append(Descriptor* desc);
3531 // Transfer a complete descriptor from the src descriptor array to this
3532 // descriptor array.
3533 void CopyFrom(int dst_index,
3534 DescriptorArray* src,
3536 const WhitenessWitness&);
3537 static Handle<DescriptorArray> Merge(Handle<DescriptorArray> desc,
3542 StoreMode store_mode,
3543 Handle<DescriptorArray> other);
3544 MUST_USE_RESULT MaybeObject* Merge(int verbatim,
3548 StoreMode store_mode,
3549 DescriptorArray* other);
3551 bool IsMoreGeneralThan(int verbatim,
3554 DescriptorArray* other);
3556 MUST_USE_RESULT MaybeObject* CopyUpTo(int enumeration_index) {
3557 return CopyUpToAddAttributes(enumeration_index, NONE);
3560 static Handle<DescriptorArray> CopyUpToAddAttributes(
3561 Handle<DescriptorArray> desc,
3562 int enumeration_index,
3563 PropertyAttributes attributes);
3564 MUST_USE_RESULT MaybeObject* CopyUpToAddAttributes(
3565 int enumeration_index,
3566 PropertyAttributes attributes);
3568 // Sort the instance descriptors by the hash codes of their keys.
3571 // Search the instance descriptors for given name.
3572 INLINE(int Search(Name* name, int number_of_own_descriptors));
3574 // As the above, but uses DescriptorLookupCache and updates it when
3576 INLINE(int SearchWithCache(Name* name, Map* map));
3578 // Allocates a DescriptorArray, but returns the singleton
3579 // empty descriptor array object if number_of_descriptors is 0.
3580 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
3581 int number_of_descriptors,
3585 static inline DescriptorArray* cast(Object* obj);
3587 // Constant for denoting key was not found.
3588 static const int kNotFound = -1;
3590 static const int kDescriptorLengthIndex = 0;
3591 static const int kEnumCacheIndex = 1;
3592 static const int kFirstIndex = 2;
3594 // The length of the "bridge" to the enum cache.
3595 static const int kEnumCacheBridgeLength = 2;
3596 static const int kEnumCacheBridgeCacheIndex = 0;
3597 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3599 // Layout description.
3600 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3601 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3602 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3604 // Layout description for the bridge array.
3605 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3607 // Layout of descriptor.
3608 static const int kDescriptorKey = 0;
3609 static const int kDescriptorDetails = 1;
3610 static const int kDescriptorValue = 2;
3611 static const int kDescriptorSize = 3;
3614 // Print all the descriptors.
3615 void PrintDescriptors(FILE* out = stdout);
3619 // Is the descriptor array sorted and without duplicates?
3620 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3622 // Is the descriptor array consistent with the back pointers in targets?
3623 bool IsConsistentWithBackPointers(Map* current_map);
3625 // Are two DescriptorArrays equal?
3626 bool IsEqualTo(DescriptorArray* other);
3629 // Returns the fixed array length required to hold number_of_descriptors
3631 static int LengthFor(int number_of_descriptors) {
3632 return ToKeyIndex(number_of_descriptors);
3636 // An entry in a DescriptorArray, represented as an (array, index) pair.
3639 inline explicit Entry(DescriptorArray* descs, int index) :
3640 descs_(descs), index_(index) { }
3642 inline PropertyType type() { return descs_->GetType(index_); }
3643 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3646 DescriptorArray* descs_;
3650 // Conversion from descriptor number to array indices.
3651 static int ToKeyIndex(int descriptor_number) {
3652 return kFirstIndex +
3653 (descriptor_number * kDescriptorSize) +
3657 static int ToDetailsIndex(int descriptor_number) {
3658 return kFirstIndex +
3659 (descriptor_number * kDescriptorSize) +
3663 static int ToValueIndex(int descriptor_number) {
3664 return kFirstIndex +
3665 (descriptor_number * kDescriptorSize) +
3669 // Swap first and second descriptor.
3670 inline void SwapSortedKeys(int first, int second);
3672 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3676 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3678 template<SearchMode search_mode, typename T>
3679 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3682 template<SearchMode search_mode, typename T>
3683 inline int Search(T* array, Name* name, int valid_entries = 0);
3686 // HashTable is a subclass of FixedArray that implements a hash table
3687 // that uses open addressing and quadratic probing.
3689 // In order for the quadratic probing to work, elements that have not
3690 // yet been used and elements that have been deleted are
3691 // distinguished. Probing continues when deleted elements are
3692 // encountered and stops when unused elements are encountered.
3694 // - Elements with key == undefined have not been used yet.
3695 // - Elements with key == the_hole have been deleted.
3697 // The hash table class is parameterized with a Shape and a Key.
3698 // Shape must be a class with the following interface:
3699 // class ExampleShape {
3701 // // Tells whether key matches other.
3702 // static bool IsMatch(Key key, Object* other);
3703 // // Returns the hash value for key.
3704 // static uint32_t Hash(Key key);
3705 // // Returns the hash value for object.
3706 // static uint32_t HashForObject(Key key, Object* object);
3707 // // Convert key to an object.
3708 // static inline Object* AsObject(Heap* heap, Key key);
3709 // // The prefix size indicates number of elements in the beginning
3710 // // of the backing storage.
3711 // static const int kPrefixSize = ..;
3712 // // The Element size indicates number of elements per entry.
3713 // static const int kEntrySize = ..;
3715 // The prefix size indicates an amount of memory in the
3716 // beginning of the backing storage that can be used for non-element
3717 // information by subclasses.
3719 template<typename Key>
3722 static const bool UsesSeed = false;
3723 static uint32_t Hash(Key key) { return 0; }
3724 static uint32_t SeededHash(Key key, uint32_t seed) {
3728 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3729 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3731 return HashForObject(key, object);
3735 template<typename Shape, typename Key>
3736 class HashTable: public FixedArray {
3739 inline uint32_t Hash(Key key) {
3740 if (Shape::UsesSeed) {
3741 return Shape::SeededHash(key,
3742 GetHeap()->HashSeed());
3744 return Shape::Hash(key);
3748 inline uint32_t HashForObject(Key key, Object* object) {
3749 if (Shape::UsesSeed) {
3750 return Shape::SeededHashForObject(key,
3751 GetHeap()->HashSeed(), object);
3753 return Shape::HashForObject(key, object);
3757 // Returns the number of elements in the hash table.
3758 int NumberOfElements() {
3759 return Smi::cast(get(kNumberOfElementsIndex))->value();
3762 // Returns the number of deleted elements in the hash table.
3763 int NumberOfDeletedElements() {
3764 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3767 // Returns the capacity of the hash table.
3769 return Smi::cast(get(kCapacityIndex))->value();
3772 // ElementAdded should be called whenever an element is added to a
3774 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3776 // ElementRemoved should be called whenever an element is removed from
3778 void ElementRemoved() {
3779 SetNumberOfElements(NumberOfElements() - 1);
3780 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3782 void ElementsRemoved(int n) {
3783 SetNumberOfElements(NumberOfElements() - n);
3784 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3787 // Returns a new HashTable object. Might return Failure.
3788 MUST_USE_RESULT static MaybeObject* Allocate(
3790 int at_least_space_for,
3791 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3792 PretenureFlag pretenure = NOT_TENURED);
3794 // Computes the required capacity for a table holding the given
3795 // number of elements. May be more than HashTable::kMaxCapacity.
3796 static int ComputeCapacity(int at_least_space_for);
3798 // Returns the key at entry.
3799 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3801 // Tells whether k is a real key. The hole and undefined are not allowed
3802 // as keys and can be used to indicate missing or deleted elements.
3803 bool IsKey(Object* k) {
3804 return !k->IsTheHole() && !k->IsUndefined();
3807 // Garbage collection support.
3808 void IteratePrefix(ObjectVisitor* visitor);
3809 void IterateElements(ObjectVisitor* visitor);
3812 static inline HashTable* cast(Object* obj);
3814 // Compute the probe offset (quadratic probing).
3815 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3816 return (n + n * n) >> 1;
3819 static const int kNumberOfElementsIndex = 0;
3820 static const int kNumberOfDeletedElementsIndex = 1;
3821 static const int kCapacityIndex = 2;
3822 static const int kPrefixStartIndex = 3;
3823 static const int kElementsStartIndex =
3824 kPrefixStartIndex + Shape::kPrefixSize;
3825 static const int kEntrySize = Shape::kEntrySize;
3826 static const int kElementsStartOffset =
3827 kHeaderSize + kElementsStartIndex * kPointerSize;
3828 static const int kCapacityOffset =
3829 kHeaderSize + kCapacityIndex * kPointerSize;
3831 // Constant used for denoting a absent entry.
3832 static const int kNotFound = -1;
3834 // Maximal capacity of HashTable. Based on maximal length of underlying
3835 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3837 static const int kMaxCapacity =
3838 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3840 // Find entry for key otherwise return kNotFound.
3841 inline int FindEntry(Key key);
3842 int FindEntry(Isolate* isolate, Key key);
3844 // Rehashes the table in-place.
3845 void Rehash(Key key);
3848 friend class ObjectHashSet;
3849 friend class ObjectHashTable;
3851 // Find the entry at which to insert element with the given key that
3852 // has the given hash value.
3853 uint32_t FindInsertionEntry(uint32_t hash);
3855 // Returns the index for an entry (of the key)
3856 static inline int EntryToIndex(int entry) {
3857 return (entry * kEntrySize) + kElementsStartIndex;
3860 // Update the number of elements in the hash table.
3861 void SetNumberOfElements(int nof) {
3862 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3865 // Update the number of deleted elements in the hash table.
3866 void SetNumberOfDeletedElements(int nod) {
3867 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3870 // Sets the capacity of the hash table.
3871 void SetCapacity(int capacity) {
3872 // To scale a computed hash code to fit within the hash table, we
3873 // use bit-wise AND with a mask, so the capacity must be positive
3875 ASSERT(capacity > 0);
3876 ASSERT(capacity <= kMaxCapacity);
3877 set(kCapacityIndex, Smi::FromInt(capacity));
3881 // Returns probe entry.
3882 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3883 ASSERT(IsPowerOf2(size));
3884 return (hash + GetProbeOffset(number)) & (size - 1);
3887 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3888 return hash & (size - 1);
3891 inline static uint32_t NextProbe(
3892 uint32_t last, uint32_t number, uint32_t size) {
3893 return (last + number) & (size - 1);
3896 // Returns _expected_ if one of entries given by the first _probe_ probes is
3897 // equal to _expected_. Otherwise, returns the entry given by the probe
3899 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3901 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3903 // Rehashes this hash-table into the new table.
3904 MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
3906 // Attempt to shrink hash table after removal of key.
3907 MUST_USE_RESULT MaybeObject* Shrink(Key key);
3909 // Ensure enough space for n additional elements.
3910 MUST_USE_RESULT MaybeObject* EnsureCapacity(
3913 PretenureFlag pretenure = NOT_TENURED);
3917 // HashTableKey is an abstract superclass for virtual key behavior.
3918 class HashTableKey {
3920 // Returns whether the other object matches this key.
3921 virtual bool IsMatch(Object* other) = 0;
3922 // Returns the hash value for this key.
3923 virtual uint32_t Hash() = 0;
3924 // Returns the hash value for object.
3925 virtual uint32_t HashForObject(Object* key) = 0;
3926 // Returns the key object for storing into the hash table.
3927 // If allocations fails a failure object is returned.
3928 MUST_USE_RESULT virtual MaybeObject* AsObject(Heap* heap) = 0;
3930 virtual ~HashTableKey() {}
3934 class StringTableShape : public BaseShape<HashTableKey*> {
3936 static inline bool IsMatch(HashTableKey* key, Object* value) {
3937 return key->IsMatch(value);
3939 static inline uint32_t Hash(HashTableKey* key) {
3942 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3943 return key->HashForObject(object);
3945 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3946 HashTableKey* key) {
3947 return key->AsObject(heap);
3950 static const int kPrefixSize = 0;
3951 static const int kEntrySize = 1;
3954 class SeqOneByteString;
3958 // No special elements in the prefix and the element size is 1
3959 // because only the string itself (the key) needs to be stored.
3960 class StringTable: public HashTable<StringTableShape, HashTableKey*> {
3962 // Find string in the string table. If it is not there yet, it is
3963 // added. The return value is the string table which might have
3964 // been enlarged. If the return value is not a failure, the string
3965 // pointer *s is set to the string found.
3966 MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
3967 MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
3969 // Looks up a string that is equal to the given string and returns
3970 // true if it is found, assigning the string to the given output
3972 bool LookupStringIfExists(String* str, String** result);
3973 bool LookupTwoCharsStringIfExists(uint16_t c1, uint16_t c2, String** result);
3976 static inline StringTable* cast(Object* obj);
3979 template <bool seq_ascii> friend class JsonParser;
3981 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3985 class MapCacheShape : public BaseShape<HashTableKey*> {
3987 static inline bool IsMatch(HashTableKey* key, Object* value) {
3988 return key->IsMatch(value);
3990 static inline uint32_t Hash(HashTableKey* key) {
3994 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3995 return key->HashForObject(object);
3998 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3999 HashTableKey* key) {
4000 return key->AsObject(heap);
4003 static const int kPrefixSize = 0;
4004 static const int kEntrySize = 2;
4010 // Maps keys that are a fixed array of unique names to a map.
4011 // Used for canonicalize maps for object literals.
4012 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
4014 // Find cached value for a name key, otherwise return null.
4015 Object* Lookup(FixedArray* key);
4016 MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
4017 static inline MapCache* cast(Object* obj);
4020 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
4024 template <typename Shape, typename Key>
4025 class Dictionary: public HashTable<Shape, Key> {
4027 static inline Dictionary<Shape, Key>* cast(Object* obj) {
4028 return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
4031 // Returns the value at entry.
4032 Object* ValueAt(int entry) {
4033 return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
4036 // Set the value for entry.
4037 void ValueAtPut(int entry, Object* value) {
4038 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
4041 // Returns the property details for the property at entry.
4042 PropertyDetails DetailsAt(int entry) {
4043 ASSERT(entry >= 0); // Not found is -1, which is not caught by get().
4044 return PropertyDetails(
4045 Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
4048 // Set the details for entry.
4049 void DetailsAtPut(int entry, PropertyDetails value) {
4050 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
4054 void CopyValuesTo(FixedArray* elements);
4056 // Delete a property from the dictionary.
4057 Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
4059 // Attempt to shrink the dictionary after deletion of key.
4060 MUST_USE_RESULT MaybeObject* Shrink(Key key);
4062 // Returns the number of elements in the dictionary filtering out properties
4063 // with the specified attributes.
4064 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
4066 // Returns the number of enumerable elements in the dictionary.
4067 int NumberOfEnumElements();
4069 enum SortMode { UNSORTED, SORTED };
4070 // Copies keys to preallocated fixed array.
4071 void CopyKeysTo(FixedArray* storage,
4072 PropertyAttributes filter,
4073 SortMode sort_mode);
4074 // Fill in details for properties into storage.
4075 void CopyKeysTo(FixedArray* storage,
4077 PropertyAttributes filter,
4078 SortMode sort_mode);
4080 // Accessors for next enumeration index.
4081 void SetNextEnumerationIndex(int index) {
4083 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
4086 int NextEnumerationIndex() {
4087 return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
4090 // Returns a new array for dictionary usage. Might return Failure.
4091 MUST_USE_RESULT static MaybeObject* Allocate(
4093 int at_least_space_for,
4094 PretenureFlag pretenure = NOT_TENURED);
4096 // Ensure enough space for n additional elements.
4097 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
4100 void Print(FILE* out = stdout);
4102 // Returns the key (slow).
4103 Object* SlowReverseLookup(Object* value);
4105 // Sets the entry to (key, value) pair.
4106 inline void SetEntry(int entry,
4109 inline void SetEntry(int entry,
4112 PropertyDetails details);
4114 MUST_USE_RESULT MaybeObject* Add(Key key,
4116 PropertyDetails details);
4119 // Generic at put operation.
4120 MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
4122 // Add entry to dictionary.
4123 MUST_USE_RESULT MaybeObject* AddEntry(Key key,
4125 PropertyDetails details,
4128 // Generate new enumeration indices to avoid enumeration index overflow.
4129 MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
4130 static const int kMaxNumberKeyIndex =
4131 HashTable<Shape, Key>::kPrefixStartIndex;
4132 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
4136 class NameDictionaryShape : public BaseShape<Name*> {
4138 static inline bool IsMatch(Name* key, Object* other);
4139 static inline uint32_t Hash(Name* key);
4140 static inline uint32_t HashForObject(Name* key, Object* object);
4141 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4143 static const int kPrefixSize = 2;
4144 static const int kEntrySize = 3;
4145 static const bool kIsEnumerable = true;
4149 class NameDictionary: public Dictionary<NameDictionaryShape, Name*> {
4151 static inline NameDictionary* cast(Object* obj) {
4152 ASSERT(obj->IsDictionary());
4153 return reinterpret_cast<NameDictionary*>(obj);
4156 // Copies enumerable keys to preallocated fixed array.
4157 void CopyEnumKeysTo(FixedArray* storage);
4158 static void DoGenerateNewEnumerationIndices(
4159 Handle<NameDictionary> dictionary);
4161 // For transforming properties of a JSObject.
4162 MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
4164 int unused_property_fields);
4166 // Find entry for key, otherwise return kNotFound. Optimized version of
4167 // HashTable::FindEntry.
4168 int FindEntry(Name* key);
4172 class NumberDictionaryShape : public BaseShape<uint32_t> {
4174 static inline bool IsMatch(uint32_t key, Object* other);
4175 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4177 static const int kEntrySize = 3;
4178 static const bool kIsEnumerable = false;
4182 class SeededNumberDictionaryShape : public NumberDictionaryShape {
4184 static const bool UsesSeed = true;
4185 static const int kPrefixSize = 2;
4187 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
4188 static inline uint32_t SeededHashForObject(uint32_t key,
4194 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
4196 static const int kPrefixSize = 0;
4198 static inline uint32_t Hash(uint32_t key);
4199 static inline uint32_t HashForObject(uint32_t key, Object* object);
4203 class SeededNumberDictionary
4204 : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
4206 static SeededNumberDictionary* cast(Object* obj) {
4207 ASSERT(obj->IsDictionary());
4208 return reinterpret_cast<SeededNumberDictionary*>(obj);
4211 // Type specific at put (default NONE attributes is used when adding).
4212 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4213 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
4214 Handle<SeededNumberDictionary> dictionary,
4216 Handle<Object> value,
4217 PropertyDetails details);
4218 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
4220 PropertyDetails details);
4222 // Set an existing entry or add a new one if needed.
4223 // Return the updated dictionary.
4224 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
4225 Handle<SeededNumberDictionary> dictionary,
4227 Handle<Object> value,
4228 PropertyDetails details);
4230 MUST_USE_RESULT MaybeObject* Set(uint32_t key,
4232 PropertyDetails details);
4234 void UpdateMaxNumberKey(uint32_t key);
4236 // If slow elements are required we will never go back to fast-case
4237 // for the elements kept in this dictionary. We require slow
4238 // elements if an element has been added at an index larger than
4239 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
4240 // when defining a getter or setter with a number key.
4241 inline bool requires_slow_elements();
4242 inline void set_requires_slow_elements();
4244 // Get the value of the max number key that has been added to this
4245 // dictionary. max_number_key can only be called if
4246 // requires_slow_elements returns false.
4247 inline uint32_t max_number_key();
4250 static const int kRequiresSlowElementsMask = 1;
4251 static const int kRequiresSlowElementsTagSize = 1;
4252 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
4256 class UnseededNumberDictionary
4257 : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
4259 static UnseededNumberDictionary* cast(Object* obj) {
4260 ASSERT(obj->IsDictionary());
4261 return reinterpret_cast<UnseededNumberDictionary*>(obj);
4264 // Type specific at put (default NONE attributes is used when adding).
4265 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4266 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
4268 // Set an existing entry or add a new one if needed.
4269 // Return the updated dictionary.
4270 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
4271 Handle<UnseededNumberDictionary> dictionary,
4273 Handle<Object> value);
4275 MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
4279 template <int entrysize>
4280 class ObjectHashTableShape : public BaseShape<Object*> {
4282 static inline bool IsMatch(Object* key, Object* other);
4283 static inline uint32_t Hash(Object* key);
4284 static inline uint32_t HashForObject(Object* key, Object* object);
4285 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4287 static const int kPrefixSize = 0;
4288 static const int kEntrySize = entrysize;
4292 // ObjectHashSet holds keys that are arbitrary objects by using the identity
4293 // hash of the key for hashing purposes.
4294 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
4296 static inline ObjectHashSet* cast(Object* obj) {
4297 ASSERT(obj->IsHashTable());
4298 return reinterpret_cast<ObjectHashSet*>(obj);
4301 // Looks up whether the given key is part of this hash set.
4302 bool Contains(Object* key);
4304 static Handle<ObjectHashSet> EnsureCapacity(
4305 Handle<ObjectHashSet> table,
4308 PretenureFlag pretenure = NOT_TENURED);
4310 // Attempt to shrink hash table after removal of key.
4311 static Handle<ObjectHashSet> Shrink(Handle<ObjectHashSet> table,
4312 Handle<Object> key);
4314 // Adds the given key to this hash set.
4315 static Handle<ObjectHashSet> Add(Handle<ObjectHashSet> table,
4316 Handle<Object> key);
4318 // Removes the given key from this hash set.
4319 static Handle<ObjectHashSet> Remove(Handle<ObjectHashSet> table,
4320 Handle<Object> key);
4324 // ObjectHashTable maps keys that are arbitrary objects to object values by
4325 // using the identity hash of the key for hashing purposes.
4326 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
4328 static inline ObjectHashTable* cast(Object* obj) {
4329 ASSERT(obj->IsHashTable());
4330 return reinterpret_cast<ObjectHashTable*>(obj);
4333 static Handle<ObjectHashTable> EnsureCapacity(
4334 Handle<ObjectHashTable> table,
4337 PretenureFlag pretenure = NOT_TENURED);
4339 // Attempt to shrink hash table after removal of key.
4340 static Handle<ObjectHashTable> Shrink(Handle<ObjectHashTable> table,
4341 Handle<Object> key);
4343 // Looks up the value associated with the given key. The hole value is
4344 // returned in case the key is not present.
4345 Object* Lookup(Object* key);
4347 // Adds (or overwrites) the value associated with the given key. Mapping a
4348 // key to the hole value causes removal of the whole entry.
4349 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
4351 Handle<Object> value);
4354 friend class MarkCompactCollector;
4356 void AddEntry(int entry, Object* key, Object* value);
4357 void RemoveEntry(int entry);
4359 // Returns the index to the value of an entry.
4360 static inline int EntryToValueIndex(int entry) {
4361 return EntryToIndex(entry) + 1;
4366 template <int entrysize>
4367 class WeakHashTableShape : public BaseShape<Object*> {
4369 static inline bool IsMatch(Object* key, Object* other);
4370 static inline uint32_t Hash(Object* key);
4371 static inline uint32_t HashForObject(Object* key, Object* object);
4372 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4374 static const int kPrefixSize = 0;
4375 static const int kEntrySize = entrysize;
4379 // WeakHashTable maps keys that are arbitrary objects to object values.
4380 // It is used for the global weak hash table that maps objects
4381 // embedded in optimized code to dependent code lists.
4382 class WeakHashTable: public HashTable<WeakHashTableShape<2>, Object*> {
4384 static inline WeakHashTable* cast(Object* obj) {
4385 ASSERT(obj->IsHashTable());
4386 return reinterpret_cast<WeakHashTable*>(obj);
4389 // Looks up the value associated with the given key. The hole value is
4390 // returned in case the key is not present.
4391 Object* Lookup(Object* key);
4393 // Adds (or overwrites) the value associated with the given key. Mapping a
4394 // key to the hole value causes removal of the whole entry.
4395 MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
4397 // This function is called when heap verification is turned on.
4398 void Zap(Object* value) {
4399 int capacity = Capacity();
4400 for (int i = 0; i < capacity; i++) {
4401 set(EntryToIndex(i), value);
4402 set(EntryToValueIndex(i), value);
4407 friend class MarkCompactCollector;
4409 void AddEntry(int entry, Object* key, Object* value);
4411 // Returns the index to the value of an entry.
4412 static inline int EntryToValueIndex(int entry) {
4413 return EntryToIndex(entry) + 1;
4418 // JSFunctionResultCache caches results of some JSFunction invocation.
4419 // It is a fixed array with fixed structure:
4420 // [0]: factory function
4421 // [1]: finger index
4422 // [2]: current cache size
4423 // [3]: dummy field.
4424 // The rest of array are key/value pairs.
4425 class JSFunctionResultCache: public FixedArray {
4427 static const int kFactoryIndex = 0;
4428 static const int kFingerIndex = kFactoryIndex + 1;
4429 static const int kCacheSizeIndex = kFingerIndex + 1;
4430 static const int kDummyIndex = kCacheSizeIndex + 1;
4431 static const int kEntriesIndex = kDummyIndex + 1;
4433 static const int kEntrySize = 2; // key + value
4435 static const int kFactoryOffset = kHeaderSize;
4436 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4437 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4439 inline void MakeZeroSize();
4440 inline void Clear();
4443 inline void set_size(int size);
4444 inline int finger_index();
4445 inline void set_finger_index(int finger_index);
4448 static inline JSFunctionResultCache* cast(Object* obj);
4450 DECLARE_VERIFIER(JSFunctionResultCache)
4454 // ScopeInfo represents information about different scopes of a source
4455 // program and the allocation of the scope's variables. Scope information
4456 // is stored in a compressed form in ScopeInfo objects and is used
4457 // at runtime (stack dumps, deoptimization, etc.).
4459 // This object provides quick access to scope info details for runtime
4461 class ScopeInfo : public FixedArray {
4463 static inline ScopeInfo* cast(Object* object);
4465 // Return the type of this scope.
4466 ScopeType scope_type();
4468 // Does this scope call eval?
4471 // Return the strict mode of this scope.
4472 StrictMode strict_mode();
4474 // Does this scope make a sloppy eval call?
4475 bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4477 // Return the total number of locals allocated on the stack and in the
4478 // context. This includes the parameters that are allocated in the context.
4481 // Return the number of stack slots for code. This number consists of two
4483 // 1. One stack slot per stack allocated local.
4484 // 2. One stack slot for the function name if it is stack allocated.
4485 int StackSlotCount();
4487 // Return the number of context slots for code if a context is allocated. This
4488 // number consists of three parts:
4489 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4490 // 2. One context slot per context allocated local.
4491 // 3. One context slot for the function name if it is context allocated.
4492 // Parameters allocated in the context count as context allocated locals. If
4493 // no contexts are allocated for this scope ContextLength returns 0.
4494 int ContextLength();
4496 // Is this scope the scope of a named function expression?
4497 bool HasFunctionName();
4499 // Return if this has context allocated locals.
4500 bool HasHeapAllocatedLocals();
4502 // Return if contexts are allocated for this scope.
4505 // Return the function_name if present.
4506 String* FunctionName();
4508 // Return the name of the given parameter.
4509 String* ParameterName(int var);
4511 // Return the name of the given local.
4512 String* LocalName(int var);
4514 // Return the name of the given stack local.
4515 String* StackLocalName(int var);
4517 // Return the name of the given context local.
4518 String* ContextLocalName(int var);
4520 // Return the mode of the given context local.
4521 VariableMode ContextLocalMode(int var);
4523 // Return the initialization flag of the given context local.
4524 InitializationFlag ContextLocalInitFlag(int var);
4526 // Lookup support for serialized scope info. Returns the
4527 // the stack slot index for a given slot name if the slot is
4528 // present; otherwise returns a value < 0. The name must be an internalized
4530 int StackSlotIndex(String* name);
4532 // Lookup support for serialized scope info. Returns the
4533 // context slot index for a given slot name if the slot is present; otherwise
4534 // returns a value < 0. The name must be an internalized string.
4535 // If the slot is present and mode != NULL, sets *mode to the corresponding
4536 // mode for that variable.
4537 int ContextSlotIndex(String* name,
4539 InitializationFlag* init_flag);
4541 // Lookup support for serialized scope info. Returns the
4542 // parameter index for a given parameter name if the parameter is present;
4543 // otherwise returns a value < 0. The name must be an internalized string.
4544 int ParameterIndex(String* name);
4546 // Lookup support for serialized scope info. Returns the function context
4547 // slot index if the function name is present and context-allocated (named
4548 // function expressions, only), otherwise returns a value < 0. The name
4549 // must be an internalized string.
4550 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4553 // Copies all the context locals into an object used to materialize a scope.
4554 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4555 Handle<Context> context,
4556 Handle<JSObject> scope_object);
4559 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4561 // Serializes empty scope info.
4562 static ScopeInfo* Empty(Isolate* isolate);
4568 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4569 // numeric and occupies one array slot.
4570 // 1. A set of properties of the scope
4571 // 2. The number of parameters. This only applies to function scopes. For
4572 // non-function scopes this is 0.
4573 // 3. The number of non-parameter variables allocated on the stack.
4574 // 4. The number of non-parameter and parameter variables allocated in the
4576 #define FOR_EACH_NUMERIC_FIELD(V) \
4579 V(StackLocalCount) \
4580 V(ContextLocalCount)
4582 #define FIELD_ACCESSORS(name) \
4583 void Set##name(int value) { \
4584 set(k##name, Smi::FromInt(value)); \
4587 if (length() > 0) { \
4588 return Smi::cast(get(k##name))->value(); \
4593 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4594 #undef FIELD_ACCESSORS
4598 #define DECL_INDEX(name) k##name,
4599 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4601 #undef FOR_EACH_NUMERIC_FIELD
4605 // The layout of the variable part of a ScopeInfo is as follows:
4606 // 1. ParameterEntries:
4607 // This part stores the names of the parameters for function scopes. One
4608 // slot is used per parameter, so in total this part occupies
4609 // ParameterCount() slots in the array. For other scopes than function
4610 // scopes ParameterCount() is 0.
4611 // 2. StackLocalEntries:
4612 // Contains the names of local variables that are allocated on the stack,
4613 // in increasing order of the stack slot index. One slot is used per stack
4614 // local, so in total this part occupies StackLocalCount() slots in the
4616 // 3. ContextLocalNameEntries:
4617 // Contains the names of local variables and parameters that are allocated
4618 // in the context. They are stored in increasing order of the context slot
4619 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4620 // context local, so in total this part occupies ContextLocalCount() slots
4622 // 4. ContextLocalInfoEntries:
4623 // Contains the variable modes and initialization flags corresponding to
4624 // the context locals in ContextLocalNameEntries. One slot is used per
4625 // context local, so in total this part occupies ContextLocalCount()
4626 // slots in the array.
4627 // 5. FunctionNameEntryIndex:
4628 // If the scope belongs to a named function expression this part contains
4629 // information about the function variable. It always occupies two array
4630 // slots: a. The name of the function variable.
4631 // b. The context or stack slot index for the variable.
4632 int ParameterEntriesIndex();
4633 int StackLocalEntriesIndex();
4634 int ContextLocalNameEntriesIndex();
4635 int ContextLocalInfoEntriesIndex();
4636 int FunctionNameEntryIndex();
4638 // Location of the function variable for named function expressions.
4639 enum FunctionVariableInfo {
4640 NONE, // No function name present.
4646 // Properties of scopes.
4647 class ScopeTypeField: public BitField<ScopeType, 0, 3> {};
4648 class CallsEvalField: public BitField<bool, 3, 1> {};
4649 class StrictModeField: public BitField<StrictMode, 4, 1> {};
4650 class FunctionVariableField: public BitField<FunctionVariableInfo, 5, 2> {};
4651 class FunctionVariableMode: public BitField<VariableMode, 7, 3> {};
4653 // BitFields representing the encoded information for context locals in the
4654 // ContextLocalInfoEntries part.
4655 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4656 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4660 // The cache for maps used by normalized (dictionary mode) objects.
4661 // Such maps do not have property descriptors, so a typical program
4662 // needs very limited number of distinct normalized maps.
4663 class NormalizedMapCache: public FixedArray {
4665 static const int kEntries = 64;
4667 static Handle<Map> Get(Handle<NormalizedMapCache> cache,
4668 Handle<JSObject> object,
4669 PropertyNormalizationMode mode);
4674 static inline NormalizedMapCache* cast(Object* obj);
4676 DECLARE_VERIFIER(NormalizedMapCache)
4680 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4681 // that is attached to code objects.
4682 class ByteArray: public FixedArrayBase {
4684 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4686 // Setter and getter.
4687 inline byte get(int index);
4688 inline void set(int index, byte value);
4690 // Treat contents as an int array.
4691 inline int get_int(int index);
4693 static int SizeFor(int length) {
4694 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4696 // We use byte arrays for free blocks in the heap. Given a desired size in
4697 // bytes that is a multiple of the word size and big enough to hold a byte
4698 // array, this function returns the number of elements a byte array should
4700 static int LengthFor(int size_in_bytes) {
4701 ASSERT(IsAligned(size_in_bytes, kPointerSize));
4702 ASSERT(size_in_bytes >= kHeaderSize);
4703 return size_in_bytes - kHeaderSize;
4706 // Returns data start address.
4707 inline Address GetDataStartAddress();
4709 // Returns a pointer to the ByteArray object for a given data start address.
4710 static inline ByteArray* FromDataStartAddress(Address address);
4713 static inline ByteArray* cast(Object* obj);
4715 // Dispatched behavior.
4716 inline int ByteArraySize() {
4717 return SizeFor(this->length());
4719 DECLARE_PRINTER(ByteArray)
4720 DECLARE_VERIFIER(ByteArray)
4722 // Layout description.
4723 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4725 // Maximal memory consumption for a single ByteArray.
4726 static const int kMaxSize = 512 * MB;
4727 // Maximal length of a single ByteArray.
4728 static const int kMaxLength = kMaxSize - kHeaderSize;
4731 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4735 // FreeSpace represents fixed sized areas of the heap that are not currently in
4736 // use. Used by the heap and GC.
4737 class FreeSpace: public HeapObject {
4739 // [size]: size of the free space including the header.
4741 inline void set_size(int value);
4743 inline int Size() { return size(); }
4746 static inline FreeSpace* cast(Object* obj);
4748 // Dispatched behavior.
4749 DECLARE_PRINTER(FreeSpace)
4750 DECLARE_VERIFIER(FreeSpace)
4752 // Layout description.
4753 // Size is smi tagged when it is stored.
4754 static const int kSizeOffset = HeapObject::kHeaderSize;
4755 static const int kHeaderSize = kSizeOffset + kPointerSize;
4757 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4760 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4764 // V has parameters (Type, type, TYPE, C type, element_size)
4765 #define BUILTIN_TYPED_ARRAY(V) \
4766 V(Uint8, uint8, UINT8, uint8_t, 1) \
4767 V(Int8, int8, INT8, int8_t, 1) \
4768 V(Uint16, uint16, UINT16, uint16_t, 2) \
4769 V(Int16, int16, INT16, int16_t, 2) \
4770 V(Uint32, uint32, UINT32, uint32_t, 4) \
4771 V(Int32, int32, INT32, int32_t, 4) \
4772 V(Float32, float32, FLOAT32, float, 4) \
4773 V(Float64, float64, FLOAT64, double, 8) \
4774 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4777 #define SIMD128_TYPED_ARRAY(V) \
4778 V(Float32x4, float32x4, FLOAT32x4, v8::internal::float32x4_value_t, 16) \
4779 V(Int32x4, int32x4, INT32x4, v8::internal::int32x4_value_t, 16)
4782 #define TYPED_ARRAYS(V) \
4783 BUILTIN_TYPED_ARRAY(V) \
4784 SIMD128_TYPED_ARRAY(V)
4787 // An ExternalArray represents a fixed-size array of primitive values
4788 // which live outside the JavaScript heap. Its subclasses are used to
4789 // implement the CanvasArray types being defined in the WebGL
4790 // specification. As of this writing the first public draft is not yet
4791 // available, but Khronos members can access the draft at:
4792 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4794 // The semantics of these arrays differ from CanvasPixelArray.
4795 // Out-of-range values passed to the setter are converted via a C
4796 // cast, not clamping. Out-of-range indices cause exceptions to be
4797 // raised rather than being silently ignored.
4798 class ExternalArray: public FixedArrayBase {
4800 inline bool is_the_hole(int index) { return false; }
4802 // [external_pointer]: The pointer to the external memory area backing this
4804 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4807 static inline ExternalArray* cast(Object* obj);
4809 // Maximal acceptable length for an external array.
4810 static const int kMaxLength = 0x3fffffff;
4812 // ExternalArray headers are not quadword aligned.
4813 static const int kExternalPointerOffset =
4814 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4815 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4816 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4819 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4823 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4824 // semantics used for implementing the CanvasPixelArray object. Please see the
4825 // specification at:
4827 // http://www.whatwg.org/specs/web-apps/current-work/
4828 // multipage/the-canvas-element.html#canvaspixelarray
4829 // In particular, write access clamps the value written to 0 or 255 if the
4830 // value written is outside this range.
4831 class ExternalUint8ClampedArray: public ExternalArray {
4833 inline uint8_t* external_uint8_clamped_pointer();
4835 // Setter and getter.
4836 inline uint8_t get_scalar(int index);
4837 MUST_USE_RESULT inline MaybeObject* get(int index);
4838 inline void set(int index, uint8_t value);
4840 // This accessor applies the correct conversion from Smi, HeapNumber and
4841 // undefined and clamps the converted value between 0 and 255.
4842 Object* SetValue(uint32_t index, Object* value);
4844 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4846 Handle<Object> value);
4849 static inline ExternalUint8ClampedArray* cast(Object* obj);
4851 // Dispatched behavior.
4852 DECLARE_PRINTER(ExternalUint8ClampedArray)
4853 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4856 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4860 class ExternalInt8Array: public ExternalArray {
4862 // Setter and getter.
4863 inline int8_t get_scalar(int index);
4864 MUST_USE_RESULT inline MaybeObject* get(int index);
4865 inline void set(int index, int8_t value);
4867 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4869 Handle<Object> value);
4871 // This accessor applies the correct conversion from Smi, HeapNumber
4873 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4876 static inline ExternalInt8Array* cast(Object* obj);
4878 // Dispatched behavior.
4879 DECLARE_PRINTER(ExternalInt8Array)
4880 DECLARE_VERIFIER(ExternalInt8Array)
4883 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4887 class ExternalUint8Array: public ExternalArray {
4889 // Setter and getter.
4890 inline uint8_t get_scalar(int index);
4891 MUST_USE_RESULT inline MaybeObject* get(int index);
4892 inline void set(int index, uint8_t value);
4894 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4896 Handle<Object> value);
4898 // This accessor applies the correct conversion from Smi, HeapNumber
4900 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4903 static inline ExternalUint8Array* cast(Object* obj);
4905 // Dispatched behavior.
4906 DECLARE_PRINTER(ExternalUint8Array)
4907 DECLARE_VERIFIER(ExternalUint8Array)
4910 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4914 class ExternalInt16Array: public ExternalArray {
4916 // Setter and getter.
4917 inline int16_t get_scalar(int index);
4918 MUST_USE_RESULT inline MaybeObject* get(int index);
4919 inline void set(int index, int16_t value);
4921 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4923 Handle<Object> value);
4925 // This accessor applies the correct conversion from Smi, HeapNumber
4927 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4930 static inline ExternalInt16Array* cast(Object* obj);
4932 // Dispatched behavior.
4933 DECLARE_PRINTER(ExternalInt16Array)
4934 DECLARE_VERIFIER(ExternalInt16Array)
4937 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4941 class ExternalUint16Array: public ExternalArray {
4943 // Setter and getter.
4944 inline uint16_t get_scalar(int index);
4945 MUST_USE_RESULT inline MaybeObject* get(int index);
4946 inline void set(int index, uint16_t value);
4948 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4950 Handle<Object> value);
4952 // This accessor applies the correct conversion from Smi, HeapNumber
4954 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4957 static inline ExternalUint16Array* cast(Object* obj);
4959 // Dispatched behavior.
4960 DECLARE_PRINTER(ExternalUint16Array)
4961 DECLARE_VERIFIER(ExternalUint16Array)
4964 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4968 class ExternalInt32Array: public ExternalArray {
4970 // Setter and getter.
4971 inline int32_t get_scalar(int index);
4972 MUST_USE_RESULT inline MaybeObject* get(int index);
4973 inline void set(int index, int32_t value);
4975 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4977 Handle<Object> value);
4979 // This accessor applies the correct conversion from Smi, HeapNumber
4981 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4984 static inline ExternalInt32Array* cast(Object* obj);
4986 // Dispatched behavior.
4987 DECLARE_PRINTER(ExternalInt32Array)
4988 DECLARE_VERIFIER(ExternalInt32Array)
4991 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4995 class ExternalUint32Array: public ExternalArray {
4997 // Setter and getter.
4998 inline uint32_t get_scalar(int index);
4999 MUST_USE_RESULT inline MaybeObject* get(int index);
5000 inline void set(int index, uint32_t value);
5002 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
5004 Handle<Object> value);
5006 // This accessor applies the correct conversion from Smi, HeapNumber
5008 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5011 static inline ExternalUint32Array* cast(Object* obj);
5013 // Dispatched behavior.
5014 DECLARE_PRINTER(ExternalUint32Array)
5015 DECLARE_VERIFIER(ExternalUint32Array)
5018 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
5022 class ExternalFloat32Array: public ExternalArray {
5024 // Setter and getter.
5025 inline float get_scalar(int index);
5026 MUST_USE_RESULT inline MaybeObject* get(int index);
5027 inline void set(int index, float value);
5029 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
5031 Handle<Object> value);
5033 // This accessor applies the correct conversion from Smi, HeapNumber
5035 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5038 static inline ExternalFloat32Array* cast(Object* obj);
5040 // Dispatched behavior.
5041 DECLARE_PRINTER(ExternalFloat32Array)
5042 DECLARE_VERIFIER(ExternalFloat32Array)
5045 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
5049 class ExternalFloat32x4Array: public ExternalArray {
5051 // Setter and getter.
5052 inline float32x4_value_t get_scalar(int index);
5053 MUST_USE_RESULT inline MaybeObject* get(int index);
5054 inline void set(int index, const float32x4_value_t& value);
5056 static Handle<Object> SetValue(Handle<ExternalFloat32x4Array> array,
5058 Handle<Object> value);
5060 // This accessor applies the correct conversion from Smi, HeapNumber
5062 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5065 static inline ExternalFloat32x4Array* cast(Object* obj);
5067 // Dispatched behavior.
5068 DECLARE_PRINTER(ExternalFloat32x4Array)
5069 DECLARE_VERIFIER(ExternalFloat32x4Array)
5072 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32x4Array);
5076 class ExternalInt32x4Array: public ExternalArray {
5078 // Setter and getter.
5079 inline int32x4_value_t get_scalar(int index);
5080 MUST_USE_RESULT inline MaybeObject* get(int index);
5081 inline void set(int index, const int32x4_value_t& value);
5083 static Handle<Object> SetValue(Handle<ExternalInt32x4Array> array,
5085 Handle<Object> value);
5086 // This accessor applies the correct conversion from Smi, HeapNumber
5088 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5091 static inline ExternalInt32x4Array* cast(Object* obj);
5093 // Dispatched behavior.
5094 DECLARE_PRINTER(ExternalInt32x4Array)
5095 DECLARE_VERIFIER(ExternalInt32x4Array)
5098 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32x4Array);
5102 class ExternalFloat64Array: public ExternalArray {
5104 // Setter and getter.
5105 inline double get_scalar(int index);
5106 MUST_USE_RESULT inline MaybeObject* get(int index);
5107 inline void set(int index, double value);
5109 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
5111 Handle<Object> value);
5113 // This accessor applies the correct conversion from Smi, HeapNumber
5115 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5118 static inline ExternalFloat64Array* cast(Object* obj);
5120 // Dispatched behavior.
5121 DECLARE_PRINTER(ExternalFloat64Array)
5122 DECLARE_VERIFIER(ExternalFloat64Array)
5125 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
5129 class FixedTypedArrayBase: public FixedArrayBase {
5132 static inline FixedTypedArrayBase* cast(Object* obj);
5134 static const int kDataOffset = kHeaderSize;
5138 // Use with care: returns raw pointer into heap.
5139 inline void* DataPtr();
5141 inline int DataSize();
5144 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
5148 template <class Traits>
5149 class FixedTypedArray: public FixedTypedArrayBase {
5151 typedef typename Traits::ElementType ElementType;
5152 static const InstanceType kInstanceType = Traits::kInstanceType;
5155 static inline FixedTypedArray<Traits>* cast(Object* obj);
5157 static inline int ElementOffset(int index) {
5158 return kDataOffset + index * sizeof(ElementType);
5161 static inline int SizeFor(int length) {
5162 return ElementOffset(length);
5165 inline ElementType get_scalar(int index);
5166 MUST_USE_RESULT inline MaybeObject* get(int index);
5167 inline void set(int index, ElementType value);
5169 static inline ElementType from_int(int value);
5170 static inline ElementType from_double(double value);
5172 // This accessor applies the correct conversion from Smi, HeapNumber
5174 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5176 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
5178 Handle<Object> value);
5180 DECLARE_PRINTER(FixedTypedArray)
5181 DECLARE_VERIFIER(FixedTypedArray)
5184 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
5187 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
5188 class Type##ArrayTraits { \
5190 typedef elementType ElementType; \
5191 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
5192 static const char* Designator() { return #type " array"; } \
5193 static inline MaybeObject* ToObject(Heap* heap, elementType scalar); \
5194 static inline elementType defaultValue(); \
5197 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
5199 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
5201 #undef FIXED_TYPED_ARRAY_TRAITS
5203 // DeoptimizationInputData is a fixed array used to hold the deoptimization
5204 // data for code generated by the Hydrogen/Lithium compiler. It also
5205 // contains information about functions that were inlined. If N different
5206 // functions were inlined then first N elements of the literal array will
5207 // contain these functions.
5210 class DeoptimizationInputData: public FixedArray {
5212 // Layout description. Indices in the array.
5213 static const int kTranslationByteArrayIndex = 0;
5214 static const int kInlinedFunctionCountIndex = 1;
5215 static const int kLiteralArrayIndex = 2;
5216 static const int kOsrAstIdIndex = 3;
5217 static const int kOsrPcOffsetIndex = 4;
5218 static const int kOptimizationIdIndex = 5;
5219 static const int kSharedFunctionInfoIndex = 6;
5220 static const int kFirstDeoptEntryIndex = 7;
5222 // Offsets of deopt entry elements relative to the start of the entry.
5223 static const int kAstIdRawOffset = 0;
5224 static const int kTranslationIndexOffset = 1;
5225 static const int kArgumentsStackHeightOffset = 2;
5226 static const int kPcOffset = 3;
5227 static const int kDeoptEntrySize = 4;
5229 // Simple element accessors.
5230 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
5232 return type::cast(get(k##name##Index)); \
5234 void Set##name(type* value) { \
5235 set(k##name##Index, value); \
5238 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
5239 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
5240 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
5241 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
5242 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
5243 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
5244 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
5246 #undef DEFINE_ELEMENT_ACCESSORS
5248 // Accessors for elements of the ith deoptimization entry.
5249 #define DEFINE_ENTRY_ACCESSORS(name, type) \
5250 type* name(int i) { \
5251 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
5253 void Set##name(int i, type* value) { \
5254 set(IndexForEntry(i) + k##name##Offset, value); \
5257 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
5258 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
5259 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
5260 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
5262 #undef DEFINE_ENTRY_ACCESSORS
5264 BailoutId AstId(int i) {
5265 return BailoutId(AstIdRaw(i)->value());
5268 void SetAstId(int i, BailoutId value) {
5269 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
5273 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
5276 // Allocates a DeoptimizationInputData.
5277 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5278 int deopt_entry_count,
5279 PretenureFlag pretenure);
5282 static inline DeoptimizationInputData* cast(Object* obj);
5284 #ifdef ENABLE_DISASSEMBLER
5285 void DeoptimizationInputDataPrint(FILE* out);
5289 static int IndexForEntry(int i) {
5290 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
5293 static int LengthFor(int entry_count) {
5294 return IndexForEntry(entry_count);
5299 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
5300 // data for code generated by the full compiler.
5301 // The format of the these objects is
5302 // [i * 2]: Ast ID for ith deoptimization.
5303 // [i * 2 + 1]: PC and state of ith deoptimization
5304 class DeoptimizationOutputData: public FixedArray {
5306 int DeoptPoints() { return length() / 2; }
5308 BailoutId AstId(int index) {
5309 return BailoutId(Smi::cast(get(index * 2))->value());
5312 void SetAstId(int index, BailoutId id) {
5313 set(index * 2, Smi::FromInt(id.ToInt()));
5316 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
5317 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
5319 static int LengthOfFixedArray(int deopt_points) {
5320 return deopt_points * 2;
5323 // Allocates a DeoptimizationOutputData.
5324 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5325 int number_of_deopt_points,
5326 PretenureFlag pretenure);
5329 static inline DeoptimizationOutputData* cast(Object* obj);
5331 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
5332 void DeoptimizationOutputDataPrint(FILE* out);
5337 // Forward declaration.
5340 class SafepointEntry;
5341 class TypeFeedbackInfo;
5343 // Code describes objects with on-the-fly generated machine code.
5344 class Code: public HeapObject {
5346 // Opaque data type for encapsulating code flags like kind, inline
5347 // cache state, and arguments count.
5348 typedef uint32_t Flags;
5350 #define NON_IC_KIND_LIST(V) \
5352 V(OPTIMIZED_FUNCTION) \
5358 #define IC_KIND_LIST(V) \
5368 #define CODE_KIND_LIST(V) \
5369 NON_IC_KIND_LIST(V) \
5373 #define DEFINE_CODE_KIND_ENUM(name) name,
5374 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5375 #undef DEFINE_CODE_KIND_ENUM
5379 // No more than 16 kinds. The value is currently encoded in four bits in
5381 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5383 static const char* Kind2String(Kind kind);
5391 static const int kPrologueOffsetNotSet = -1;
5393 #ifdef ENABLE_DISASSEMBLER
5395 static const char* ICState2String(InlineCacheState state);
5396 static const char* StubType2String(StubType type);
5397 static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
5398 void Disassemble(const char* name, FILE* out = stdout);
5399 #endif // ENABLE_DISASSEMBLER
5401 // [instruction_size]: Size of the native instructions
5402 inline int instruction_size();
5403 inline void set_instruction_size(int value);
5405 // [relocation_info]: Code relocation information
5406 DECL_ACCESSORS(relocation_info, ByteArray)
5407 void InvalidateRelocation();
5408 void InvalidateEmbeddedObjects();
5410 // [handler_table]: Fixed array containing offsets of exception handlers.
5411 DECL_ACCESSORS(handler_table, FixedArray)
5413 // [deoptimization_data]: Array containing data for deopt.
5414 DECL_ACCESSORS(deoptimization_data, FixedArray)
5416 // [raw_type_feedback_info]: This field stores various things, depending on
5417 // the kind of the code object.
5418 // FUNCTION => type feedback information.
5419 // STUB => various things, e.g. a SMI
5420 DECL_ACCESSORS(raw_type_feedback_info, Object)
5421 inline Object* type_feedback_info();
5422 inline void set_type_feedback_info(
5423 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5424 inline int stub_info();
5425 inline void set_stub_info(int info);
5427 // [next_code_link]: Link for lists of optimized or deoptimized code.
5428 // Note that storage for this field is overlapped with typefeedback_info.
5429 DECL_ACCESSORS(next_code_link, Object)
5431 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5432 // field does not have to be traced during garbage collection since
5433 // it is only used by the garbage collector itself.
5434 DECL_ACCESSORS(gc_metadata, Object)
5436 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5437 // at the moment when this object was created.
5438 inline void set_ic_age(int count);
5439 inline int ic_age();
5441 // [prologue_offset]: Offset of the function prologue, used for aging
5442 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5443 inline int prologue_offset();
5444 inline void set_prologue_offset(int offset);
5446 // Unchecked accessors to be used during GC.
5447 inline ByteArray* unchecked_relocation_info();
5449 inline int relocation_size();
5451 // [flags]: Various code flags.
5452 inline Flags flags();
5453 inline void set_flags(Flags flags);
5455 // [flags]: Access to specific code flags.
5457 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5458 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5460 inline StubType type(); // Only valid for monomorphic IC stubs.
5462 // Testers for IC stub kinds.
5463 inline bool is_inline_cache_stub();
5464 inline bool is_debug_stub();
5465 inline bool is_handler() { return kind() == HANDLER; }
5466 inline bool is_load_stub() { return kind() == LOAD_IC; }
5467 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5468 inline bool is_store_stub() { return kind() == STORE_IC; }
5469 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5470 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5471 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5472 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5473 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5474 inline bool is_keyed_stub();
5475 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5477 inline void set_raw_kind_specific_flags1(int value);
5478 inline void set_raw_kind_specific_flags2(int value);
5480 // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
5481 inline int major_key();
5482 inline void set_major_key(int value);
5483 inline bool has_major_key();
5485 // For kind STUB or ICs, tells whether or not a code object was generated by
5486 // the optimizing compiler (but it may not be an optimized function).
5487 bool is_crankshafted();
5488 inline void set_is_crankshafted(bool value);
5490 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5491 inline bool optimizable();
5492 inline void set_optimizable(bool value);
5494 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5495 // deoptimization support.
5496 inline bool has_deoptimization_support();
5497 inline void set_has_deoptimization_support(bool value);
5499 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5500 // been compiled with debug break slots.
5501 inline bool has_debug_break_slots();
5502 inline void set_has_debug_break_slots(bool value);
5504 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5505 // been compiled with IsOptimizing set to true.
5506 inline bool is_compiled_optimizable();
5507 inline void set_compiled_optimizable(bool value);
5509 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5510 // how long the function has been marked for OSR and therefore which
5511 // level of loop nesting we are willing to do on-stack replacement
5513 inline void set_allow_osr_at_loop_nesting_level(int level);
5514 inline int allow_osr_at_loop_nesting_level();
5516 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5517 // the code object was seen on the stack with no IC patching going on.
5518 inline int profiler_ticks();
5519 inline void set_profiler_ticks(int ticks);
5521 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5522 // reserved in the code prologue.
5523 inline unsigned stack_slots();
5524 inline void set_stack_slots(unsigned slots);
5526 // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
5527 // the instruction stream where the safepoint table starts.
5528 inline unsigned safepoint_table_offset();
5529 inline void set_safepoint_table_offset(unsigned offset);
5531 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5532 // instruction stream where the back edge table starts.
5533 inline unsigned back_edge_table_offset();
5534 inline void set_back_edge_table_offset(unsigned offset);
5536 inline bool back_edges_patched_for_osr();
5537 inline void set_back_edges_patched_for_osr(bool value);
5539 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5540 inline byte to_boolean_state();
5542 // [has_function_cache]: For kind STUB tells whether there is a function
5543 // cache is passed to the stub.
5544 inline bool has_function_cache();
5545 inline void set_has_function_cache(bool flag);
5548 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5549 // the code is going to be deoptimized because of dead embedded maps.
5550 inline bool marked_for_deoptimization();
5551 inline void set_marked_for_deoptimization(bool flag);
5553 // [constant_pool]: The constant pool for this function.
5554 inline ConstantPoolArray* constant_pool();
5555 inline void set_constant_pool(Object* constant_pool);
5557 // Get the safepoint entry for the given pc.
5558 SafepointEntry GetSafepointEntry(Address pc);
5560 // Find an object in a stub with a specified map
5561 Object* FindNthObject(int n, Map* match_map);
5563 // Find the first allocation site in an IC stub.
5564 AllocationSite* FindFirstAllocationSite();
5566 // Find the first map in an IC stub.
5567 Map* FindFirstMap();
5568 void FindAllMaps(MapHandleList* maps);
5569 void FindAllTypes(TypeHandleList* types);
5571 // Find the first handler in an IC stub.
5572 Code* FindFirstHandler();
5574 // Find |length| handlers and put them into |code_list|. Returns false if not
5575 // enough handlers can be found.
5576 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5578 // Find the first name in an IC stub.
5579 Name* FindFirstName();
5581 class FindAndReplacePattern;
5582 // For each (map-to-find, object-to-replace) pair in the pattern, this
5583 // function replaces the corresponding placeholder in the code with the
5584 // object-to-replace. The function assumes that pairs in the pattern come in
5585 // the same order as the placeholders in the code.
5586 void FindAndReplace(const FindAndReplacePattern& pattern);
5588 // The entire code object including its header is copied verbatim to the
5589 // snapshot so that it can be written in one, fast, memcpy during
5590 // deserialization. The deserializer will overwrite some pointers, rather
5591 // like a runtime linker, but the random allocation addresses used in the
5592 // mksnapshot process would still be present in the unlinked snapshot data,
5593 // which would make snapshot production non-reproducible. This method wipes
5594 // out the to-be-overwritten header data for reproducible snapshots.
5595 inline void WipeOutHeader();
5597 // Flags operations.
5598 static inline Flags ComputeFlags(
5600 InlineCacheState ic_state = UNINITIALIZED,
5601 ExtraICState extra_ic_state = kNoExtraICState,
5602 StubType type = NORMAL,
5603 InlineCacheHolderFlag holder = OWN_MAP);
5605 static inline Flags ComputeMonomorphicFlags(
5607 ExtraICState extra_ic_state = kNoExtraICState,
5608 InlineCacheHolderFlag holder = OWN_MAP,
5609 StubType type = NORMAL);
5611 static inline Flags ComputeHandlerFlags(
5613 StubType type = NORMAL,
5614 InlineCacheHolderFlag holder = OWN_MAP);
5616 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5617 static inline StubType ExtractTypeFromFlags(Flags flags);
5618 static inline Kind ExtractKindFromFlags(Flags flags);
5619 static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5620 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5622 static inline Flags RemoveTypeFromFlags(Flags flags);
5624 // Convert a target address into a code object.
5625 static inline Code* GetCodeFromTargetAddress(Address address);
5627 // Convert an entry address into an object.
5628 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5630 // Returns the address of the first instruction.
5631 inline byte* instruction_start();
5633 // Returns the address right after the last instruction.
5634 inline byte* instruction_end();
5636 // Returns the size of the instructions, padding, and relocation information.
5637 inline int body_size();
5639 // Returns the address of the first relocation info (read backwards!).
5640 inline byte* relocation_start();
5642 // Code entry point.
5643 inline byte* entry();
5645 // Returns true if pc is inside this object's instructions.
5646 inline bool contains(byte* pc);
5648 // Relocate the code by delta bytes. Called to signal that this code
5649 // object has been moved by delta bytes.
5650 void Relocate(intptr_t delta);
5652 // Migrate code described by desc.
5653 void CopyFrom(const CodeDesc& desc);
5655 // Returns the object size for a given body (used for allocation).
5656 static int SizeFor(int body_size) {
5657 ASSERT_SIZE_TAG_ALIGNED(body_size);
5658 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5661 // Calculate the size of the code object to report for log events. This takes
5662 // the layout of the code object into account.
5663 int ExecutableSize() {
5664 // Check that the assumptions about the layout of the code object holds.
5665 ASSERT_EQ(static_cast<int>(instruction_start() - address()),
5667 return instruction_size() + Code::kHeaderSize;
5670 // Locating source position.
5671 int SourcePosition(Address pc);
5672 int SourceStatementPosition(Address pc);
5675 static inline Code* cast(Object* obj);
5677 // Dispatched behavior.
5678 int CodeSize() { return SizeFor(body_size()); }
5679 inline void CodeIterateBody(ObjectVisitor* v);
5681 template<typename StaticVisitor>
5682 inline void CodeIterateBody(Heap* heap);
5684 DECLARE_PRINTER(Code)
5685 DECLARE_VERIFIER(Code)
5687 void ClearInlineCaches();
5688 void ClearInlineCaches(Kind kind);
5690 void ClearTypeFeedbackInfo(Heap* heap);
5692 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5693 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5695 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5697 kNotExecutedCodeAge = -2,
5698 kExecutedOnceCodeAge = -1,
5700 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5702 kFirstCodeAge = kNotExecutedCodeAge,
5703 kLastCodeAge = kAfterLastCodeAge - 1,
5704 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5705 kIsOldCodeAge = kSexagenarianCodeAge,
5706 kPreAgedCodeAge = kIsOldCodeAge - 1
5708 #undef DECLARE_CODE_AGE_ENUM
5710 // Code aging. Indicates how many full GCs this code has survived without
5711 // being entered through the prologue. Used to determine when it is
5712 // relatively safe to flush this code object and replace it with the lazy
5713 // compilation stub.
5714 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5715 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5716 void MakeOlder(MarkingParity);
5717 static bool IsYoungSequence(byte* sequence);
5720 // Gets the raw code age, including psuedo code-age values such as
5721 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5723 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5724 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5727 void PrintDeoptLocation(FILE* out, int bailout_id);
5728 bool CanDeoptAt(Address pc);
5731 void VerifyEmbeddedObjectsDependency();
5734 inline bool IsWeakObject(Object* object) {
5735 return is_optimized_code() && IsWeakObjectInOptimizedCode(object);
5738 inline bool IsWeakObjectInOptimizedCode(Object* object);
5740 // Max loop nesting marker used to postpose OSR. We don't take loop
5741 // nesting that is deeper than 5 levels into account.
5742 static const int kMaxLoopNestingMarker = 6;
5744 // Layout description.
5745 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5746 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5747 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5748 static const int kDeoptimizationDataOffset =
5749 kHandlerTableOffset + kPointerSize;
5750 static const int kTypeFeedbackInfoOffset =
5751 kDeoptimizationDataOffset + kPointerSize;
5752 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5753 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5754 static const int kICAgeOffset =
5755 kGCMetadataOffset + kPointerSize;
5756 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5757 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5758 static const int kKindSpecificFlags2Offset =
5759 kKindSpecificFlags1Offset + kIntSize;
5760 // Note: We might be able to squeeze this into the flags above.
5761 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5762 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5764 static const int kHeaderPaddingStart = kConstantPoolOffset + kIntSize;
5766 // Add padding to align the instruction start following right after
5767 // the Code object header.
5768 static const int kHeaderSize =
5769 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5771 // Byte offsets within kKindSpecificFlags1Offset.
5772 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5774 static const int kFullCodeFlags = kOptimizableOffset + 1;
5775 class FullCodeFlagsHasDeoptimizationSupportField:
5776 public BitField<bool, 0, 1> {}; // NOLINT
5777 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5778 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5780 static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
5781 static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
5783 // Flags layout. BitField<type, shift, size>.
5784 class ICStateField: public BitField<InlineCacheState, 0, 3> {};
5785 class TypeField: public BitField<StubType, 3, 1> {};
5786 class CacheHolderField: public BitField<InlineCacheHolderFlag, 5, 1> {};
5787 class KindField: public BitField<Kind, 6, 4> {};
5788 // TODO(bmeurer): Bit 10 is available for free use. :-)
5789 class ExtraICStateField: public BitField<ExtraICState, 11,
5790 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5792 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5793 static const int kStackSlotsFirstBit = 0;
5794 static const int kStackSlotsBitCount = 24;
5795 static const int kHasFunctionCacheFirstBit =
5796 kStackSlotsFirstBit + kStackSlotsBitCount;
5797 static const int kHasFunctionCacheBitCount = 1;
5798 static const int kMarkedForDeoptimizationFirstBit =
5799 kStackSlotsFirstBit + kStackSlotsBitCount + 1;
5800 static const int kMarkedForDeoptimizationBitCount = 1;
5802 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5803 STATIC_ASSERT(kHasFunctionCacheFirstBit + kHasFunctionCacheBitCount <= 32);
5804 STATIC_ASSERT(kMarkedForDeoptimizationFirstBit +
5805 kMarkedForDeoptimizationBitCount <= 32);
5807 class StackSlotsField: public BitField<int,
5808 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5809 class HasFunctionCacheField: public BitField<bool,
5810 kHasFunctionCacheFirstBit, kHasFunctionCacheBitCount> {}; // NOLINT
5811 class MarkedForDeoptimizationField: public BitField<bool,
5812 kMarkedForDeoptimizationFirstBit,
5813 kMarkedForDeoptimizationBitCount> {}; // NOLINT
5815 // KindSpecificFlags2 layout (ALL)
5816 static const int kIsCrankshaftedBit = 0;
5817 class IsCrankshaftedField: public BitField<bool,
5818 kIsCrankshaftedBit, 1> {}; // NOLINT
5820 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5821 static const int kStubMajorKeyFirstBit = kIsCrankshaftedBit + 1;
5822 static const int kSafepointTableOffsetFirstBit =
5823 kStubMajorKeyFirstBit + kStubMajorKeyBits;
5824 static const int kSafepointTableOffsetBitCount = 24;
5826 STATIC_ASSERT(kStubMajorKeyFirstBit + kStubMajorKeyBits <= 32);
5827 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5828 kSafepointTableOffsetBitCount <= 32);
5829 STATIC_ASSERT(1 + kStubMajorKeyBits +
5830 kSafepointTableOffsetBitCount <= 32);
5832 class SafepointTableOffsetField: public BitField<int,
5833 kSafepointTableOffsetFirstBit,
5834 kSafepointTableOffsetBitCount> {}; // NOLINT
5835 class StubMajorKeyField: public BitField<int,
5836 kStubMajorKeyFirstBit, kStubMajorKeyBits> {}; // NOLINT
5838 // KindSpecificFlags2 layout (FUNCTION)
5839 class BackEdgeTableOffsetField: public BitField<int,
5840 kIsCrankshaftedBit + 1, 29> {}; // NOLINT
5841 class BackEdgesPatchedForOSRField: public BitField<bool,
5842 kIsCrankshaftedBit + 1 + 29, 1> {}; // NOLINT
5844 static const int kArgumentsBits = 16;
5845 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5847 // This constant should be encodable in an ARM instruction.
5848 static const int kFlagsNotUsedInLookup =
5849 TypeField::kMask | CacheHolderField::kMask;
5852 friend class RelocIterator;
5853 friend class Deoptimizer; // For FindCodeAgeSequence.
5855 void ClearInlineCaches(Kind* kind);
5858 byte* FindCodeAgeSequence();
5859 static void GetCodeAgeAndParity(Code* code, Age* age,
5860 MarkingParity* parity);
5861 static void GetCodeAgeAndParity(byte* sequence, Age* age,
5862 MarkingParity* parity);
5863 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5865 // Code aging -- platform-specific
5866 static void PatchPlatformCodeAge(Isolate* isolate,
5867 byte* sequence, Age age,
5868 MarkingParity parity);
5870 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5874 class CompilationInfo;
5876 // This class describes the layout of dependent codes array of a map. The
5877 // array is partitioned into several groups of dependent codes. Each group
5878 // contains codes with the same dependency on the map. The array has the
5879 // following layout for n dependency groups:
5881 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5882 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5883 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5885 // The first n elements are Smis, each of them specifies the number of codes
5886 // in the corresponding group. The subsequent elements contain grouped code
5887 // objects. The suffix of the array can be filled with the undefined value if
5888 // the number of codes is less than the length of the array. The order of the
5889 // code objects within a group is not preserved.
5891 // All code indexes used in the class are counted starting from the first
5892 // code object of the first group. In other words, code index 0 corresponds
5893 // to array index n = kCodesStartIndex.
5895 class DependentCode: public FixedArray {
5897 enum DependencyGroup {
5898 // Group of code that weakly embed this map and depend on being
5899 // deoptimized when the map is garbage collected.
5900 kWeaklyEmbeddedGroup,
5901 // Group of code that embed a transition to this map, and depend on being
5902 // deoptimized when the transition is replaced by a new version.
5904 // Group of code that omit run-time prototype checks for prototypes
5905 // described by this map. The group is deoptimized whenever an object
5906 // described by this map changes shape (and transitions to a new map),
5907 // possibly invalidating the assumptions embedded in the code.
5908 kPrototypeCheckGroup,
5909 // Group of code that depends on elements not being added to objects with
5911 kElementsCantBeAddedGroup,
5912 // Group of code that depends on global property values in property cells
5913 // not being changed.
5914 kPropertyCellChangedGroup,
5915 // Group of code that depends on tenuring information in AllocationSites
5916 // not being changed.
5917 kAllocationSiteTenuringChangedGroup,
5918 // Group of code that depends on element transition information in
5919 // AllocationSites not being changed.
5920 kAllocationSiteTransitionChangedGroup,
5921 kGroupCount = kAllocationSiteTransitionChangedGroup + 1
5924 // Array for holding the index of the first code object of each group.
5925 // The last element stores the total number of code objects.
5926 class GroupStartIndexes {
5928 explicit GroupStartIndexes(DependentCode* entries);
5929 void Recompute(DependentCode* entries);
5930 int at(int i) { return start_indexes_[i]; }
5931 int number_of_entries() { return start_indexes_[kGroupCount]; }
5933 int start_indexes_[kGroupCount + 1];
5936 bool Contains(DependencyGroup group, Code* code);
5937 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5938 DependencyGroup group,
5939 Handle<Object> object);
5940 void UpdateToFinishedCode(DependencyGroup group,
5941 CompilationInfo* info,
5943 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5944 CompilationInfo* info);
5946 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5947 DependentCode::DependencyGroup group);
5949 bool MarkCodeForDeoptimization(Isolate* isolate,
5950 DependentCode::DependencyGroup group);
5952 // The following low-level accessors should only be used by this class
5953 // and the mark compact collector.
5954 inline int number_of_entries(DependencyGroup group);
5955 inline void set_number_of_entries(DependencyGroup group, int value);
5956 inline bool is_code_at(int i);
5957 inline Code* code_at(int i);
5958 inline CompilationInfo* compilation_info_at(int i);
5959 inline void set_object_at(int i, Object* object);
5960 inline Object** slot_at(int i);
5961 inline Object* object_at(int i);
5962 inline void clear_at(int i);
5963 inline void copy(int from, int to);
5964 static inline DependentCode* cast(Object* object);
5966 static DependentCode* ForObject(Handle<HeapObject> object,
5967 DependencyGroup group);
5970 // Make a room at the end of the given group by moving out the first
5971 // code objects of the subsequent groups.
5972 inline void ExtendGroup(DependencyGroup group);
5973 static const int kCodesStartIndex = kGroupCount;
5977 // All heap objects have a Map that describes their structure.
5978 // A Map contains information about:
5979 // - Size information about the object
5980 // - How to iterate over an object (for garbage collection)
5981 class Map: public HeapObject {
5984 // Size in bytes or kVariableSizeSentinel if instances do not have
5986 inline int instance_size();
5987 inline void set_instance_size(int value);
5989 // Count of properties allocated in the object.
5990 inline int inobject_properties();
5991 inline void set_inobject_properties(int value);
5993 // Count of property fields pre-allocated in the object when first allocated.
5994 inline int pre_allocated_property_fields();
5995 inline void set_pre_allocated_property_fields(int value);
5998 inline InstanceType instance_type();
5999 inline void set_instance_type(InstanceType value);
6001 // Tells how many unused property fields are available in the
6002 // instance (only used for JSObject in fast mode).
6003 inline int unused_property_fields();
6004 inline void set_unused_property_fields(int value);
6007 inline byte bit_field();
6008 inline void set_bit_field(byte value);
6011 inline byte bit_field2();
6012 inline void set_bit_field2(byte value);
6015 inline uint32_t bit_field3();
6016 inline void set_bit_field3(uint32_t bits);
6018 class EnumLengthBits: public BitField<int,
6019 0, kDescriptorIndexBitCount> {}; // NOLINT
6020 class NumberOfOwnDescriptorsBits: public BitField<int,
6021 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
6022 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
6023 class IsShared: public BitField<bool, 20, 1> {};
6024 class FunctionWithPrototype: public BitField<bool, 21, 1> {};
6025 class DictionaryMap: public BitField<bool, 22, 1> {};
6026 class OwnsDescriptors: public BitField<bool, 23, 1> {};
6027 class HasInstanceCallHandler: public BitField<bool, 24, 1> {};
6028 class Deprecated: public BitField<bool, 25, 1> {};
6029 class IsFrozen: public BitField<bool, 26, 1> {};
6030 class IsUnstable: public BitField<bool, 27, 1> {};
6031 class IsMigrationTarget: public BitField<bool, 28, 1> {};
6033 // Tells whether the object in the prototype property will be used
6034 // for instances created from this function. If the prototype
6035 // property is set to a value that is not a JSObject, the prototype
6036 // property will not be used to create instances of the function.
6037 // See ECMA-262, 13.2.2.
6038 inline void set_non_instance_prototype(bool value);
6039 inline bool has_non_instance_prototype();
6041 // Tells whether function has special prototype property. If not, prototype
6042 // property will not be created when accessed (will return undefined),
6043 // and construction from this function will not be allowed.
6044 inline void set_function_with_prototype(bool value);
6045 inline bool function_with_prototype();
6047 // Tells whether the instance with this map should be ignored by the
6048 // Object.getPrototypeOf() function and the __proto__ accessor.
6049 inline void set_is_hidden_prototype() {
6050 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
6053 inline bool is_hidden_prototype() {
6054 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
6057 // Records and queries whether the instance has a named interceptor.
6058 inline void set_has_named_interceptor() {
6059 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
6062 inline bool has_named_interceptor() {
6063 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
6066 // Records and queries whether the instance has an indexed interceptor.
6067 inline void set_has_indexed_interceptor() {
6068 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
6071 inline bool has_indexed_interceptor() {
6072 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
6075 // Tells whether the instance is undetectable.
6076 // An undetectable object is a special class of JSObject: 'typeof' operator
6077 // returns undefined, ToBoolean returns false. Otherwise it behaves like
6078 // a normal JS object. It is useful for implementing undetectable
6079 // document.all in Firefox & Safari.
6080 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
6081 inline void set_is_undetectable() {
6082 set_bit_field(bit_field() | (1 << kIsUndetectable));
6085 inline bool is_undetectable() {
6086 return ((1 << kIsUndetectable) & bit_field()) != 0;
6089 // Tells whether the instance has a call-as-function handler.
6090 inline void set_is_observed() {
6091 set_bit_field(bit_field() | (1 << kIsObserved));
6094 inline bool is_observed() {
6095 return ((1 << kIsObserved) & bit_field()) != 0;
6098 inline void set_is_extensible(bool value);
6099 inline bool is_extensible();
6101 inline void set_elements_kind(ElementsKind elements_kind) {
6102 ASSERT(elements_kind < kElementsKindCount);
6103 ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
6104 set_bit_field2((bit_field2() & ~kElementsKindMask) |
6105 (elements_kind << kElementsKindShift));
6106 ASSERT(this->elements_kind() == elements_kind);
6109 inline ElementsKind elements_kind() {
6110 return static_cast<ElementsKind>(
6111 (bit_field2() & kElementsKindMask) >> kElementsKindShift);
6114 // Tells whether the instance has fast elements that are only Smis.
6115 inline bool has_fast_smi_elements() {
6116 return IsFastSmiElementsKind(elements_kind());
6119 // Tells whether the instance has fast elements.
6120 inline bool has_fast_object_elements() {
6121 return IsFastObjectElementsKind(elements_kind());
6124 inline bool has_fast_smi_or_object_elements() {
6125 return IsFastSmiOrObjectElementsKind(elements_kind());
6128 inline bool has_fast_double_elements() {
6129 return IsFastDoubleElementsKind(elements_kind());
6132 inline bool has_fast_elements() {
6133 return IsFastElementsKind(elements_kind());
6136 inline bool has_sloppy_arguments_elements() {
6137 return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6140 inline bool has_external_array_elements() {
6141 return IsExternalArrayElementsKind(elements_kind());
6144 inline bool has_fixed_typed_array_elements() {
6145 return IsFixedTypedArrayElementsKind(elements_kind());
6148 inline bool has_dictionary_elements() {
6149 return IsDictionaryElementsKind(elements_kind());
6152 inline bool has_slow_elements_kind() {
6153 return elements_kind() == DICTIONARY_ELEMENTS
6154 || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6157 static bool IsValidElementsTransition(ElementsKind from_kind,
6158 ElementsKind to_kind);
6160 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
6161 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
6162 bool DictionaryElementsInPrototypeChainOnly();
6164 inline bool HasTransitionArray();
6165 inline bool HasElementsTransition();
6166 inline Map* elements_transition_map();
6167 MUST_USE_RESULT inline MaybeObject* set_elements_transition_map(
6168 Map* transitioned_map);
6169 inline void SetTransition(int transition_index, Map* target);
6170 inline Map* GetTransition(int transition_index);
6172 static Handle<TransitionArray> AddTransition(Handle<Map> map,
6175 SimpleTransitionFlag flag);
6177 MUST_USE_RESULT inline MaybeObject* AddTransition(Name* key,
6179 SimpleTransitionFlag flag);
6180 DECL_ACCESSORS(transitions, TransitionArray)
6181 inline void ClearTransitions(Heap* heap,
6182 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6184 void DeprecateTransitionTree();
6185 void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6188 Map* FindUpdatedMap(int verbatim, int length, DescriptorArray* descriptors);
6189 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6191 inline int GetInObjectPropertyOffset(int index);
6193 int NumberOfFields();
6195 bool InstancesNeedRewriting(Map* target,
6196 int target_number_of_fields,
6197 int target_inobject,
6199 static Handle<Map> GeneralizeAllFieldRepresentations(
6201 Representation new_representation);
6202 static Handle<Map> GeneralizeRepresentation(
6205 Representation new_representation,
6206 StoreMode store_mode);
6207 static Handle<Map> CopyGeneralizeAllRepresentations(
6210 StoreMode store_mode,
6211 PropertyAttributes attributes,
6212 const char* reason);
6214 void PrintGeneralization(FILE* file,
6219 bool constant_to_field,
6220 Representation old_representation,
6221 Representation new_representation);
6223 // Returns the constructor name (the name (possibly, inferred name) of the
6224 // function that was used to instantiate the object).
6225 String* constructor_name();
6227 // Tells whether the map is attached to SharedFunctionInfo
6228 // (for inobject slack tracking).
6229 inline void set_attached_to_shared_function_info(bool value);
6231 inline bool attached_to_shared_function_info();
6233 // Tells whether the map is shared between objects that may have different
6234 // behavior. If true, the map should never be modified, instead a clone
6235 // should be created and modified.
6236 inline void set_is_shared(bool value);
6237 inline bool is_shared();
6239 // Tells whether the map is used for JSObjects in dictionary mode (ie
6240 // normalized objects, ie objects for which HasFastProperties returns false).
6241 // A map can never be used for both dictionary mode and fast mode JSObjects.
6242 // False by default and for HeapObjects that are not JSObjects.
6243 inline void set_dictionary_map(bool value);
6244 inline bool is_dictionary_map();
6246 // Tells whether the instance needs security checks when accessing its
6248 inline void set_is_access_check_needed(bool access_check_needed);
6249 inline bool is_access_check_needed();
6251 // Returns true if map has a non-empty stub code cache.
6252 inline bool has_code_cache();
6254 // [prototype]: implicit prototype object.
6255 DECL_ACCESSORS(prototype, Object)
6257 // [constructor]: points back to the function responsible for this map.
6258 DECL_ACCESSORS(constructor, Object)
6260 // [instance descriptors]: describes the object.
6261 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
6262 inline void InitializeDescriptors(DescriptorArray* descriptors);
6264 // [stub cache]: contains stubs compiled for this map.
6265 DECL_ACCESSORS(code_cache, Object)
6267 // [dependent code]: list of optimized codes that have this map embedded.
6268 DECL_ACCESSORS(dependent_code, DependentCode)
6270 // [back pointer]: points back to the parent map from which a transition
6271 // leads to this map. The field overlaps with prototype transitions and the
6272 // back pointer will be moved into the prototype transitions array if
6274 inline Object* GetBackPointer();
6275 inline void SetBackPointer(Object* value,
6276 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6277 inline void init_back_pointer(Object* undefined);
6279 // [prototype transitions]: cache of prototype transitions.
6280 // Prototype transition is a transition that happens
6281 // when we change object's prototype to a new one.
6283 // 0: finger - index of the first free cell in the cache
6284 // 1: back pointer that overlaps with prototype transitions field.
6285 // 2 + 2 * i: prototype
6286 // 3 + 2 * i: target map
6287 inline FixedArray* GetPrototypeTransitions();
6288 MUST_USE_RESULT inline MaybeObject* SetPrototypeTransitions(
6289 FixedArray* prototype_transitions);
6290 inline bool HasPrototypeTransitions();
6292 inline HeapObject* UncheckedPrototypeTransitions();
6293 inline TransitionArray* unchecked_transition_array();
6295 static const int kProtoTransitionHeaderSize = 1;
6296 static const int kProtoTransitionNumberOfEntriesOffset = 0;
6297 static const int kProtoTransitionElementsPerEntry = 2;
6298 static const int kProtoTransitionPrototypeOffset = 0;
6299 static const int kProtoTransitionMapOffset = 1;
6301 inline int NumberOfProtoTransitions() {
6302 FixedArray* cache = GetPrototypeTransitions();
6303 if (cache->length() == 0) return 0;
6305 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6308 inline void SetNumberOfProtoTransitions(int value) {
6309 FixedArray* cache = GetPrototypeTransitions();
6310 ASSERT(cache->length() != 0);
6311 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6314 // Lookup in the map's instance descriptors and fill out the result
6315 // with the given holder if the name is found. The holder may be
6316 // NULL when this function is used from the compiler.
6317 inline void LookupDescriptor(JSObject* holder,
6319 LookupResult* result);
6321 inline void LookupTransition(JSObject* holder,
6323 LookupResult* result);
6325 inline PropertyDetails GetLastDescriptorDetails();
6327 // The size of transition arrays are limited so they do not end up in large
6328 // object space. Otherwise ClearNonLiveTransitions would leak memory while
6329 // applying in-place right trimming.
6330 inline bool CanHaveMoreTransitions();
6333 int number_of_own_descriptors = NumberOfOwnDescriptors();
6334 ASSERT(number_of_own_descriptors > 0);
6335 return number_of_own_descriptors - 1;
6338 int NumberOfOwnDescriptors() {
6339 return NumberOfOwnDescriptorsBits::decode(bit_field3());
6342 void SetNumberOfOwnDescriptors(int number) {
6343 ASSERT(number <= instance_descriptors()->number_of_descriptors());
6344 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6347 inline Cell* RetrieveDescriptorsPointer();
6350 return EnumLengthBits::decode(bit_field3());
6353 void SetEnumLength(int length) {
6354 if (length != kInvalidEnumCacheSentinel) {
6355 ASSERT(length >= 0);
6356 ASSERT(length == 0 || instance_descriptors()->HasEnumCache());
6357 ASSERT(length <= NumberOfOwnDescriptors());
6359 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6362 inline bool owns_descriptors();
6363 inline void set_owns_descriptors(bool is_shared);
6364 inline bool has_instance_call_handler();
6365 inline void set_has_instance_call_handler();
6366 inline void freeze();
6367 inline bool is_frozen();
6368 inline void mark_unstable();
6369 inline bool is_stable();
6370 inline void set_migration_target(bool value);
6371 inline bool is_migration_target();
6372 inline void deprecate();
6373 inline bool is_deprecated();
6374 inline bool CanBeDeprecated();
6375 // Returns a non-deprecated version of the input. If the input was not
6376 // deprecated, it is directly returned. Otherwise, the non-deprecated version
6377 // is found by re-transitioning from the root of the transition tree using the
6378 // descriptor array of the map. Returns NULL if no updated map is found.
6379 // This method also applies any pending migrations along the prototype chain.
6380 static Handle<Map> CurrentMapForDeprecated(Handle<Map> map);
6381 // Same as above, but does not touch the prototype chain.
6382 static Handle<Map> CurrentMapForDeprecatedInternal(Handle<Map> map);
6384 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6385 MUST_USE_RESULT MaybeObject* RawCopy(int instance_size);
6386 MUST_USE_RESULT MaybeObject* CopyWithPreallocatedFieldDescriptors();
6387 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6388 MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
6389 static Handle<Map> CopyReplaceDescriptors(Handle<Map> map,
6390 Handle<DescriptorArray> descriptors,
6391 TransitionFlag flag,
6393 MUST_USE_RESULT MaybeObject* CopyReplaceDescriptors(
6394 DescriptorArray* descriptors,
6395 TransitionFlag flag,
6397 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6398 static Handle<Map> CopyInstallDescriptors(
6401 Handle<DescriptorArray> descriptors);
6402 MUST_USE_RESULT MaybeObject* ShareDescriptor(DescriptorArray* descriptors,
6403 Descriptor* descriptor);
6404 MUST_USE_RESULT MaybeObject* CopyAddDescriptor(Descriptor* descriptor,
6405 TransitionFlag flag);
6406 MUST_USE_RESULT MaybeObject* CopyInsertDescriptor(Descriptor* descriptor,
6407 TransitionFlag flag);
6408 MUST_USE_RESULT MaybeObject* CopyReplaceDescriptor(
6409 DescriptorArray* descriptors,
6410 Descriptor* descriptor,
6412 TransitionFlag flag);
6414 MUST_USE_RESULT MaybeObject* AsElementsKind(ElementsKind kind);
6416 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6418 MUST_USE_RESULT MaybeObject* CopyAsElementsKind(ElementsKind kind,
6419 TransitionFlag flag);
6421 static Handle<Map> CopyForObserved(Handle<Map> map);
6423 static Handle<Map> CopyNormalized(Handle<Map> map,
6424 PropertyNormalizationMode mode,
6425 NormalizedMapSharingMode sharing);
6427 inline void AppendDescriptor(Descriptor* desc,
6428 const DescriptorArray::WhitenessWitness&);
6430 // Returns a copy of the map, with all transitions dropped from the
6431 // instance descriptors.
6432 static Handle<Map> Copy(Handle<Map> map);
6433 MUST_USE_RESULT MaybeObject* Copy();
6435 // Returns the next free property index (only valid for FAST MODE).
6436 int NextFreePropertyIndex();
6438 // Returns the number of properties described in instance_descriptors
6439 // filtering out properties with the specified attributes.
6440 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6441 PropertyAttributes filter = NONE);
6443 // Returns the number of slots allocated for the initial properties
6444 // backing storage for instances of this map.
6445 int InitialPropertiesLength() {
6446 return pre_allocated_property_fields() + unused_property_fields() -
6447 inobject_properties();
6451 static inline Map* cast(Object* obj);
6453 // Locate an accessor in the instance descriptor.
6454 AccessorDescriptor* FindAccessor(Name* name);
6456 // Code cache operations.
6458 // Clears the code cache.
6459 inline void ClearCodeCache(Heap* heap);
6461 // Update code cache.
6462 static void UpdateCodeCache(Handle<Map> map,
6465 MUST_USE_RESULT MaybeObject* UpdateCodeCache(Name* name, Code* code);
6467 // Extend the descriptor array of the map with the list of descriptors.
6468 // In case of duplicates, the latest descriptor is used.
6469 static void AppendCallbackDescriptors(Handle<Map> map,
6470 Handle<Object> descriptors);
6472 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6474 // Returns the found code or undefined if absent.
6475 Object* FindInCodeCache(Name* name, Code::Flags flags);
6477 // Returns the non-negative index of the code object if it is in the
6478 // cache and -1 otherwise.
6479 int IndexInCodeCache(Object* name, Code* code);
6481 // Removes a code object from the code cache at the given index.
6482 void RemoveFromCodeCache(Name* name, Code* code, int index);
6484 // Set all map transitions from this map to dead maps to null. Also clear
6485 // back pointers in transition targets so that we do not process this map
6486 // again while following back pointers.
6487 void ClearNonLiveTransitions(Heap* heap);
6489 // Computes a hash value for this map, to be used in HashTables and such.
6492 bool EquivalentToForTransition(Map* other);
6494 // Compares this map to another to see if they describe equivalent objects.
6495 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6496 // it had exactly zero inobject properties.
6497 // The "shared" flags of both this map and |other| are ignored.
6498 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6500 // Returns the map that this map transitions to if its elements_kind
6501 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6502 // |safe_to_add_transitions| is set to false if adding transitions is not
6504 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6506 // Returns the transitioned map for this map with the most generic
6507 // elements_kind that's found in |candidates|, or null handle if no match is
6509 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6510 Map* FindTransitionedMap(MapList* candidates);
6512 // Zaps the contents of backing data structures. Note that the
6513 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6514 // holding weak references when incremental marking is used, because it also
6515 // iterates over objects that are otherwise unreachable.
6516 // In general we only want to call these functions in release mode when
6517 // heap verification is turned on.
6518 void ZapPrototypeTransitions();
6519 void ZapTransitions();
6521 bool CanTransition() {
6522 // Only JSObject and subtypes have map transitions and back pointers.
6523 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6524 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6527 bool IsJSObjectMap() {
6528 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6530 bool IsJSGlobalProxyMap() {
6531 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6533 bool IsJSGlobalObjectMap() {
6534 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6536 bool IsGlobalObjectMap() {
6537 const InstanceType type = instance_type();
6538 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6541 // Fires when the layout of an object with a leaf map changes.
6542 // This includes adding transitions to the leaf map or changing
6543 // the descriptor array.
6544 inline void NotifyLeafMapLayoutChange();
6546 inline bool CanOmitMapChecks();
6548 void AddDependentCompilationInfo(DependentCode::DependencyGroup group,
6549 CompilationInfo* info);
6551 void AddDependentCode(DependentCode::DependencyGroup group,
6554 bool IsMapInArrayPrototypeChain();
6556 // Dispatched behavior.
6557 DECLARE_PRINTER(Map)
6558 DECLARE_VERIFIER(Map)
6561 void SharedMapVerify();
6562 void VerifyOmittedMapChecks();
6565 inline int visitor_id();
6566 inline void set_visitor_id(int visitor_id);
6568 typedef void (*TraverseCallback)(Map* map, void* data);
6570 void TraverseTransitionTree(TraverseCallback callback, void* data);
6572 // When you set the prototype of an object using the __proto__ accessor you
6573 // need a new map for the object (the prototype is stored in the map). In
6574 // order not to multiply maps unnecessarily we store these as transitions in
6575 // the original map. That way we can transition to the same map if the same
6576 // prototype is set, rather than creating a new map every time. The
6577 // transitions are in the form of a map where the keys are prototype objects
6578 // and the values are the maps the are transitioned to.
6579 static const int kMaxCachedPrototypeTransitions = 256;
6580 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6581 Handle<Object> prototype);
6582 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6583 Handle<Object> prototype,
6584 Handle<Map> target_map);
6586 static const int kMaxPreAllocatedPropertyFields = 255;
6588 // Layout description.
6589 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6590 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6591 static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
6592 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6593 // Storage for the transition array is overloaded to directly contain a back
6594 // pointer if unused. When the map has transitions, the back pointer is
6595 // transferred to the transition array and accessed through an extra
6597 static const int kTransitionsOrBackPointerOffset =
6598 kConstructorOffset + kPointerSize;
6599 static const int kDescriptorsOffset =
6600 kTransitionsOrBackPointerOffset + kPointerSize;
6601 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6602 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6603 static const int kBitField3Offset = kDependentCodeOffset + kPointerSize;
6604 static const int kSize = kBitField3Offset + kPointerSize;
6606 // Layout of pointer fields. Heap iteration code relies on them
6607 // being continuously allocated.
6608 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6609 static const int kPointerFieldsEndOffset = kBitField3Offset + kPointerSize;
6611 // Byte offsets within kInstanceSizesOffset.
6612 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6613 static const int kInObjectPropertiesByte = 1;
6614 static const int kInObjectPropertiesOffset =
6615 kInstanceSizesOffset + kInObjectPropertiesByte;
6616 static const int kPreAllocatedPropertyFieldsByte = 2;
6617 static const int kPreAllocatedPropertyFieldsOffset =
6618 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6619 static const int kVisitorIdByte = 3;
6620 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6622 // Byte offsets within kInstanceAttributesOffset attributes.
6623 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6624 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
6625 static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
6626 static const int kBitField2Offset = kInstanceAttributesOffset + 3;
6628 STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
6630 // Bit positions for bit field.
6631 static const int kUnused = 0; // To be used for marking recently used maps.
6632 static const int kHasNonInstancePrototype = 1;
6633 static const int kIsHiddenPrototype = 2;
6634 static const int kHasNamedInterceptor = 3;
6635 static const int kHasIndexedInterceptor = 4;
6636 static const int kIsUndetectable = 5;
6637 static const int kIsObserved = 6;
6638 static const int kIsAccessCheckNeeded = 7;
6640 // Bit positions for bit field 2
6641 static const int kIsExtensible = 0;
6642 static const int kStringWrapperSafeForDefaultValueOf = 1;
6643 static const int kAttachedToSharedFunctionInfo = 2;
6644 // No bits can be used after kElementsKindFirstBit, they are all reserved for
6645 // storing ElementKind.
6646 static const int kElementsKindShift = 3;
6647 static const int kElementsKindBitCount = 5;
6649 // Derived values from bit field 2
6650 static const int kElementsKindMask = (-1 << kElementsKindShift) &
6651 ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
6652 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6653 (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
6654 static const int8_t kMaximumBitField2FastSmiElementValue =
6655 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6656 Map::kElementsKindShift) - 1;
6657 static const int8_t kMaximumBitField2FastHoleyElementValue =
6658 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6659 Map::kElementsKindShift) - 1;
6660 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6661 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6662 Map::kElementsKindShift) - 1;
6664 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6665 kPointerFieldsEndOffset,
6666 kSize> BodyDescriptor;
6669 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6673 // An abstract superclass, a marker class really, for simple structure classes.
6674 // It doesn't carry much functionality but allows struct classes to be
6675 // identified in the type system.
6676 class Struct: public HeapObject {
6678 inline void InitializeBody(int object_size);
6679 static inline Struct* cast(Object* that);
6683 // A simple one-element struct, useful where smis need to be boxed.
6684 class Box : public Struct {
6686 // [value]: the boxed contents.
6687 DECL_ACCESSORS(value, Object)
6689 static inline Box* cast(Object* obj);
6691 // Dispatched behavior.
6692 DECLARE_PRINTER(Box)
6693 DECLARE_VERIFIER(Box)
6695 static const int kValueOffset = HeapObject::kHeaderSize;
6696 static const int kSize = kValueOffset + kPointerSize;
6699 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6703 // Script describes a script which has been added to the VM.
6704 class Script: public Struct {
6713 // Script compilation types.
6714 enum CompilationType {
6715 COMPILATION_TYPE_HOST = 0,
6716 COMPILATION_TYPE_EVAL = 1
6719 // Script compilation state.
6720 enum CompilationState {
6721 COMPILATION_STATE_INITIAL = 0,
6722 COMPILATION_STATE_COMPILED = 1
6725 // [source]: the script source.
6726 DECL_ACCESSORS(source, Object)
6728 // [name]: the script name.
6729 DECL_ACCESSORS(name, Object)
6731 // [id]: the script id.
6732 DECL_ACCESSORS(id, Smi)
6734 // [line_offset]: script line offset in resource from where it was extracted.
6735 DECL_ACCESSORS(line_offset, Smi)
6737 // [column_offset]: script column offset in resource from where it was
6739 DECL_ACCESSORS(column_offset, Smi)
6741 // [context_data]: context data for the context this script was compiled in.
6742 DECL_ACCESSORS(context_data, Object)
6744 // [wrapper]: the wrapper cache.
6745 DECL_ACCESSORS(wrapper, Foreign)
6747 // [type]: the script type.
6748 DECL_ACCESSORS(type, Smi)
6750 // [line_ends]: FixedArray of line ends positions.
6751 DECL_ACCESSORS(line_ends, Object)
6753 // [eval_from_shared]: for eval scripts the shared funcion info for the
6754 // function from which eval was called.
6755 DECL_ACCESSORS(eval_from_shared, Object)
6757 // [eval_from_instructions_offset]: the instruction offset in the code for the
6758 // function from which eval was called where eval was called.
6759 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6761 // [flags]: Holds an exciting bitfield.
6762 DECL_ACCESSORS(flags, Smi)
6764 // [compilation_type]: how the the script was compiled. Encoded in the
6766 inline CompilationType compilation_type();
6767 inline void set_compilation_type(CompilationType type);
6769 // [compilation_state]: determines whether the script has already been
6770 // compiled. Encoded in the 'flags' field.
6771 inline CompilationState compilation_state();
6772 inline void set_compilation_state(CompilationState state);
6774 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6775 // ScriptOrigin, and used by the embedder to make decisions about the
6776 // script's level of privilege. V8 just passes this through. Encoded in
6777 // the 'flags' field.
6778 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6780 static inline Script* cast(Object* obj);
6782 // If script source is an external string, check that the underlying
6783 // resource is accessible. Otherwise, always return true.
6784 inline bool HasValidSource();
6786 // Dispatched behavior.
6787 DECLARE_PRINTER(Script)
6788 DECLARE_VERIFIER(Script)
6790 static const int kSourceOffset = HeapObject::kHeaderSize;
6791 static const int kNameOffset = kSourceOffset + kPointerSize;
6792 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6793 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6794 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6795 static const int kWrapperOffset = kContextOffset + kPointerSize;
6796 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6797 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6798 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6799 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6800 static const int kEvalFrominstructionsOffsetOffset =
6801 kEvalFromSharedOffset + kPointerSize;
6802 static const int kFlagsOffset =
6803 kEvalFrominstructionsOffsetOffset + kPointerSize;
6804 static const int kSize = kFlagsOffset + kPointerSize;
6807 // Bit positions in the flags field.
6808 static const int kCompilationTypeBit = 0;
6809 static const int kCompilationStateBit = 1;
6810 static const int kIsSharedCrossOriginBit = 2;
6812 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6816 // List of builtin functions we want to identify to improve code
6819 // Each entry has a name of a global object property holding an object
6820 // optionally followed by ".prototype", a name of a builtin function
6821 // on the object (the one the id is set for), and a label.
6823 // Installation of ids for the selected builtin functions is handled
6824 // by the bootstrapper.
6825 #define FUNCTIONS_WITH_ID_LIST(V) \
6826 V(Array.prototype, push, ArrayPush) \
6827 V(Array.prototype, pop, ArrayPop) \
6828 V(Function.prototype, apply, FunctionApply) \
6829 V(String.prototype, charCodeAt, StringCharCodeAt) \
6830 V(String.prototype, charAt, StringCharAt) \
6831 V(String, fromCharCode, StringFromCharCode) \
6832 V(Math, floor, MathFloor) \
6833 V(Math, round, MathRound) \
6834 V(Math, ceil, MathCeil) \
6835 V(Math, abs, MathAbs) \
6836 V(Math, log, MathLog) \
6837 V(Math, exp, MathExp) \
6838 V(Math, sqrt, MathSqrt) \
6839 V(Math, pow, MathPow) \
6840 V(Math, max, MathMax) \
6841 V(Math, min, MathMin) \
6842 V(Math, imul, MathImul)
6844 #define SIMD_NULLARY_OPERATIONS(V) \
6845 V(SIMD.float32x4, zero, Float32x4Zero, Float32x4) \
6846 V(SIMD.int32x4, zero, Int32x4Zero, Int32x4)
6848 #define SIMD_UNARY_OPERATIONS(V) \
6849 V(SIMD.float32x4, abs, Float32x4Abs, Float32x4, Float32x4) \
6850 V(SIMD.float32x4, bitsToInt32x4, Float32x4BitsToInt32x4, Int32x4, Float32x4) \
6851 V(SIMD.float32x4, neg, Float32x4Neg, Float32x4, Float32x4) \
6852 V(SIMD.float32x4, reciprocal, Float32x4Reciprocal, Float32x4, Float32x4) \
6853 V(SIMD.float32x4, reciprocalSqrt, Float32x4ReciprocalSqrt, \
6854 Float32x4, Float32x4) \
6855 V(SIMD.float32x4, splat, Float32x4Splat, Float32x4, Double) \
6856 V(SIMD.float32x4, sqrt, Float32x4Sqrt, Float32x4, Float32x4) \
6857 V(SIMD.float32x4, toInt32x4, Float32x4ToInt32x4, Int32x4, Float32x4) \
6858 V(SIMD.int32x4, bitsToFloat32x4, Int32x4BitsToFloat32x4, Float32x4, Int32x4) \
6859 V(SIMD.int32x4, neg, Int32x4Neg, Int32x4, Int32x4) \
6860 V(SIMD.int32x4, not, Int32x4Not, Int32x4, Int32x4) \
6861 V(SIMD.int32x4, splat, Int32x4Splat, Int32x4, Integer32) \
6862 V(SIMD.int32x4, toFloat32x4, Int32x4ToFloat32x4, Float32x4, Int32x4)
6864 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6865 #define SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(V) \
6866 V(SIMD.float32x4.prototype, signMask, Float32x4GetSignMask, Integer32, \
6868 V(SIMD.float32x4.prototype, x, Float32x4GetX, Double, Float32x4) \
6869 V(SIMD.float32x4.prototype, y, Float32x4GetY, Double, Float32x4) \
6870 V(SIMD.float32x4.prototype, z, Float32x4GetZ, Double, Float32x4) \
6871 V(SIMD.float32x4.prototype, w, Float32x4GetW, Double, Float32x4) \
6872 V(SIMD.int32x4.prototype, signMask, Int32x4GetSignMask, Integer32, Int32x4) \
6873 V(SIMD.int32x4.prototype, x, Int32x4GetX, Integer32, Int32x4) \
6874 V(SIMD.int32x4.prototype, y, Int32x4GetY, Integer32, Int32x4) \
6875 V(SIMD.int32x4.prototype, z, Int32x4GetZ, Integer32, Int32x4) \
6876 V(SIMD.int32x4.prototype, w, Int32x4GetW, Integer32, Int32x4) \
6877 V(SIMD.int32x4.prototype, flagX, Int32x4GetFlagX, Tagged, Int32x4) \
6878 V(SIMD.int32x4.prototype, flagY, Int32x4GetFlagY, Tagged, Int32x4) \
6879 V(SIMD.int32x4.prototype, flagZ, Int32x4GetFlagZ, Tagged, Int32x4) \
6880 V(SIMD.int32x4.prototype, flagW, Int32x4GetFlagW, Tagged, Int32x4)
6882 #define SIMD_BINARY_OPERATIONS(V) \
6883 V(SIMD.float32x4, add, Float32x4Add, Float32x4, Float32x4, Float32x4) \
6884 V(SIMD.float32x4, div, Float32x4Div, Float32x4, Float32x4, Float32x4) \
6885 V(SIMD.float32x4, max, Float32x4Max, Float32x4, Float32x4, Float32x4) \
6886 V(SIMD.float32x4, min, Float32x4Min, Float32x4, Float32x4, Float32x4) \
6887 V(SIMD.float32x4, mul, Float32x4Mul, Float32x4, Float32x4, Float32x4) \
6888 V(SIMD.float32x4, sub, Float32x4Sub, Float32x4, Float32x4, Float32x4) \
6889 V(SIMD.float32x4, equal, Float32x4Equal, Int32x4, Float32x4, Float32x4) \
6890 V(SIMD.float32x4, notEqual, Float32x4NotEqual, Int32x4, Float32x4, \
6892 V(SIMD.float32x4, greaterThan, Float32x4GreaterThan, Int32x4, Float32x4, \
6894 V(SIMD.float32x4, greaterThanOrEqual, Float32x4GreaterThanOrEqual, Int32x4, \
6895 Float32x4, Float32x4) \
6896 V(SIMD.float32x4, lessThan, Float32x4LessThan, Int32x4, Float32x4, \
6898 V(SIMD.float32x4, lessThanOrEqual, Float32x4LessThanOrEqual, Int32x4, \
6899 Float32x4, Float32x4) \
6900 V(SIMD.float32x4, shuffle, Float32x4Shuffle, Float32x4, Float32x4, \
6902 V(SIMD.float32x4, scale, Float32x4Scale, Float32x4, Float32x4, Double) \
6903 V(SIMD.float32x4, withX, Float32x4WithX, Float32x4, Float32x4, Double) \
6904 V(SIMD.float32x4, withY, Float32x4WithY, Float32x4, Float32x4, Double) \
6905 V(SIMD.float32x4, withZ, Float32x4WithZ, Float32x4, Float32x4, Double) \
6906 V(SIMD.float32x4, withW, Float32x4WithW, Float32x4, Float32x4, Double) \
6907 V(SIMD.int32x4, add, Int32x4Add, Int32x4, Int32x4, Int32x4) \
6908 V(SIMD.int32x4, and, Int32x4And, Int32x4, Int32x4, Int32x4) \
6909 V(SIMD.int32x4, mul, Int32x4Mul, Int32x4, Int32x4, Int32x4) \
6910 V(SIMD.int32x4, or, Int32x4Or, Int32x4, Int32x4, Int32x4) \
6911 V(SIMD.int32x4, sub, Int32x4Sub, Int32x4, Int32x4, Int32x4) \
6912 V(SIMD.int32x4, xor, Int32x4Xor, Int32x4, Int32x4, Int32x4) \
6913 V(SIMD.int32x4, shuffle, Int32x4Shuffle, Int32x4, Int32x4, Integer32) \
6914 V(SIMD.int32x4, withX, Int32x4WithX, Int32x4, Int32x4, Integer32) \
6915 V(SIMD.int32x4, withY, Int32x4WithY, Int32x4, Int32x4, Integer32) \
6916 V(SIMD.int32x4, withZ, Int32x4WithZ, Int32x4, Int32x4, Integer32) \
6917 V(SIMD.int32x4, withW, Int32x4WithW, Int32x4, Int32x4, Integer32) \
6918 V(SIMD.int32x4, withFlagX, Int32x4WithFlagX, Int32x4, Int32x4, Tagged) \
6919 V(SIMD.int32x4, withFlagY, Int32x4WithFlagY, Int32x4, Int32x4, Tagged) \
6920 V(SIMD.int32x4, withFlagZ, Int32x4WithFlagZ, Int32x4, Int32x4, Tagged) \
6921 V(SIMD.int32x4, withFlagW, Int32x4WithFlagW, Int32x4, Int32x4, Tagged) \
6922 V(SIMD.int32x4, greaterThan, Int32x4GreaterThan, Int32x4, Int32x4, Int32x4) \
6923 V(SIMD.int32x4, equal, Int32x4Equal, Int32x4, Int32x4, Int32x4) \
6924 V(SIMD.int32x4, lessThan, Int32x4LessThan, Int32x4, Int32x4, Int32x4) \
6925 V(SIMD.int32x4, shiftLeft, Int32x4ShiftLeft, Int32x4, Int32x4, Integer32) \
6926 V(SIMD.int32x4, shiftRight, Int32x4ShiftRight, Int32x4, Int32x4, Integer32) \
6927 V(SIMD.int32x4, shiftRightArithmetic, Int32x4ShiftRightArithmetic, Int32x4, \
6930 #define SIMD_TERNARY_OPERATIONS(V) \
6931 V(SIMD.float32x4, clamp, Float32x4Clamp, Float32x4, Float32x4, Float32x4, \
6933 V(SIMD.float32x4, shuffleMix, Float32x4ShuffleMix, Float32x4, Float32x4, \
6934 Float32x4, Integer32) \
6935 V(SIMD.int32x4, select, Int32x4Select, Float32x4, Int32x4, Float32x4, \
6938 #define SIMD_QUARTERNARY_OPERATIONS(V) \
6939 V(SIMD, float32x4, Float32x4Constructor, Float32x4, Double, Double, Double, \
6941 V(SIMD, int32x4, Int32x4Constructor, Int32x4, Integer32, Integer32, \
6942 Integer32, Integer32) \
6943 V(SIMD.int32x4, bool, Int32x4Bool, Int32x4, Tagged, Tagged, Tagged, Tagged)
6945 #define SIMD_ARRAY_OPERATIONS(V) \
6946 V(Float32x4Array.prototype, getAt, Float32x4ArrayGetAt) \
6947 V(Float32x4Array.prototype, setAt, Float32x4ArraySetAt) \
6948 V(Int32x4Array.prototype, getAt, Int32x4ArrayGetAt) \
6949 V(Int32x4Array.prototype, setAt, Int32x4ArraySetAt)
6951 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6952 #define SIMD_FAKE_ID_LISTS(V) \
6953 V(SIMD, unreachable, SIMD128Unreachable) \
6954 V(SIMD, change, SIMD128Change)
6956 enum BuiltinFunctionId {
6958 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6960 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6961 // Fake id for a special case of Math.pow. Note, it continues the
6962 // list of math functions.
6964 // Installed only on --harmony-maths.
6966 SIMD_FAKE_ID_LISTS(DECLARE_FUNCTION_ID)
6967 SIMD_ARRAY_OPERATIONS(DECLARE_FUNCTION_ID)
6968 #undef DECLARE_FUNCTION_ID
6969 #define DECLARE_SIMD_NULLARY_FUNCTION_ID(i1, i2, name, i3) \
6971 SIMD_NULLARY_OPERATIONS(DECLARE_SIMD_NULLARY_FUNCTION_ID)
6972 #undef DECLARE_SIMD_NULLARY_FUNCTION_ID
6973 #define DECLARE_SIMD_UNARY_FUNCTION_ID(i1, i2, name, i3, i4) \
6975 SIMD_UNARY_OPERATIONS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6976 SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6977 #undef DECLARE_SIMD_UNARY_FUNCTION_ID
6978 #define DECLARE_SIMD_BINARY_FUNCTION_ID(i1, i2, name, i3, i4, i5) \
6980 SIMD_BINARY_OPERATIONS(DECLARE_SIMD_BINARY_FUNCTION_ID)
6981 #undef DECLARE_SIMD_BINARY_FUNCTION_ID
6982 #define DECLARE_SIMD_TERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6) \
6984 SIMD_TERNARY_OPERATIONS(DECLARE_SIMD_TERNARY_FUNCTION_ID)
6985 #undef DECLARE_SIMD_TERNARY_FUNCTION_ID
6986 #define DECLARE_SIMD_QUARTERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6, i7) \
6988 SIMD_QUARTERNARY_OPERATIONS(DECLARE_SIMD_QUARTERNARY_FUNCTION_ID)
6989 #undef DECLARE_SIMD_QUARTERNARY_FUNCTION_ID
6990 kNumberOfBuiltinFunction
6994 // SharedFunctionInfo describes the JSFunction information that can be
6995 // shared by multiple instances of the function.
6996 class SharedFunctionInfo: public HeapObject {
6998 // [name]: Function name.
6999 DECL_ACCESSORS(name, Object)
7001 // [code]: Function code.
7002 DECL_ACCESSORS(code, Code)
7003 inline void ReplaceCode(Code* code);
7005 // [optimized_code_map]: Map from native context to optimized code
7006 // and a shared literals array or Smi(0) if none.
7007 DECL_ACCESSORS(optimized_code_map, Object)
7009 // Returns index i of the entry with the specified context and OSR entry.
7010 // At position i - 1 is the context, position i the code, and i + 1 the
7011 // literals array. Returns -1 when no matching entry is found.
7012 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
7014 // Installs optimized code from the code map on the given closure. The
7015 // index has to be consistent with a search result as defined above.
7016 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
7018 Code* GetCodeFromOptimizedCodeMap(int index);
7020 // Clear optimized code map.
7021 void ClearOptimizedCodeMap();
7023 // Removed a specific optimized code object from the optimized code map.
7024 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
7026 // Trims the optimized code map after entries have been removed.
7027 void TrimOptimizedCodeMap(int shrink_by);
7029 // Add a new entry to the optimized code map.
7030 MUST_USE_RESULT MaybeObject* AddToOptimizedCodeMap(Context* native_context,
7032 FixedArray* literals,
7033 BailoutId osr_ast_id);
7034 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
7035 Handle<Context> native_context,
7037 Handle<FixedArray> literals,
7038 BailoutId osr_ast_id);
7040 // Layout description of the optimized code map.
7041 static const int kNextMapIndex = 0;
7042 static const int kEntriesStart = 1;
7043 static const int kContextOffset = 0;
7044 static const int kCachedCodeOffset = 1;
7045 static const int kLiteralsOffset = 2;
7046 static const int kOsrAstIdOffset = 3;
7047 static const int kEntryLength = 4;
7048 static const int kInitialLength = kEntriesStart + kEntryLength;
7050 // [scope_info]: Scope info.
7051 DECL_ACCESSORS(scope_info, ScopeInfo)
7053 // [construct stub]: Code stub for constructing instances of this function.
7054 DECL_ACCESSORS(construct_stub, Code)
7056 // Returns if this function has been compiled to native code yet.
7057 inline bool is_compiled();
7059 // [length]: The function length - usually the number of declared parameters.
7060 // Use up to 2^30 parameters.
7061 inline int length();
7062 inline void set_length(int value);
7064 // [formal parameter count]: The declared number of parameters.
7065 inline int formal_parameter_count();
7066 inline void set_formal_parameter_count(int value);
7068 // Set the formal parameter count so the function code will be
7069 // called without using argument adaptor frames.
7070 inline void DontAdaptArguments();
7072 // [expected_nof_properties]: Expected number of properties for the function.
7073 inline int expected_nof_properties();
7074 inline void set_expected_nof_properties(int value);
7076 // Inobject slack tracking is the way to reclaim unused inobject space.
7078 // The instance size is initially determined by adding some slack to
7079 // expected_nof_properties (to allow for a few extra properties added
7080 // after the constructor). There is no guarantee that the extra space
7081 // will not be wasted.
7083 // Here is the algorithm to reclaim the unused inobject space:
7084 // - Detect the first constructor call for this SharedFunctionInfo.
7085 // When it happens enter the "in progress" state: remember the
7086 // constructor's initial_map and install a special construct stub that
7087 // counts constructor calls.
7088 // - While the tracking is in progress create objects filled with
7089 // one_pointer_filler_map instead of undefined_value. This way they can be
7090 // resized quickly and safely.
7091 // - Once enough (kGenerousAllocationCount) objects have been created
7092 // compute the 'slack' (traverse the map transition tree starting from the
7093 // initial_map and find the lowest value of unused_property_fields).
7094 // - Traverse the transition tree again and decrease the instance size
7095 // of every map. Existing objects will resize automatically (they are
7096 // filled with one_pointer_filler_map). All further allocations will
7097 // use the adjusted instance size.
7098 // - Decrease expected_nof_properties so that an allocations made from
7099 // another context will use the adjusted instance size too.
7100 // - Exit "in progress" state by clearing the reference to the initial_map
7101 // and setting the regular construct stub (generic or inline).
7103 // The above is the main event sequence. Some special cases are possible
7104 // while the tracking is in progress:
7107 // Check if the initial_map is referenced by any live objects (except this
7108 // SharedFunctionInfo). If it is, continue tracking as usual.
7109 // If it is not, clear the reference and reset the tracking state. The
7110 // tracking will be initiated again on the next constructor call.
7112 // - The constructor is called from another context.
7113 // Immediately complete the tracking, perform all the necessary changes
7114 // to maps. This is necessary because there is no efficient way to track
7115 // multiple initial_maps.
7116 // Proceed to create an object in the current context (with the adjusted
7119 // - A different constructor function sharing the same SharedFunctionInfo is
7120 // called in the same context. This could be another closure in the same
7121 // context, or the first function could have been disposed.
7122 // This is handled the same way as the previous case.
7124 // Important: inobject slack tracking is not attempted during the snapshot
7127 static const int kGenerousAllocationCount = 8;
7129 // [construction_count]: Counter for constructor calls made during
7130 // the tracking phase.
7131 inline int construction_count();
7132 inline void set_construction_count(int value);
7134 // [initial_map]: initial map of the first function called as a constructor.
7135 // Saved for the duration of the tracking phase.
7136 // This is a weak link (GC resets it to undefined_value if no other live
7137 // object reference this map).
7138 DECL_ACCESSORS(initial_map, Object)
7140 // True if the initial_map is not undefined and the countdown stub is
7142 inline bool IsInobjectSlackTrackingInProgress();
7144 // Starts the tracking.
7145 // Stores the initial map and installs the countdown stub.
7146 // IsInobjectSlackTrackingInProgress is normally true after this call,
7147 // except when tracking have not been started (e.g. the map has no unused
7148 // properties or the snapshot is being built).
7149 void StartInobjectSlackTracking(Map* map);
7151 // Completes the tracking.
7152 // IsInobjectSlackTrackingInProgress is false after this call.
7153 void CompleteInobjectSlackTracking();
7155 // Invoked before pointers in SharedFunctionInfo are being marked.
7156 // Also clears the optimized code map.
7157 inline void BeforeVisitingPointers();
7159 // Clears the initial_map before the GC marking phase to ensure the reference
7160 // is weak. IsInobjectSlackTrackingInProgress is false after this call.
7161 void DetachInitialMap();
7163 // Restores the link to the initial map after the GC marking phase.
7164 // IsInobjectSlackTrackingInProgress is true after this call.
7165 void AttachInitialMap(Map* map);
7167 // False if there are definitely no live objects created from this function.
7168 // True if live objects _may_ exist (existence not guaranteed).
7169 // May go back from true to false after GC.
7170 DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
7172 // [instance class name]: class name for instances.
7173 DECL_ACCESSORS(instance_class_name, Object)
7175 // [function data]: This field holds some additional data for function.
7176 // Currently it either has FunctionTemplateInfo to make benefit the API
7177 // or Smi identifying a builtin function.
7178 // In the long run we don't want all functions to have this field but
7179 // we can fix that when we have a better model for storing hidden data
7181 DECL_ACCESSORS(function_data, Object)
7183 inline bool IsApiFunction();
7184 inline FunctionTemplateInfo* get_api_func_data();
7185 inline bool HasBuiltinFunctionId();
7186 inline BuiltinFunctionId builtin_function_id();
7188 // [script info]: Script from which the function originates.
7189 DECL_ACCESSORS(script, Object)
7191 // [num_literals]: Number of literals used by this function.
7192 inline int num_literals();
7193 inline void set_num_literals(int value);
7195 // [start_position_and_type]: Field used to store both the source code
7196 // position, whether or not the function is a function expression,
7197 // and whether or not the function is a toplevel function. The two
7198 // least significants bit indicates whether the function is an
7199 // expression and the rest contains the source code position.
7200 inline int start_position_and_type();
7201 inline void set_start_position_and_type(int value);
7203 // [debug info]: Debug information.
7204 DECL_ACCESSORS(debug_info, Object)
7206 // [inferred name]: Name inferred from variable or property
7207 // assignment of this function. Used to facilitate debugging and
7208 // profiling of JavaScript code written in OO style, where almost
7209 // all functions are anonymous but are assigned to object
7211 DECL_ACCESSORS(inferred_name, String)
7213 // The function's name if it is non-empty, otherwise the inferred name.
7214 String* DebugName();
7216 // Position of the 'function' token in the script source.
7217 inline int function_token_position();
7218 inline void set_function_token_position(int function_token_position);
7220 // Position of this function in the script source.
7221 inline int start_position();
7222 inline void set_start_position(int start_position);
7224 // End position of this function in the script source.
7225 inline int end_position();
7226 inline void set_end_position(int end_position);
7228 // Is this function a function expression in the source code.
7229 DECL_BOOLEAN_ACCESSORS(is_expression)
7231 // Is this function a top-level function (scripts, evals).
7232 DECL_BOOLEAN_ACCESSORS(is_toplevel)
7234 // Bit field containing various information collected by the compiler to
7235 // drive optimization.
7236 inline int compiler_hints();
7237 inline void set_compiler_hints(int value);
7239 inline int ast_node_count();
7240 inline void set_ast_node_count(int count);
7242 inline int profiler_ticks();
7244 // Inline cache age is used to infer whether the function survived a context
7245 // disposal or not. In the former case we reset the opt_count.
7246 inline int ic_age();
7247 inline void set_ic_age(int age);
7249 // Indicates if this function can be lazy compiled.
7250 // This is used to determine if we can safely flush code from a function
7251 // when doing GC if we expect that the function will no longer be used.
7252 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7254 // Indicates if this function can be lazy compiled without a context.
7255 // This is used to determine if we can force compilation without reaching
7256 // the function through program execution but through other means (e.g. heap
7257 // iteration by the debugger).
7258 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7260 // Indicates whether optimizations have been disabled for this
7261 // shared function info. If a function is repeatedly optimized or if
7262 // we cannot optimize the function we disable optimization to avoid
7263 // spending time attempting to optimize it again.
7264 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7266 // Indicates the language mode.
7267 inline StrictMode strict_mode();
7268 inline void set_strict_mode(StrictMode strict_mode);
7270 // False if the function definitely does not allocate an arguments object.
7271 DECL_BOOLEAN_ACCESSORS(uses_arguments)
7273 // True if the function has any duplicated parameter names.
7274 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7276 // Indicates whether the function is a native function.
7277 // These needs special treatment in .call and .apply since
7278 // null passed as the receiver should not be translated to the
7280 DECL_BOOLEAN_ACCESSORS(native)
7282 // Indicate that this builtin needs to be inlined in crankshaft.
7283 DECL_BOOLEAN_ACCESSORS(inline_builtin)
7285 // Indicates that the function was created by the Function function.
7286 // Though it's anonymous, toString should treat it as if it had the name
7287 // "anonymous". We don't set the name itself so that the system does not
7288 // see a binding for it.
7289 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7291 // Indicates whether the function is a bound function created using
7292 // the bind function.
7293 DECL_BOOLEAN_ACCESSORS(bound)
7295 // Indicates that the function is anonymous (the name field can be set
7296 // through the API, which does not change this flag).
7297 DECL_BOOLEAN_ACCESSORS(is_anonymous)
7299 // Is this a function or top-level/eval code.
7300 DECL_BOOLEAN_ACCESSORS(is_function)
7302 // Indicates that the function cannot be optimized.
7303 DECL_BOOLEAN_ACCESSORS(dont_optimize)
7305 // Indicates that the function cannot be inlined.
7306 DECL_BOOLEAN_ACCESSORS(dont_inline)
7308 // Indicates that code for this function cannot be cached.
7309 DECL_BOOLEAN_ACCESSORS(dont_cache)
7311 // Indicates that code for this function cannot be flushed.
7312 DECL_BOOLEAN_ACCESSORS(dont_flush)
7314 // Indicates that this function is a generator.
7315 DECL_BOOLEAN_ACCESSORS(is_generator)
7317 // Indicates whether or not the code in the shared function support
7319 inline bool has_deoptimization_support();
7321 // Enable deoptimization support through recompiled code.
7322 void EnableDeoptimizationSupport(Code* recompiled);
7324 // Disable (further) attempted optimization of all functions sharing this
7325 // shared function info.
7326 void DisableOptimization(BailoutReason reason);
7328 inline BailoutReason DisableOptimizationReason();
7330 // Lookup the bailout ID and ASSERT that it exists in the non-optimized
7331 // code, returns whether it asserted (i.e., always true if assertions are
7333 bool VerifyBailoutId(BailoutId id);
7335 // [source code]: Source code for the function.
7336 bool HasSourceCode();
7337 Handle<Object> GetSourceCode();
7339 // Number of times the function was optimized.
7340 inline int opt_count();
7341 inline void set_opt_count(int opt_count);
7343 // Number of times the function was deoptimized.
7344 inline void set_deopt_count(int value);
7345 inline int deopt_count();
7346 inline void increment_deopt_count();
7348 // Number of time we tried to re-enable optimization after it
7349 // was disabled due to high number of deoptimizations.
7350 inline void set_opt_reenable_tries(int value);
7351 inline int opt_reenable_tries();
7353 inline void TryReenableOptimization();
7355 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7356 inline void set_counters(int value);
7357 inline int counters();
7359 // Stores opt_count and bailout_reason as bit-fields.
7360 inline void set_opt_count_and_bailout_reason(int value);
7361 inline int opt_count_and_bailout_reason();
7363 void set_bailout_reason(BailoutReason reason) {
7364 set_opt_count_and_bailout_reason(
7365 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7369 void set_dont_optimize_reason(BailoutReason reason) {
7370 set_bailout_reason(reason);
7371 set_dont_optimize(reason != kNoReason);
7374 // Check whether or not this function is inlineable.
7375 bool IsInlineable();
7377 // Source size of this function.
7380 // Calculate the instance size.
7381 int CalculateInstanceSize();
7383 // Calculate the number of in-object properties.
7384 int CalculateInObjectProperties();
7386 // Dispatched behavior.
7387 // Set max_length to -1 for unlimited length.
7388 void SourceCodePrint(StringStream* accumulator, int max_length);
7389 DECLARE_PRINTER(SharedFunctionInfo)
7390 DECLARE_VERIFIER(SharedFunctionInfo)
7392 void ResetForNewContext(int new_ic_age);
7395 static inline SharedFunctionInfo* cast(Object* obj);
7398 static const int kDontAdaptArgumentsSentinel = -1;
7400 // Layout description.
7402 static const int kNameOffset = HeapObject::kHeaderSize;
7403 static const int kCodeOffset = kNameOffset + kPointerSize;
7404 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7405 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7406 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7407 static const int kInstanceClassNameOffset =
7408 kConstructStubOffset + kPointerSize;
7409 static const int kFunctionDataOffset =
7410 kInstanceClassNameOffset + kPointerSize;
7411 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7412 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7413 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7414 static const int kInitialMapOffset =
7415 kInferredNameOffset + kPointerSize;
7416 // ast_node_count is a Smi field. It could be grouped with another Smi field
7417 // into a PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
7418 static const int kAstNodeCountOffset =
7419 kInitialMapOffset + kPointerSize;
7420 #if V8_HOST_ARCH_32_BIT
7422 static const int kLengthOffset =
7423 kAstNodeCountOffset + kPointerSize;
7424 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7425 static const int kExpectedNofPropertiesOffset =
7426 kFormalParameterCountOffset + kPointerSize;
7427 static const int kNumLiteralsOffset =
7428 kExpectedNofPropertiesOffset + kPointerSize;
7429 static const int kStartPositionAndTypeOffset =
7430 kNumLiteralsOffset + kPointerSize;
7431 static const int kEndPositionOffset =
7432 kStartPositionAndTypeOffset + kPointerSize;
7433 static const int kFunctionTokenPositionOffset =
7434 kEndPositionOffset + kPointerSize;
7435 static const int kCompilerHintsOffset =
7436 kFunctionTokenPositionOffset + kPointerSize;
7437 static const int kOptCountAndBailoutReasonOffset =
7438 kCompilerHintsOffset + kPointerSize;
7439 static const int kCountersOffset =
7440 kOptCountAndBailoutReasonOffset + kPointerSize;
7443 static const int kSize = kCountersOffset + kPointerSize;
7445 // The only reason to use smi fields instead of int fields
7446 // is to allow iteration without maps decoding during
7447 // garbage collections.
7448 // To avoid wasting space on 64-bit architectures we use
7449 // the following trick: we group integer fields into pairs
7450 // First integer in each pair is shifted left by 1.
7451 // By doing this we guarantee that LSB of each kPointerSize aligned
7452 // word is not set and thus this word cannot be treated as pointer
7453 // to HeapObject during old space traversal.
7454 static const int kLengthOffset =
7455 kAstNodeCountOffset + kPointerSize;
7456 static const int kFormalParameterCountOffset =
7457 kLengthOffset + kIntSize;
7459 static const int kExpectedNofPropertiesOffset =
7460 kFormalParameterCountOffset + kIntSize;
7461 static const int kNumLiteralsOffset =
7462 kExpectedNofPropertiesOffset + kIntSize;
7464 static const int kEndPositionOffset =
7465 kNumLiteralsOffset + kIntSize;
7466 static const int kStartPositionAndTypeOffset =
7467 kEndPositionOffset + kIntSize;
7469 static const int kFunctionTokenPositionOffset =
7470 kStartPositionAndTypeOffset + kIntSize;
7471 static const int kCompilerHintsOffset =
7472 kFunctionTokenPositionOffset + kIntSize;
7474 static const int kOptCountAndBailoutReasonOffset =
7475 kCompilerHintsOffset + kIntSize;
7477 static const int kCountersOffset =
7478 kOptCountAndBailoutReasonOffset + kIntSize;
7481 static const int kSize = kCountersOffset + kIntSize;
7485 // The construction counter for inobject slack tracking is stored in the
7486 // most significant byte of compiler_hints which is otherwise unused.
7487 // Its offset depends on the endian-ness of the architecture.
7488 #if __BYTE_ORDER == __LITTLE_ENDIAN
7489 static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
7490 #elif __BYTE_ORDER == __BIG_ENDIAN
7491 static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
7493 #error Unknown byte ordering
7496 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7498 typedef FixedBodyDescriptor<kNameOffset,
7499 kInitialMapOffset + kPointerSize,
7500 kSize> BodyDescriptor;
7502 // Bit positions in start_position_and_type.
7503 // The source code start position is in the 30 most significant bits of
7504 // the start_position_and_type field.
7505 static const int kIsExpressionBit = 0;
7506 static const int kIsTopLevelBit = 1;
7507 static const int kStartPositionShift = 2;
7508 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7510 // Bit positions in compiler_hints.
7511 enum CompilerHints {
7512 kAllowLazyCompilation,
7513 kAllowLazyCompilationWithoutContext,
7514 kLiveObjectsMayExist,
7515 kOptimizationDisabled,
7516 kStrictModeFunction,
7518 kHasDuplicateParameters,
7523 kNameShouldPrintAsAnonymous,
7530 kCompilerHintsCount // Pseudo entry
7533 class DeoptCountBits: public BitField<int, 0, 4> {};
7534 class OptReenableTriesBits: public BitField<int, 4, 18> {};
7535 class ICAgeBits: public BitField<int, 22, 8> {};
7537 class OptCountBits: public BitField<int, 0, 22> {};
7538 class DisabledOptimizationReasonBits: public BitField<int, 22, 8> {};
7541 #if V8_HOST_ARCH_32_BIT
7542 // On 32 bit platforms, compiler hints is a smi.
7543 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7544 static const int kCompilerHintsSize = kPointerSize;
7546 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7547 static const int kCompilerHintsSmiTagSize = 0;
7548 static const int kCompilerHintsSize = kIntSize;
7551 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7552 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7555 // Constants for optimizing codegen for strict mode function and
7557 // Allows to use byte-width instructions.
7558 static const int kStrictModeBitWithinByte =
7559 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7561 static const int kNativeBitWithinByte =
7562 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7564 #if __BYTE_ORDER == __LITTLE_ENDIAN
7565 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7566 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7567 static const int kNativeByteOffset = kCompilerHintsOffset +
7568 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7569 #elif __BYTE_ORDER == __BIG_ENDIAN
7570 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7571 (kCompilerHintsSize - 1) -
7572 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7573 static const int kNativeByteOffset = kCompilerHintsOffset +
7574 (kCompilerHintsSize - 1) -
7575 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7577 #error Unknown byte ordering
7581 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7585 class JSGeneratorObject: public JSObject {
7587 // [function]: The function corresponding to this generator object.
7588 DECL_ACCESSORS(function, JSFunction)
7590 // [context]: The context of the suspended computation.
7591 DECL_ACCESSORS(context, Context)
7593 // [receiver]: The receiver of the suspended computation.
7594 DECL_ACCESSORS(receiver, Object)
7596 // [continuation]: Offset into code of continuation.
7598 // A positive offset indicates a suspended generator. The special
7599 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7600 // cannot be resumed.
7601 inline int continuation();
7602 inline void set_continuation(int continuation);
7604 // [operand_stack]: Saved operand stack.
7605 DECL_ACCESSORS(operand_stack, FixedArray)
7607 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7608 // if the captured activation had no stack handler.
7609 inline int stack_handler_index();
7610 inline void set_stack_handler_index(int stack_handler_index);
7613 static inline JSGeneratorObject* cast(Object* obj);
7615 // Dispatched behavior.
7616 DECLARE_PRINTER(JSGeneratorObject)
7617 DECLARE_VERIFIER(JSGeneratorObject)
7619 // Magic sentinel values for the continuation.
7620 static const int kGeneratorExecuting = -1;
7621 static const int kGeneratorClosed = 0;
7623 // Layout description.
7624 static const int kFunctionOffset = JSObject::kHeaderSize;
7625 static const int kContextOffset = kFunctionOffset + kPointerSize;
7626 static const int kReceiverOffset = kContextOffset + kPointerSize;
7627 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7628 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7629 static const int kStackHandlerIndexOffset =
7630 kOperandStackOffset + kPointerSize;
7631 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7633 // Resume mode, for use by runtime functions.
7634 enum ResumeMode { NEXT, THROW };
7636 // Yielding from a generator returns an object with the following inobject
7637 // properties. See Context::generator_result_map() for the map.
7638 static const int kResultValuePropertyIndex = 0;
7639 static const int kResultDonePropertyIndex = 1;
7640 static const int kResultPropertyCount = 2;
7642 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7643 static const int kResultDonePropertyOffset =
7644 kResultValuePropertyOffset + kPointerSize;
7645 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7648 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7652 // Representation for module instance objects.
7653 class JSModule: public JSObject {
7655 // [context]: the context holding the module's locals, or undefined if none.
7656 DECL_ACCESSORS(context, Object)
7658 // [scope_info]: Scope info.
7659 DECL_ACCESSORS(scope_info, ScopeInfo)
7662 static inline JSModule* cast(Object* obj);
7664 // Dispatched behavior.
7665 DECLARE_PRINTER(JSModule)
7666 DECLARE_VERIFIER(JSModule)
7668 // Layout description.
7669 static const int kContextOffset = JSObject::kHeaderSize;
7670 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7671 static const int kSize = kScopeInfoOffset + kPointerSize;
7674 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7678 // JSFunction describes JavaScript functions.
7679 class JSFunction: public JSObject {
7681 // [prototype_or_initial_map]:
7682 DECL_ACCESSORS(prototype_or_initial_map, Object)
7684 // [shared]: The information about the function that
7685 // can be shared by instances.
7686 DECL_ACCESSORS(shared, SharedFunctionInfo)
7688 // [context]: The context for this function.
7689 inline Context* context();
7690 inline void set_context(Object* context);
7692 // [code]: The generated code object for this function. Executed
7693 // when the function is invoked, e.g. foo() or new foo(). See
7694 // [[Call]] and [[Construct]] description in ECMA-262, section
7696 inline Code* code();
7697 inline void set_code(Code* code);
7698 inline void set_code_no_write_barrier(Code* code);
7699 inline void ReplaceCode(Code* code);
7701 // Tells whether this function is builtin.
7702 inline bool IsBuiltin();
7704 // Tells whether or not the function needs arguments adaption.
7705 inline bool NeedsArgumentsAdaption();
7707 // Tells whether or not this function has been optimized.
7708 inline bool IsOptimized();
7710 // Tells whether or not this function can be optimized.
7711 inline bool IsOptimizable();
7713 // Mark this function for lazy recompilation. The function will be
7714 // recompiled the next time it is executed.
7715 void MarkForOptimization();
7716 void MarkForConcurrentOptimization();
7717 void MarkInOptimizationQueue();
7719 // Tells whether or not the function is already marked for lazy
7721 inline bool IsMarkedForOptimization();
7722 inline bool IsMarkedForConcurrentOptimization();
7724 // Tells whether or not the function is on the concurrent recompilation queue.
7725 inline bool IsInOptimizationQueue();
7727 // [literals_or_bindings]: Fixed array holding either
7728 // the materialized literals or the bindings of a bound function.
7730 // If the function contains object, regexp or array literals, the
7731 // literals array prefix contains the object, regexp, and array
7732 // function to be used when creating these literals. This is
7733 // necessary so that we do not dynamically lookup the object, regexp
7734 // or array functions. Performing a dynamic lookup, we might end up
7735 // using the functions from a new context that we should not have
7738 // On bound functions, the array is a (copy-on-write) fixed-array containing
7739 // the function that was bound, bound this-value and any bound
7740 // arguments. Bound functions never contain literals.
7741 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7743 inline FixedArray* literals();
7744 inline void set_literals(FixedArray* literals);
7746 inline FixedArray* function_bindings();
7747 inline void set_function_bindings(FixedArray* bindings);
7749 // The initial map for an object created by this constructor.
7750 inline Map* initial_map();
7751 inline void set_initial_map(Map* value);
7752 inline bool has_initial_map();
7753 static void EnsureHasInitialMap(Handle<JSFunction> function);
7755 // Get and set the prototype property on a JSFunction. If the
7756 // function has an initial map the prototype is set on the initial
7757 // map. Otherwise, the prototype is put in the initial map field
7758 // until an initial map is needed.
7759 inline bool has_prototype();
7760 inline bool has_instance_prototype();
7761 inline Object* prototype();
7762 inline Object* instance_prototype();
7763 static void SetPrototype(Handle<JSFunction> function,
7764 Handle<Object> value);
7765 static void SetInstancePrototype(Handle<JSFunction> function,
7766 Handle<Object> value);
7768 // After prototype is removed, it will not be created when accessed, and
7769 // [[Construct]] from this function will not be allowed.
7770 void RemovePrototype();
7771 inline bool should_have_prototype();
7773 // Accessor for this function's initial map's [[class]]
7774 // property. This is primarily used by ECMA native functions. This
7775 // method sets the class_name field of this function's initial map
7776 // to a given value. It creates an initial map if this function does
7777 // not have one. Note that this method does not copy the initial map
7778 // if it has one already, but simply replaces it with the new value.
7779 // Instances created afterwards will have a map whose [[class]] is
7780 // set to 'value', but there is no guarantees on instances created
7782 void SetInstanceClassName(String* name);
7784 // Returns if this function has been compiled to native code yet.
7785 inline bool is_compiled();
7787 // [next_function_link]: Links functions into various lists, e.g. the list
7788 // of optimized functions hanging off the native_context. The CodeFlusher
7789 // uses this link to chain together flushing candidates. Treated weakly
7790 // by the garbage collector.
7791 DECL_ACCESSORS(next_function_link, Object)
7793 // Prints the name of the function using PrintF.
7794 void PrintName(FILE* out = stdout);
7797 static inline JSFunction* cast(Object* obj);
7799 // Iterates the objects, including code objects indirectly referenced
7800 // through pointers to the first instruction in the code object.
7801 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7803 // Dispatched behavior.
7804 DECLARE_PRINTER(JSFunction)
7805 DECLARE_VERIFIER(JSFunction)
7807 // Returns the number of allocated literals.
7808 inline int NumberOfLiterals();
7810 // Retrieve the native context from a function's literal array.
7811 static Context* NativeContextFromLiterals(FixedArray* literals);
7813 // Used for flags such as --hydrogen-filter.
7814 bool PassesFilter(const char* raw_filter);
7816 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7817 // kSize) is weak and has special handling during garbage collection.
7818 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7819 static const int kPrototypeOrInitialMapOffset =
7820 kCodeEntryOffset + kPointerSize;
7821 static const int kSharedFunctionInfoOffset =
7822 kPrototypeOrInitialMapOffset + kPointerSize;
7823 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7824 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7825 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7826 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7827 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7829 // Layout of the literals array.
7830 static const int kLiteralsPrefixSize = 1;
7831 static const int kLiteralNativeContextIndex = 0;
7833 // Layout of the bound-function binding array.
7834 static const int kBoundFunctionIndex = 0;
7835 static const int kBoundThisIndex = 1;
7836 static const int kBoundArgumentsStartIndex = 2;
7839 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7843 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7844 // and the prototype is hidden. JSGlobalProxy always delegates
7845 // property accesses to its prototype if the prototype is not null.
7847 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7849 // Accessing a JSGlobalProxy requires security check.
7851 class JSGlobalProxy : public JSObject {
7853 // [native_context]: the owner native context of this global proxy object.
7854 // It is null value if this object is not used by any context.
7855 DECL_ACCESSORS(native_context, Object)
7858 static inline JSGlobalProxy* cast(Object* obj);
7860 inline bool IsDetachedFrom(GlobalObject* global);
7862 // Dispatched behavior.
7863 DECLARE_PRINTER(JSGlobalProxy)
7864 DECLARE_VERIFIER(JSGlobalProxy)
7866 // Layout description.
7867 static const int kNativeContextOffset = JSObject::kHeaderSize;
7868 static const int kSize = kNativeContextOffset + kPointerSize;
7871 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7875 // Forward declaration.
7876 class JSBuiltinsObject;
7878 // Common super class for JavaScript global objects and the special
7879 // builtins global objects.
7880 class GlobalObject: public JSObject {
7882 // [builtins]: the object holding the runtime routines written in JS.
7883 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7885 // [native context]: the natives corresponding to this global object.
7886 DECL_ACCESSORS(native_context, Context)
7888 // [global context]: the most recent (i.e. innermost) global context.
7889 DECL_ACCESSORS(global_context, Context)
7891 // [global receiver]: the global receiver object of the context
7892 DECL_ACCESSORS(global_receiver, JSObject)
7894 // Retrieve the property cell used to store a property.
7895 PropertyCell* GetPropertyCell(LookupResult* result);
7897 // This is like GetProperty, but is used when you know the lookup won't fail
7898 // by throwing an exception. This is for the debug and builtins global
7899 // objects, where it is known which properties can be expected to be present
7901 Object* GetPropertyNoExceptionThrown(Name* key) {
7902 Object* answer = GetProperty(key)->ToObjectUnchecked();
7907 static inline GlobalObject* cast(Object* obj);
7909 // Layout description.
7910 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7911 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7912 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7913 static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
7914 static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
7917 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7921 // JavaScript global object.
7922 class JSGlobalObject: public GlobalObject {
7925 static inline JSGlobalObject* cast(Object* obj);
7927 // Ensure that the global object has a cell for the given property name.
7928 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7931 inline bool IsDetached();
7933 // Dispatched behavior.
7934 DECLARE_PRINTER(JSGlobalObject)
7935 DECLARE_VERIFIER(JSGlobalObject)
7937 // Layout description.
7938 static const int kSize = GlobalObject::kHeaderSize;
7941 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7945 // Builtins global object which holds the runtime routines written in
7947 class JSBuiltinsObject: public GlobalObject {
7949 // Accessors for the runtime routines written in JavaScript.
7950 inline Object* javascript_builtin(Builtins::JavaScript id);
7951 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7953 // Accessors for code of the runtime routines written in JavaScript.
7954 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7955 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7958 static inline JSBuiltinsObject* cast(Object* obj);
7960 // Dispatched behavior.
7961 DECLARE_PRINTER(JSBuiltinsObject)
7962 DECLARE_VERIFIER(JSBuiltinsObject)
7964 // Layout description. The size of the builtins object includes
7965 // room for two pointers per runtime routine written in javascript
7966 // (function and code object).
7967 static const int kJSBuiltinsCount = Builtins::id_count;
7968 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7969 static const int kJSBuiltinsCodeOffset =
7970 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7971 static const int kSize =
7972 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7974 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7975 return kJSBuiltinsOffset + id * kPointerSize;
7978 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7979 return kJSBuiltinsCodeOffset + id * kPointerSize;
7983 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7987 // Representation for JS Wrapper objects, String, Number, Float32x4, Int32x4,
7989 class JSValue: public JSObject {
7991 // [value]: the object being wrapped.
7992 DECL_ACCESSORS(value, Object)
7995 static inline JSValue* cast(Object* obj);
7997 // Dispatched behavior.
7998 DECLARE_PRINTER(JSValue)
7999 DECLARE_VERIFIER(JSValue)
8001 // Layout description.
8002 static const int kValueOffset = JSObject::kHeaderSize;
8003 static const int kSize = kValueOffset + kPointerSize;
8006 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
8012 // Representation for JS date objects.
8013 class JSDate: public JSObject {
8015 // If one component is NaN, all of them are, indicating a NaN time value.
8016 // [value]: the time value.
8017 DECL_ACCESSORS(value, Object)
8018 // [year]: caches year. Either undefined, smi, or NaN.
8019 DECL_ACCESSORS(year, Object)
8020 // [month]: caches month. Either undefined, smi, or NaN.
8021 DECL_ACCESSORS(month, Object)
8022 // [day]: caches day. Either undefined, smi, or NaN.
8023 DECL_ACCESSORS(day, Object)
8024 // [weekday]: caches day of week. Either undefined, smi, or NaN.
8025 DECL_ACCESSORS(weekday, Object)
8026 // [hour]: caches hours. Either undefined, smi, or NaN.
8027 DECL_ACCESSORS(hour, Object)
8028 // [min]: caches minutes. Either undefined, smi, or NaN.
8029 DECL_ACCESSORS(min, Object)
8030 // [sec]: caches seconds. Either undefined, smi, or NaN.
8031 DECL_ACCESSORS(sec, Object)
8032 // [cache stamp]: sample of the date cache stamp at the
8033 // moment when local fields were cached.
8034 DECL_ACCESSORS(cache_stamp, Object)
8037 static inline JSDate* cast(Object* obj);
8039 // Returns the date field with the specified index.
8040 // See FieldIndex for the list of date fields.
8041 static Object* GetField(Object* date, Smi* index);
8043 void SetValue(Object* value, bool is_value_nan);
8046 // Dispatched behavior.
8047 DECLARE_PRINTER(JSDate)
8048 DECLARE_VERIFIER(JSDate)
8050 // The order is important. It must be kept in sync with date macros
8061 kFirstUncachedField,
8062 kMillisecond = kFirstUncachedField,
8066 kYearUTC = kFirstUTCField,
8079 // Layout description.
8080 static const int kValueOffset = JSObject::kHeaderSize;
8081 static const int kYearOffset = kValueOffset + kPointerSize;
8082 static const int kMonthOffset = kYearOffset + kPointerSize;
8083 static const int kDayOffset = kMonthOffset + kPointerSize;
8084 static const int kWeekdayOffset = kDayOffset + kPointerSize;
8085 static const int kHourOffset = kWeekdayOffset + kPointerSize;
8086 static const int kMinOffset = kHourOffset + kPointerSize;
8087 static const int kSecOffset = kMinOffset + kPointerSize;
8088 static const int kCacheStampOffset = kSecOffset + kPointerSize;
8089 static const int kSize = kCacheStampOffset + kPointerSize;
8092 inline Object* DoGetField(FieldIndex index);
8094 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
8096 // Computes and caches the cacheable fields of the date.
8097 inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
8100 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
8104 // Representation of message objects used for error reporting through
8105 // the API. The messages are formatted in JavaScript so this object is
8106 // a real JavaScript object. The information used for formatting the
8107 // error messages are not directly accessible from JavaScript to
8108 // prevent leaking information to user code called during error
8110 class JSMessageObject: public JSObject {
8112 // [type]: the type of error message.
8113 DECL_ACCESSORS(type, String)
8115 // [arguments]: the arguments for formatting the error message.
8116 DECL_ACCESSORS(arguments, JSArray)
8118 // [script]: the script from which the error message originated.
8119 DECL_ACCESSORS(script, Object)
8121 // [stack_frames]: an array of stack frames for this error object.
8122 DECL_ACCESSORS(stack_frames, Object)
8124 // [start_position]: the start position in the script for the error message.
8125 inline int start_position();
8126 inline void set_start_position(int value);
8128 // [end_position]: the end position in the script for the error message.
8129 inline int end_position();
8130 inline void set_end_position(int value);
8133 static inline JSMessageObject* cast(Object* obj);
8135 // Dispatched behavior.
8136 DECLARE_PRINTER(JSMessageObject)
8137 DECLARE_VERIFIER(JSMessageObject)
8139 // Layout description.
8140 static const int kTypeOffset = JSObject::kHeaderSize;
8141 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8142 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8143 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
8144 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8145 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8146 static const int kSize = kEndPositionOffset + kPointerSize;
8148 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8149 kStackFramesOffset + kPointerSize,
8150 kSize> BodyDescriptor;
8154 // Regular expressions
8155 // The regular expression holds a single reference to a FixedArray in
8156 // the kDataOffset field.
8157 // The FixedArray contains the following data:
8158 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8159 // - reference to the original source string
8160 // - reference to the original flag string
8161 // If it is an atom regexp
8162 // - a reference to a literal string to search for
8163 // If it is an irregexp regexp:
8164 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
8165 // used for tracking the last usage (used for code flushing).
8166 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8167 // used for tracking the last usage (used for code flushing)..
8168 // - max number of registers used by irregexp implementations.
8169 // - number of capture registers (output values) of the regexp.
8170 class JSRegExp: public JSObject {
8173 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8174 // ATOM: A simple string to match against using an indexOf operation.
8175 // IRREGEXP: Compiled with Irregexp.
8176 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8177 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8178 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
8182 explicit Flags(uint32_t value) : value_(value) { }
8183 bool is_global() { return (value_ & GLOBAL) != 0; }
8184 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8185 bool is_multiline() { return (value_ & MULTILINE) != 0; }
8186 uint32_t value() { return value_; }
8191 DECL_ACCESSORS(data, Object)
8193 inline Type TypeTag();
8194 inline int CaptureCount();
8195 inline Flags GetFlags();
8196 inline String* Pattern();
8197 inline Object* DataAt(int index);
8198 // Set implementation data after the object has been prepared.
8199 inline void SetDataAt(int index, Object* value);
8201 static int code_index(bool is_ascii) {
8203 return kIrregexpASCIICodeIndex;
8205 return kIrregexpUC16CodeIndex;
8209 static int saved_code_index(bool is_ascii) {
8211 return kIrregexpASCIICodeSavedIndex;
8213 return kIrregexpUC16CodeSavedIndex;
8217 static inline JSRegExp* cast(Object* obj);
8219 // Dispatched behavior.
8220 DECLARE_VERIFIER(JSRegExp)
8222 static const int kDataOffset = JSObject::kHeaderSize;
8223 static const int kSize = kDataOffset + kPointerSize;
8225 // Indices in the data array.
8226 static const int kTagIndex = 0;
8227 static const int kSourceIndex = kTagIndex + 1;
8228 static const int kFlagsIndex = kSourceIndex + 1;
8229 static const int kDataIndex = kFlagsIndex + 1;
8230 // The data fields are used in different ways depending on the
8231 // value of the tag.
8232 // Atom regexps (literal strings).
8233 static const int kAtomPatternIndex = kDataIndex;
8235 static const int kAtomDataSize = kAtomPatternIndex + 1;
8237 // Irregexp compiled code or bytecode for ASCII. If compilation
8238 // fails, this fields hold an exception object that should be
8239 // thrown if the regexp is used again.
8240 static const int kIrregexpASCIICodeIndex = kDataIndex;
8241 // Irregexp compiled code or bytecode for UC16. If compilation
8242 // fails, this fields hold an exception object that should be
8243 // thrown if the regexp is used again.
8244 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8246 // Saved instance of Irregexp compiled code or bytecode for ASCII that
8247 // is a potential candidate for flushing.
8248 static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
8249 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8250 // a potential candidate for flushing.
8251 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8253 // Maximal number of registers used by either ASCII or UC16.
8254 // Only used to check that there is enough stack space
8255 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8256 // Number of captures in the compiled regexp.
8257 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8259 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8261 // Offsets directly into the data fixed array.
8262 static const int kDataTagOffset =
8263 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8264 static const int kDataAsciiCodeOffset =
8265 FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
8266 static const int kDataUC16CodeOffset =
8267 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8268 static const int kIrregexpCaptureCountOffset =
8269 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8271 // In-object fields.
8272 static const int kSourceFieldIndex = 0;
8273 static const int kGlobalFieldIndex = 1;
8274 static const int kIgnoreCaseFieldIndex = 2;
8275 static const int kMultilineFieldIndex = 3;
8276 static const int kLastIndexFieldIndex = 4;
8277 static const int kInObjectFieldCount = 5;
8279 // The uninitialized value for a regexp code object.
8280 static const int kUninitializedValue = -1;
8282 // The compilation error value for the regexp code object. The real error
8283 // object is in the saved code field.
8284 static const int kCompilationErrorValue = -2;
8286 // When we store the sweep generation at which we moved the code from the
8287 // code index to the saved code index we mask it of to be in the [0:255]
8289 static const int kCodeAgeMask = 0xff;
8293 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8295 static inline bool IsMatch(HashTableKey* key, Object* value) {
8296 return key->IsMatch(value);
8299 static inline uint32_t Hash(HashTableKey* key) {
8303 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8304 return key->HashForObject(object);
8307 MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8308 HashTableKey* key) {
8309 return key->AsObject(heap);
8312 static const int kPrefixSize = 0;
8313 static const int kEntrySize = 2;
8317 class CompilationCacheTable: public HashTable<CompilationCacheShape,
8320 // Find cached value for a string key, otherwise return null.
8321 Object* Lookup(String* src, Context* context);
8322 Object* LookupEval(String* src,
8324 StrictMode strict_mode,
8325 int scope_position);
8326 Object* LookupRegExp(String* source, JSRegExp::Flags flags);
8327 MUST_USE_RESULT MaybeObject* Put(String* src,
8330 MUST_USE_RESULT MaybeObject* PutEval(String* src,
8332 SharedFunctionInfo* value,
8333 int scope_position);
8334 MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
8335 JSRegExp::Flags flags,
8338 // Remove given value from cache.
8339 void Remove(Object* value);
8341 static inline CompilationCacheTable* cast(Object* obj);
8344 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8348 class CodeCache: public Struct {
8350 DECL_ACCESSORS(default_cache, FixedArray)
8351 DECL_ACCESSORS(normal_type_cache, Object)
8353 // Add the code object to the cache.
8354 MUST_USE_RESULT MaybeObject* Update(Name* name, Code* code);
8356 // Lookup code object in the cache. Returns code object if found and undefined
8358 Object* Lookup(Name* name, Code::Flags flags);
8360 // Get the internal index of a code object in the cache. Returns -1 if the
8361 // code object is not in that cache. This index can be used to later call
8362 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8364 int GetIndex(Object* name, Code* code);
8366 // Remove an object from the cache with the provided internal index.
8367 void RemoveByIndex(Object* name, Code* code, int index);
8369 static inline CodeCache* cast(Object* obj);
8371 // Dispatched behavior.
8372 DECLARE_PRINTER(CodeCache)
8373 DECLARE_VERIFIER(CodeCache)
8375 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8376 static const int kNormalTypeCacheOffset =
8377 kDefaultCacheOffset + kPointerSize;
8378 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8381 MUST_USE_RESULT MaybeObject* UpdateDefaultCache(Name* name, Code* code);
8382 MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(Name* name, Code* code);
8383 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8384 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8386 // Code cache layout of the default cache. Elements are alternating name and
8387 // code objects for non normal load/store/call IC's.
8388 static const int kCodeCacheEntrySize = 2;
8389 static const int kCodeCacheEntryNameOffset = 0;
8390 static const int kCodeCacheEntryCodeOffset = 1;
8392 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8396 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8398 static inline bool IsMatch(HashTableKey* key, Object* value) {
8399 return key->IsMatch(value);
8402 static inline uint32_t Hash(HashTableKey* key) {
8406 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8407 return key->HashForObject(object);
8410 MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8411 HashTableKey* key) {
8412 return key->AsObject(heap);
8415 static const int kPrefixSize = 0;
8416 static const int kEntrySize = 2;
8420 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
8423 Object* Lookup(Name* name, Code::Flags flags);
8424 MUST_USE_RESULT MaybeObject* Put(Name* name, Code* code);
8426 int GetIndex(Name* name, Code::Flags flags);
8427 void RemoveByIndex(int index);
8429 static inline CodeCacheHashTable* cast(Object* obj);
8431 // Initial size of the fixed array backing the hash table.
8432 static const int kInitialSize = 64;
8435 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8439 class PolymorphicCodeCache: public Struct {
8441 DECL_ACCESSORS(cache, Object)
8443 static void Update(Handle<PolymorphicCodeCache> cache,
8444 MapHandleList* maps,
8448 MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
8452 // Returns an undefined value if the entry is not found.
8453 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8455 static inline PolymorphicCodeCache* cast(Object* obj);
8457 // Dispatched behavior.
8458 DECLARE_PRINTER(PolymorphicCodeCache)
8459 DECLARE_VERIFIER(PolymorphicCodeCache)
8461 static const int kCacheOffset = HeapObject::kHeaderSize;
8462 static const int kSize = kCacheOffset + kPointerSize;
8465 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8469 class PolymorphicCodeCacheHashTable
8470 : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
8472 Object* Lookup(MapHandleList* maps, int code_kind);
8474 MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
8478 static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
8480 static const int kInitialSize = 64;
8482 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8486 class TypeFeedbackInfo: public Struct {
8488 inline int ic_total_count();
8489 inline void set_ic_total_count(int count);
8491 inline int ic_with_type_info_count();
8492 inline void change_ic_with_type_info_count(int count);
8494 inline void initialize_storage();
8496 inline void change_own_type_change_checksum();
8497 inline int own_type_change_checksum();
8499 inline void set_inlined_type_change_checksum(int checksum);
8500 inline bool matches_inlined_type_change_checksum(int checksum);
8502 DECL_ACCESSORS(feedback_vector, FixedArray)
8504 static inline TypeFeedbackInfo* cast(Object* obj);
8506 // Dispatched behavior.
8507 DECLARE_PRINTER(TypeFeedbackInfo)
8508 DECLARE_VERIFIER(TypeFeedbackInfo)
8510 static const int kStorage1Offset = HeapObject::kHeaderSize;
8511 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8512 static const int kFeedbackVectorOffset =
8513 kStorage2Offset + kPointerSize;
8514 static const int kSize = kFeedbackVectorOffset + kPointerSize;
8516 // The object that indicates an uninitialized cache.
8517 static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
8519 // The object that indicates a megamorphic state.
8520 static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
8522 // The object that indicates a monomorphic state of Array with
8524 static inline Handle<Object> MonomorphicArraySentinel(Isolate* isolate,
8525 ElementsKind elements_kind);
8527 // A raw version of the uninitialized sentinel that's safe to read during
8528 // garbage collection (e.g., for patching the cache).
8529 static inline Object* RawUninitializedSentinel(Heap* heap);
8531 static const int kForInFastCaseMarker = 0;
8532 static const int kForInSlowCaseMarker = 1;
8535 static const int kTypeChangeChecksumBits = 7;
8537 class ICTotalCountField: public BitField<int, 0,
8538 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8539 class OwnTypeChangeChecksum: public BitField<int,
8540 kSmiValueSize - kTypeChangeChecksumBits,
8541 kTypeChangeChecksumBits> {}; // NOLINT
8542 class ICsWithTypeInfoCountField: public BitField<int, 0,
8543 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8544 class InlinedTypeChangeChecksum: public BitField<int,
8545 kSmiValueSize - kTypeChangeChecksumBits,
8546 kTypeChangeChecksumBits> {}; // NOLINT
8548 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8552 enum AllocationSiteMode {
8553 DONT_TRACK_ALLOCATION_SITE,
8554 TRACK_ALLOCATION_SITE,
8555 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8559 class AllocationSite: public Struct {
8561 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8562 static const double kPretenureRatio;
8563 static const int kPretenureMinimumCreated = 100;
8565 // Values for pretenure decision field.
8566 enum PretenureDecision {
8571 kLastPretenureDecisionValue = kZombie
8574 DECL_ACCESSORS(transition_info, Object)
8575 // nested_site threads a list of sites that represent nested literals
8576 // walked in a particular order. So [[1, 2], 1, 2] will have one
8577 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8578 DECL_ACCESSORS(nested_site, Object)
8579 DECL_ACCESSORS(pretenure_data, Smi)
8580 DECL_ACCESSORS(pretenure_create_count, Smi)
8581 DECL_ACCESSORS(dependent_code, DependentCode)
8582 DECL_ACCESSORS(weak_next, Object)
8584 inline void Initialize();
8586 // This method is expensive, it should only be called for reporting.
8587 bool IsNestedSite();
8589 // transition_info bitfields, for constructed array transition info.
8590 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8591 class UnusedBits: public BitField<int, 15, 14> {};
8592 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8594 // Bitfields for pretenure_data
8595 class MementoFoundCountBits: public BitField<int, 0, 27> {};
8596 class PretenureDecisionBits: public BitField<PretenureDecision, 27, 2> {};
8597 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8598 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8600 // Increments the mementos found counter and returns true when the first
8601 // memento was found for a given allocation site.
8602 inline bool IncrementMementoFoundCount();
8604 inline void IncrementMementoCreateCount();
8606 PretenureFlag GetPretenureMode();
8608 void ResetPretenureDecision();
8610 PretenureDecision pretenure_decision() {
8611 int value = pretenure_data()->value();
8612 return PretenureDecisionBits::decode(value);
8615 void set_pretenure_decision(PretenureDecision decision) {
8616 int value = pretenure_data()->value();
8618 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8619 SKIP_WRITE_BARRIER);
8622 bool deopt_dependent_code() {
8623 int value = pretenure_data()->value();
8624 return DeoptDependentCodeBit::decode(value);
8627 void set_deopt_dependent_code(bool deopt) {
8628 int value = pretenure_data()->value();
8630 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8631 SKIP_WRITE_BARRIER);
8634 int memento_found_count() {
8635 int value = pretenure_data()->value();
8636 return MementoFoundCountBits::decode(value);
8639 inline void set_memento_found_count(int count);
8641 int memento_create_count() {
8642 return pretenure_create_count()->value();
8645 void set_memento_create_count(int count) {
8646 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8649 // The pretenuring decision is made during gc, and the zombie state allows
8650 // us to recognize when an allocation site is just being kept alive because
8651 // a later traversal of new space may discover AllocationMementos that point
8652 // to this AllocationSite.
8654 return pretenure_decision() == kZombie;
8657 inline void MarkZombie();
8659 inline bool DigestPretenuringFeedback();
8661 ElementsKind GetElementsKind() {
8662 ASSERT(!SitePointsToLiteral());
8663 int value = Smi::cast(transition_info())->value();
8664 return ElementsKindBits::decode(value);
8667 void SetElementsKind(ElementsKind kind) {
8668 int value = Smi::cast(transition_info())->value();
8669 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8670 SKIP_WRITE_BARRIER);
8673 bool CanInlineCall() {
8674 int value = Smi::cast(transition_info())->value();
8675 return DoNotInlineBit::decode(value) == 0;
8678 void SetDoNotInlineCall() {
8679 int value = Smi::cast(transition_info())->value();
8680 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8681 SKIP_WRITE_BARRIER);
8684 bool SitePointsToLiteral() {
8685 // If transition_info is a smi, then it represents an ElementsKind
8686 // for a constructed array. Otherwise, it must be a boilerplate
8687 // for an object or array literal.
8688 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8691 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8692 ElementsKind to_kind);
8699 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8701 CompilationInfo* info);
8703 DECLARE_PRINTER(AllocationSite)
8704 DECLARE_VERIFIER(AllocationSite)
8706 static inline AllocationSite* cast(Object* obj);
8707 static inline AllocationSiteMode GetMode(
8708 ElementsKind boilerplate_elements_kind);
8709 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8710 static inline bool CanTrack(InstanceType type);
8712 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8713 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8714 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8715 static const int kPretenureCreateCountOffset =
8716 kPretenureDataOffset + kPointerSize;
8717 static const int kDependentCodeOffset =
8718 kPretenureCreateCountOffset + kPointerSize;
8719 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8720 static const int kSize = kWeakNextOffset + kPointerSize;
8722 // During mark compact we need to take special care for the dependent code
8724 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8725 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8727 // For other visitors, use the fixed body descriptor below.
8728 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8729 kDependentCodeOffset + kPointerSize,
8730 kSize> BodyDescriptor;
8733 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8734 bool PretenuringDecisionMade() {
8735 return pretenure_decision() != kUndecided;
8738 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8742 class AllocationMemento: public Struct {
8744 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8745 static const int kSize = kAllocationSiteOffset + kPointerSize;
8747 DECL_ACCESSORS(allocation_site, Object)
8750 return allocation_site()->IsAllocationSite() &&
8751 !AllocationSite::cast(allocation_site())->IsZombie();
8753 AllocationSite* GetAllocationSite() {
8755 return AllocationSite::cast(allocation_site());
8758 DECLARE_PRINTER(AllocationMemento)
8759 DECLARE_VERIFIER(AllocationMemento)
8761 static inline AllocationMemento* cast(Object* obj);
8764 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8768 // Representation of a slow alias as part of a sloppy arguments objects.
8769 // For fast aliases (if HasSloppyArgumentsElements()):
8770 // - the parameter map contains an index into the context
8771 // - all attributes of the element have default values
8772 // For slow aliases (if HasDictionaryArgumentsElements()):
8773 // - the parameter map contains no fast alias mapping (i.e. the hole)
8774 // - this struct (in the slow backing store) contains an index into the context
8775 // - all attributes are available as part if the property details
8776 class AliasedArgumentsEntry: public Struct {
8778 inline int aliased_context_slot();
8779 inline void set_aliased_context_slot(int count);
8781 static inline AliasedArgumentsEntry* cast(Object* obj);
8783 // Dispatched behavior.
8784 DECLARE_PRINTER(AliasedArgumentsEntry)
8785 DECLARE_VERIFIER(AliasedArgumentsEntry)
8787 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8788 static const int kSize = kAliasedContextSlot + kPointerSize;
8791 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8795 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8796 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8799 class StringHasher {
8801 explicit inline StringHasher(int length, uint32_t seed);
8803 template <typename schar>
8804 static inline uint32_t HashSequentialString(const schar* chars,
8808 // Reads all the data, even for long strings and computes the utf16 length.
8809 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8811 int* utf16_length_out);
8813 // Calculated hash value for a string consisting of 1 to
8814 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8815 // value is represented decimal value.
8816 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8818 // No string is allowed to have a hash of zero. That value is reserved
8819 // for internal properties. If the hash calculation yields zero then we
8821 static const int kZeroHash = 27;
8823 // Reusable parts of the hashing algorithm.
8824 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8825 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8828 // Returns the value to store in the hash field of a string with
8829 // the given length and contents.
8830 uint32_t GetHashField();
8831 // Returns true if the hash of this string can be computed without
8832 // looking at the contents.
8833 inline bool has_trivial_hash();
8834 // Adds a block of characters to the hash.
8835 template<typename Char>
8836 inline void AddCharacters(const Char* chars, int len);
8839 // Add a character to the hash.
8840 inline void AddCharacter(uint16_t c);
8841 // Update index. Returns true if string is still an index.
8842 inline bool UpdateIndex(uint16_t c);
8845 uint32_t raw_running_hash_;
8846 uint32_t array_index_;
8847 bool is_array_index_;
8848 bool is_first_char_;
8849 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8853 // The characteristics of a string are stored in its map. Retrieving these
8854 // few bits of information is moderately expensive, involving two memory
8855 // loads where the second is dependent on the first. To improve efficiency
8856 // the shape of the string is given its own class so that it can be retrieved
8857 // once and used for several string operations. A StringShape is small enough
8858 // to be passed by value and is immutable, but be aware that flattening a
8859 // string can potentially alter its shape. Also be aware that a GC caused by
8860 // something else can alter the shape of a string due to ConsString
8861 // shortcutting. Keeping these restrictions in mind has proven to be error-
8862 // prone and so we no longer put StringShapes in variables unless there is a
8863 // concrete performance benefit at that particular point in the code.
8864 class StringShape BASE_EMBEDDED {
8866 inline explicit StringShape(String* s);
8867 inline explicit StringShape(Map* s);
8868 inline explicit StringShape(InstanceType t);
8869 inline bool IsSequential();
8870 inline bool IsExternal();
8871 inline bool IsCons();
8872 inline bool IsSliced();
8873 inline bool IsIndirect();
8874 inline bool IsExternalAscii();
8875 inline bool IsExternalTwoByte();
8876 inline bool IsSequentialAscii();
8877 inline bool IsSequentialTwoByte();
8878 inline bool IsInternalized();
8879 inline StringRepresentationTag representation_tag();
8880 inline uint32_t encoding_tag();
8881 inline uint32_t full_representation_tag();
8882 inline uint32_t size_tag();
8884 inline uint32_t type() { return type_; }
8885 inline void invalidate() { valid_ = false; }
8886 inline bool valid() { return valid_; }
8888 inline void invalidate() { }
8894 inline void set_valid() { valid_ = true; }
8897 inline void set_valid() { }
8902 // The Name abstract class captures anything that can be used as a property
8903 // name, i.e., strings and symbols. All names store a hash value.
8904 class Name: public HeapObject {
8906 // Get and set the hash field of the name.
8907 inline uint32_t hash_field();
8908 inline void set_hash_field(uint32_t value);
8910 // Tells whether the hash code has been computed.
8911 inline bool HasHashCode();
8913 // Returns a hash value used for the property table
8914 inline uint32_t Hash();
8916 // Equality operations.
8917 inline bool Equals(Name* other);
8920 inline bool AsArrayIndex(uint32_t* index);
8923 static inline Name* cast(Object* obj);
8925 bool IsCacheable(Isolate* isolate);
8927 DECLARE_PRINTER(Name)
8929 // Layout description.
8930 static const int kHashFieldOffset = HeapObject::kHeaderSize;
8931 static const int kSize = kHashFieldOffset + kPointerSize;
8933 // Mask constant for checking if a name has a computed hash code
8934 // and if it is a string that is an array index. The least significant bit
8935 // indicates whether a hash code has been computed. If the hash code has
8936 // been computed the 2nd bit tells whether the string can be used as an
8938 static const int kHashNotComputedMask = 1;
8939 static const int kIsNotArrayIndexMask = 1 << 1;
8940 static const int kNofHashBitFields = 2;
8942 // Shift constant retrieving hash code from hash field.
8943 static const int kHashShift = kNofHashBitFields;
8945 // Only these bits are relevant in the hash, since the top two are shifted
8947 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8949 // Array index strings this short can keep their index in the hash field.
8950 static const int kMaxCachedArrayIndexLength = 7;
8952 // For strings which are array indexes the hash value has the string length
8953 // mixed into the hash, mainly to avoid a hash value of zero which would be
8954 // the case for the string '0'. 24 bits are used for the array index value.
8955 static const int kArrayIndexValueBits = 24;
8956 static const int kArrayIndexLengthBits =
8957 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8959 STATIC_CHECK((kArrayIndexLengthBits > 0));
8961 static const int kArrayIndexHashLengthShift =
8962 kArrayIndexValueBits + kNofHashBitFields;
8964 static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
8966 static const int kArrayIndexValueMask =
8967 ((1 << kArrayIndexValueBits) - 1) << kHashShift;
8969 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8970 // could use a mask to test if the length of string is less than or equal to
8971 // kMaxCachedArrayIndexLength.
8972 STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8974 static const unsigned int kContainsCachedArrayIndexMask =
8975 (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
8976 kIsNotArrayIndexMask;
8978 // Value of empty hash field indicating that the hash is not computed.
8979 static const int kEmptyHashField =
8980 kIsNotArrayIndexMask | kHashNotComputedMask;
8983 static inline bool IsHashFieldComputed(uint32_t field);
8986 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8991 class Symbol: public Name {
8993 // [name]: the print name of a symbol, or undefined if none.
8994 DECL_ACCESSORS(name, Object)
8996 DECL_ACCESSORS(flags, Smi)
8998 // [is_private]: whether this is a private symbol.
8999 DECL_BOOLEAN_ACCESSORS(is_private)
9002 static inline Symbol* cast(Object* obj);
9004 // Dispatched behavior.
9005 DECLARE_PRINTER(Symbol)
9006 DECLARE_VERIFIER(Symbol)
9008 // Layout description.
9009 static const int kNameOffset = Name::kSize;
9010 static const int kFlagsOffset = kNameOffset + kPointerSize;
9011 static const int kSize = kFlagsOffset + kPointerSize;
9013 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
9016 static const int kPrivateBit = 0;
9018 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
9024 // The String abstract class captures JavaScript string values:
9027 // 4.3.16 String Value
9028 // A string value is a member of the type String and is a finite
9029 // ordered sequence of zero or more 16-bit unsigned integer values.
9031 // All string values have a length field.
9032 class String: public Name {
9034 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
9036 // Representation of the flat content of a String.
9037 // A non-flat string doesn't have flat content.
9038 // A flat string has content that's encoded as a sequence of either
9039 // ASCII chars or two-byte UC16.
9040 // Returned by String::GetFlatContent().
9043 // Returns true if the string is flat and this structure contains content.
9044 bool IsFlat() { return state_ != NON_FLAT; }
9045 // Returns true if the structure contains ASCII content.
9046 bool IsAscii() { return state_ == ASCII; }
9047 // Returns true if the structure contains two-byte content.
9048 bool IsTwoByte() { return state_ == TWO_BYTE; }
9050 // Return the one byte content of the string. Only use if IsAscii() returns
9052 Vector<const uint8_t> ToOneByteVector() {
9053 ASSERT_EQ(ASCII, state_);
9056 // Return the two-byte content of the string. Only use if IsTwoByte()
9058 Vector<const uc16> ToUC16Vector() {
9059 ASSERT_EQ(TWO_BYTE, state_);
9060 return Vector<const uc16>::cast(buffer_);
9064 enum State { NON_FLAT, ASCII, TWO_BYTE };
9066 // Constructors only used by String::GetFlatContent().
9067 explicit FlatContent(Vector<const uint8_t> chars)
9070 explicit FlatContent(Vector<const uc16> chars)
9071 : buffer_(Vector<const byte>::cast(chars)),
9072 state_(TWO_BYTE) { }
9073 FlatContent() : buffer_(), state_(NON_FLAT) { }
9075 Vector<const uint8_t> buffer_;
9078 friend class String;
9081 // Get and set the length of the string.
9082 inline int length();
9083 inline void set_length(int value);
9085 // Returns whether this string has only ASCII chars, i.e. all of them can
9086 // be ASCII encoded. This might be the case even if the string is
9087 // two-byte. Such strings may appear when the embedder prefers
9088 // two-byte external representations even for ASCII data.
9089 inline bool IsOneByteRepresentation();
9090 inline bool IsTwoByteRepresentation();
9092 // Cons and slices have an encoding flag that may not represent the actual
9093 // encoding of the underlying string. This is taken into account here.
9094 // Requires: this->IsFlat()
9095 inline bool IsOneByteRepresentationUnderneath();
9096 inline bool IsTwoByteRepresentationUnderneath();
9098 // NOTE: this should be considered only a hint. False negatives are
9100 inline bool HasOnlyOneByteChars();
9102 // Get and set individual two byte chars in the string.
9103 inline void Set(int index, uint16_t value);
9104 // Get individual two byte char in the string. Repeated calls
9105 // to this method are not efficient unless the string is flat.
9106 INLINE(uint16_t Get(int index));
9108 // Try to flatten the string. Checks first inline to see if it is
9109 // necessary. Does nothing if the string is not a cons string.
9110 // Flattening allocates a sequential string with the same data as
9111 // the given string and mutates the cons string to a degenerate
9112 // form, where the first component is the new sequential string and
9113 // the second component is the empty string. If allocation fails,
9114 // this function returns a failure. If flattening succeeds, this
9115 // function returns the sequential string that is now the first
9116 // component of the cons string.
9118 // Degenerate cons strings are handled specially by the garbage
9119 // collector (see IsShortcutCandidate).
9121 // Use FlattenString from Handles.cc to flatten even in case an
9122 // allocation failure happens.
9123 inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
9125 // Convenience function. Has exactly the same behavior as
9126 // TryFlatten(), except in the case of failure returns the original
9128 inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
9130 // Tries to return the content of a flat string as a structure holding either
9131 // a flat vector of char or of uc16.
9132 // If the string isn't flat, and therefore doesn't have flat content, the
9133 // returned structure will report so, and can't provide a vector of either
9135 FlatContent GetFlatContent();
9137 // Returns the parent of a sliced string or first part of a flat cons string.
9138 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9139 inline String* GetUnderlying();
9141 // Mark the string as an undetectable object. It only applies to
9142 // ASCII and two byte string types.
9143 bool MarkAsUndetectable();
9145 // String equality operations.
9146 inline bool Equals(String* other);
9147 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9148 bool IsOneByteEqualTo(Vector<const uint8_t> str);
9149 bool IsTwoByteEqualTo(Vector<const uc16> str);
9151 // Return a UTF8 representation of the string. The string is null
9152 // terminated but may optionally contain nulls. Length is returned
9153 // in length_output if length_output is not a null pointer The string
9154 // should be nearly flat, otherwise the performance of this method may
9155 // be very slow (quadratic in the length). Setting robustness_flag to
9156 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9157 // handles unexpected data without causing assert failures and it does not
9158 // do any heap allocations. This is useful when printing stack traces.
9159 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9160 RobustnessFlag robustness_flag,
9163 int* length_output = 0);
9164 SmartArrayPointer<char> ToCString(
9165 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9166 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9167 int* length_output = 0);
9169 // Return a 16 bit Unicode representation of the string.
9170 // The string should be nearly flat, otherwise the performance of
9171 // of this method may be very bad. Setting robustness_flag to
9172 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9173 // handles unexpected data without causing assert failures and it does not
9174 // do any heap allocations. This is useful when printing stack traces.
9175 SmartArrayPointer<uc16> ToWideCString(
9176 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9178 bool ComputeArrayIndex(uint32_t* index);
9181 bool MakeExternal(v8::String::ExternalStringResource* resource);
9182 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
9185 inline bool AsArrayIndex(uint32_t* index);
9188 static inline String* cast(Object* obj);
9190 void PrintOn(FILE* out);
9192 // For use during stack traces. Performs rudimentary sanity check.
9195 // Dispatched behavior.
9196 void StringShortPrint(StringStream* accumulator);
9198 char* ToAsciiArray();
9200 DECLARE_PRINTER(String)
9201 DECLARE_VERIFIER(String)
9203 inline bool IsFlat();
9205 // Layout description.
9206 static const int kLengthOffset = Name::kSize;
9207 static const int kSize = kLengthOffset + kPointerSize;
9209 // Maximum number of characters to consider when trying to convert a string
9210 // value into an array index.
9211 static const int kMaxArrayIndexSize = 10;
9212 STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9215 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9216 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9217 static const int kMaxUtf16CodeUnit = 0xffff;
9219 // Value of hash field containing computed hash equal to zero.
9220 static const int kEmptyStringHash = kIsNotArrayIndexMask;
9222 // Maximal string length.
9223 static const int kMaxLength = (1 << 28) - 16;
9225 // Max length for computing hash. For strings longer than this limit the
9226 // string length is used as the hash value.
9227 static const int kMaxHashCalcLength = 16383;
9229 // Limit for truncation in short printing.
9230 static const int kMaxShortPrintLength = 1024;
9232 // Support for regular expressions.
9233 const uc16* GetTwoByteData(unsigned start);
9235 // Helper function for flattening strings.
9236 template <typename sinkchar>
9237 static void WriteToFlat(String* source,
9242 // The return value may point to the first aligned word containing the
9243 // first non-ascii character, rather than directly to the non-ascii character.
9244 // If the return value is >= the passed length, the entire string was ASCII.
9245 static inline int NonAsciiStart(const char* chars, int length) {
9246 const char* start = chars;
9247 const char* limit = chars + length;
9248 #ifdef V8_HOST_CAN_READ_UNALIGNED
9249 ASSERT(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9250 const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9251 while (chars + sizeof(uintptr_t) <= limit) {
9252 if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
9253 return static_cast<int>(chars - start);
9255 chars += sizeof(uintptr_t);
9258 while (chars < limit) {
9259 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9260 return static_cast<int>(chars - start);
9264 return static_cast<int>(chars - start);
9267 static inline bool IsAscii(const char* chars, int length) {
9268 return NonAsciiStart(chars, length) >= length;
9271 static inline bool IsAscii(const uint8_t* chars, int length) {
9273 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9276 static inline int NonOneByteStart(const uc16* chars, int length) {
9277 const uc16* limit = chars + length;
9278 const uc16* start = chars;
9279 while (chars < limit) {
9280 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9283 return static_cast<int>(chars - start);
9286 static inline bool IsOneByte(const uc16* chars, int length) {
9287 return NonOneByteStart(chars, length) >= length;
9290 // TODO(dcarney): Replace all instances of this with VisitFlat.
9291 template<class Visitor, class ConsOp>
9292 static inline void Visit(String* string,
9299 template<class Visitor>
9300 static inline ConsString* VisitFlat(Visitor* visitor,
9306 template<class Visitor>
9307 static inline ConsString* VisitFlat(Visitor* visitor,
9310 int32_t type = string->map()->instance_type();
9311 return VisitFlat(visitor, string, offset, string->length(), type);
9317 // Try to flatten the top level ConsString that is hiding behind this
9318 // string. This is a no-op unless the string is a ConsString. Flatten
9319 // mutates the ConsString and might return a failure.
9320 MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
9322 // Slow case of String::Equals. This implementation works on any strings
9323 // but it is most efficient on strings that are almost flat.
9324 bool SlowEquals(String* other);
9326 // Slow case of AsArrayIndex.
9327 bool SlowAsArrayIndex(uint32_t* index);
9329 // Compute and set the hash code.
9330 uint32_t ComputeAndSetHash();
9332 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9336 // The SeqString abstract class captures sequential string values.
9337 class SeqString: public String {
9340 static inline SeqString* cast(Object* obj);
9342 // Layout description.
9343 static const int kHeaderSize = String::kSize;
9345 // Truncate the string in-place if possible and return the result.
9346 // In case of new_length == 0, the empty string is returned without
9347 // truncating the original string.
9348 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9351 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9355 // The AsciiString class captures sequential ASCII string objects.
9356 // Each character in the AsciiString is an ASCII character.
9357 class SeqOneByteString: public SeqString {
9359 static const bool kHasAsciiEncoding = true;
9361 // Dispatched behavior.
9362 inline uint16_t SeqOneByteStringGet(int index);
9363 inline void SeqOneByteStringSet(int index, uint16_t value);
9365 // Get the address of the characters in this string.
9366 inline Address GetCharsAddress();
9368 inline uint8_t* GetChars();
9371 static inline SeqOneByteString* cast(Object* obj);
9373 // Garbage collection support. This method is called by the
9374 // garbage collector to compute the actual size of an AsciiString
9376 inline int SeqOneByteStringSize(InstanceType instance_type);
9378 // Computes the size for an AsciiString instance of a given length.
9379 static int SizeFor(int length) {
9380 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9383 // Maximal memory usage for a single sequential ASCII string.
9384 static const int kMaxSize = 512 * MB - 1;
9385 STATIC_CHECK((kMaxSize - kHeaderSize) >= String::kMaxLength);
9388 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9392 // The TwoByteString class captures sequential unicode string objects.
9393 // Each character in the TwoByteString is a two-byte uint16_t.
9394 class SeqTwoByteString: public SeqString {
9396 static const bool kHasAsciiEncoding = false;
9398 // Dispatched behavior.
9399 inline uint16_t SeqTwoByteStringGet(int index);
9400 inline void SeqTwoByteStringSet(int index, uint16_t value);
9402 // Get the address of the characters in this string.
9403 inline Address GetCharsAddress();
9405 inline uc16* GetChars();
9408 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9411 static inline SeqTwoByteString* cast(Object* obj);
9413 // Garbage collection support. This method is called by the
9414 // garbage collector to compute the actual size of a TwoByteString
9416 inline int SeqTwoByteStringSize(InstanceType instance_type);
9418 // Computes the size for a TwoByteString instance of a given length.
9419 static int SizeFor(int length) {
9420 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9423 // Maximal memory usage for a single sequential two-byte string.
9424 static const int kMaxSize = 512 * MB - 1;
9425 STATIC_CHECK(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9426 String::kMaxLength);
9429 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9433 // The ConsString class describes string values built by using the
9434 // addition operator on strings. A ConsString is a pair where the
9435 // first and second components are pointers to other string values.
9436 // One or both components of a ConsString can be pointers to other
9437 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9438 // are non-ConsString string values. The string value represented by
9439 // a ConsString can be obtained by concatenating the leaf string
9440 // values in a left-to-right depth-first traversal of the tree.
9441 class ConsString: public String {
9443 // First string of the cons cell.
9444 inline String* first();
9445 // Doesn't check that the result is a string, even in debug mode. This is
9446 // useful during GC where the mark bits confuse the checks.
9447 inline Object* unchecked_first();
9448 inline void set_first(String* first,
9449 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9451 // Second string of the cons cell.
9452 inline String* second();
9453 // Doesn't check that the result is a string, even in debug mode. This is
9454 // useful during GC where the mark bits confuse the checks.
9455 inline Object* unchecked_second();
9456 inline void set_second(String* second,
9457 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9459 // Dispatched behavior.
9460 uint16_t ConsStringGet(int index);
9463 static inline ConsString* cast(Object* obj);
9465 // Layout description.
9466 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9467 static const int kSecondOffset = kFirstOffset + kPointerSize;
9468 static const int kSize = kSecondOffset + kPointerSize;
9470 // Minimum length for a cons string.
9471 static const int kMinLength = 13;
9473 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9476 DECLARE_VERIFIER(ConsString)
9479 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9483 // The Sliced String class describes strings that are substrings of another
9484 // sequential string. The motivation is to save time and memory when creating
9485 // a substring. A Sliced String is described as a pointer to the parent,
9486 // the offset from the start of the parent string and the length. Using
9487 // a Sliced String therefore requires unpacking of the parent string and
9488 // adding the offset to the start address. A substring of a Sliced String
9489 // are not nested since the double indirection is simplified when creating
9490 // such a substring.
9491 // Currently missing features are:
9492 // - handling externalized parent strings
9493 // - external strings as parent
9494 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9495 class SlicedString: public String {
9497 inline String* parent();
9498 inline void set_parent(String* parent,
9499 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9500 inline int offset();
9501 inline void set_offset(int offset);
9503 // Dispatched behavior.
9504 uint16_t SlicedStringGet(int index);
9507 static inline SlicedString* cast(Object* obj);
9509 // Layout description.
9510 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9511 static const int kOffsetOffset = kParentOffset + kPointerSize;
9512 static const int kSize = kOffsetOffset + kPointerSize;
9514 // Minimum length for a sliced string.
9515 static const int kMinLength = 13;
9517 typedef FixedBodyDescriptor<kParentOffset,
9518 kOffsetOffset + kPointerSize, kSize>
9521 DECLARE_VERIFIER(SlicedString)
9524 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9528 // The ExternalString class describes string values that are backed by
9529 // a string resource that lies outside the V8 heap. ExternalStrings
9530 // consist of the length field common to all strings, a pointer to the
9531 // external resource. It is important to ensure (externally) that the
9532 // resource is not deallocated while the ExternalString is live in the
9535 // The API expects that all ExternalStrings are created through the
9536 // API. Therefore, ExternalStrings should not be used internally.
9537 class ExternalString: public String {
9540 static inline ExternalString* cast(Object* obj);
9542 // Layout description.
9543 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9544 static const int kShortSize = kResourceOffset + kPointerSize;
9545 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9546 static const int kSize = kResourceDataOffset + kPointerSize;
9548 static const int kMaxShortLength =
9549 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9551 // Return whether external string is short (data pointer is not cached).
9552 inline bool is_short();
9554 STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
9557 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9561 // The ExternalAsciiString class is an external string backed by an
9563 class ExternalAsciiString: public ExternalString {
9565 static const bool kHasAsciiEncoding = true;
9567 typedef v8::String::ExternalAsciiStringResource Resource;
9569 // The underlying resource.
9570 inline const Resource* resource();
9571 inline void set_resource(const Resource* buffer);
9573 // Update the pointer cache to the external character array.
9574 // The cached pointer is always valid, as the external character array does =
9575 // not move during lifetime. Deserialization is the only exception, after
9576 // which the pointer cache has to be refreshed.
9577 inline void update_data_cache();
9579 inline const uint8_t* GetChars();
9581 // Dispatched behavior.
9582 inline uint16_t ExternalAsciiStringGet(int index);
9585 static inline ExternalAsciiString* cast(Object* obj);
9587 // Garbage collection support.
9588 inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
9590 template<typename StaticVisitor>
9591 inline void ExternalAsciiStringIterateBody();
9594 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
9598 // The ExternalTwoByteString class is an external string backed by a UTF-16
9600 class ExternalTwoByteString: public ExternalString {
9602 static const bool kHasAsciiEncoding = false;
9604 typedef v8::String::ExternalStringResource Resource;
9606 // The underlying string resource.
9607 inline const Resource* resource();
9608 inline void set_resource(const Resource* buffer);
9610 // Update the pointer cache to the external character array.
9611 // The cached pointer is always valid, as the external character array does =
9612 // not move during lifetime. Deserialization is the only exception, after
9613 // which the pointer cache has to be refreshed.
9614 inline void update_data_cache();
9616 inline const uint16_t* GetChars();
9618 // Dispatched behavior.
9619 inline uint16_t ExternalTwoByteStringGet(int index);
9622 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9625 static inline ExternalTwoByteString* cast(Object* obj);
9627 // Garbage collection support.
9628 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9630 template<typename StaticVisitor>
9631 inline void ExternalTwoByteStringIterateBody();
9634 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9638 // Utility superclass for stack-allocated objects that must be updated
9639 // on gc. It provides two ways for the gc to update instances, either
9640 // iterating or updating after gc.
9641 class Relocatable BASE_EMBEDDED {
9643 explicit inline Relocatable(Isolate* isolate);
9644 inline virtual ~Relocatable();
9645 virtual void IterateInstance(ObjectVisitor* v) { }
9646 virtual void PostGarbageCollection() { }
9648 static void PostGarbageCollectionProcessing(Isolate* isolate);
9649 static int ArchiveSpacePerThread();
9650 static char* ArchiveState(Isolate* isolate, char* to);
9651 static char* RestoreState(Isolate* isolate, char* from);
9652 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9653 static void Iterate(ObjectVisitor* v, Relocatable* top);
9654 static char* Iterate(ObjectVisitor* v, char* t);
9662 // A flat string reader provides random access to the contents of a
9663 // string independent of the character width of the string. The handle
9664 // must be valid as long as the reader is being used.
9665 class FlatStringReader : public Relocatable {
9667 FlatStringReader(Isolate* isolate, Handle<String> str);
9668 FlatStringReader(Isolate* isolate, Vector<const char> input);
9669 void PostGarbageCollection();
9670 inline uc32 Get(int index);
9671 int length() { return length_; }
9680 // A ConsStringOp that returns null.
9681 // Useful when the operation to apply on a ConsString
9682 // requires an expensive data structure.
9683 class ConsStringNullOp {
9685 inline ConsStringNullOp() {}
9686 static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9688 DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9692 // This maintains an off-stack representation of the stack frames required
9693 // to traverse a ConsString, allowing an entirely iterative and restartable
9694 // traversal of the entire string
9695 // Note: this class is not GC-safe.
9696 class ConsStringIteratorOp {
9698 inline ConsStringIteratorOp() {}
9699 String* Operate(String* string,
9700 unsigned* offset_out,
9702 unsigned* length_out);
9703 inline String* ContinueOperation(int32_t* type_out, unsigned* length_out);
9704 inline void Reset();
9705 inline bool HasMore();
9708 // TODO(dcarney): Templatize this out for different stack sizes.
9709 static const unsigned kStackSize = 32;
9710 // Use a mask instead of doing modulo operations for stack wrapping.
9711 static const unsigned kDepthMask = kStackSize-1;
9712 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9713 static inline unsigned OffsetForDepth(unsigned depth);
9715 inline void PushLeft(ConsString* string);
9716 inline void PushRight(ConsString* string);
9717 inline void AdjustMaximumDepth();
9719 String* NextLeaf(bool* blew_stack, int32_t* type_out, unsigned* length_out);
9720 String* Search(unsigned* offset_out,
9722 unsigned* length_out);
9725 unsigned maximum_depth_;
9726 // Stack must always contain only frames for which right traversal
9727 // has not yet been performed.
9728 ConsString* frames_[kStackSize];
9731 DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9735 // Note: this class is not GC-safe.
9736 class StringCharacterStream {
9738 inline StringCharacterStream(String* string,
9739 ConsStringIteratorOp* op,
9740 unsigned offset = 0);
9741 inline uint16_t GetNext();
9742 inline bool HasMore();
9743 inline void Reset(String* string, unsigned offset = 0);
9744 inline void VisitOneByteString(const uint8_t* chars, unsigned length);
9745 inline void VisitTwoByteString(const uint16_t* chars, unsigned length);
9750 const uint8_t* buffer8_;
9751 const uint16_t* buffer16_;
9753 const uint8_t* end_;
9754 ConsStringIteratorOp* op_;
9755 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9759 template <typename T>
9760 class VectorIterator {
9762 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9763 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9764 T GetNext() { return data_[index_++]; }
9765 bool has_more() { return index_ < data_.length(); }
9767 Vector<const T> data_;
9772 // The Oddball describes objects null, undefined, true, and false.
9773 class Oddball: public HeapObject {
9775 // [to_string]: Cached to_string computed at startup.
9776 DECL_ACCESSORS(to_string, String)
9778 // [to_number]: Cached to_number computed at startup.
9779 DECL_ACCESSORS(to_number, Object)
9782 inline void set_kind(byte kind);
9785 static inline Oddball* cast(Object* obj);
9787 // Dispatched behavior.
9788 DECLARE_VERIFIER(Oddball)
9790 // Initialize the fields.
9791 MUST_USE_RESULT MaybeObject* Initialize(Heap* heap,
9792 const char* to_string,
9796 // Layout description.
9797 static const int kToStringOffset = HeapObject::kHeaderSize;
9798 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9799 static const int kKindOffset = kToNumberOffset + kPointerSize;
9800 static const int kSize = kKindOffset + kPointerSize;
9802 static const byte kFalse = 0;
9803 static const byte kTrue = 1;
9804 static const byte kNotBooleanMask = ~1;
9805 static const byte kTheHole = 2;
9806 static const byte kNull = 3;
9807 static const byte kArgumentMarker = 4;
9808 static const byte kUndefined = 5;
9809 static const byte kUninitialized = 6;
9810 static const byte kOther = 7;
9812 typedef FixedBodyDescriptor<kToStringOffset,
9813 kToNumberOffset + kPointerSize,
9814 kSize> BodyDescriptor;
9816 STATIC_CHECK(kKindOffset == Internals::kOddballKindOffset);
9817 STATIC_CHECK(kNull == Internals::kNullOddballKind);
9818 STATIC_CHECK(kUndefined == Internals::kUndefinedOddballKind);
9821 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9825 class Cell: public HeapObject {
9827 // [value]: value of the global property.
9828 DECL_ACCESSORS(value, Object)
9831 static inline Cell* cast(Object* obj);
9833 static inline Cell* FromValueAddress(Address value) {
9834 Object* result = FromAddress(value - kValueOffset);
9835 ASSERT(result->IsCell() || result->IsPropertyCell());
9836 return static_cast<Cell*>(result);
9839 inline Address ValueAddress() {
9840 return address() + kValueOffset;
9843 // Dispatched behavior.
9844 DECLARE_PRINTER(Cell)
9845 DECLARE_VERIFIER(Cell)
9847 // Layout description.
9848 static const int kValueOffset = HeapObject::kHeaderSize;
9849 static const int kSize = kValueOffset + kPointerSize;
9851 typedef FixedBodyDescriptor<kValueOffset,
9852 kValueOffset + kPointerSize,
9853 kSize> BodyDescriptor;
9856 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9860 class PropertyCell: public Cell {
9862 // [type]: type of the global property.
9864 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9866 // [dependent_code]: dependent code that depends on the type of the global
9868 DECL_ACCESSORS(dependent_code, DependentCode)
9870 // Sets the value of the cell and updates the type field to be the union
9871 // of the cell's current type and the value's type. If the change causes
9872 // a change of the type of the cell's contents, code dependent on the cell
9873 // will be deoptimized.
9874 static void SetValueInferType(Handle<PropertyCell> cell,
9875 Handle<Object> value);
9877 // Computes the new type of the cell's contents for the given value, but
9878 // without actually modifying the 'type' field.
9879 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9880 Handle<Object> value);
9882 void AddDependentCompilationInfo(CompilationInfo* info);
9884 void AddDependentCode(Handle<Code> code);
9887 static inline PropertyCell* cast(Object* obj);
9889 inline Address TypeAddress() {
9890 return address() + kTypeOffset;
9893 // Dispatched behavior.
9894 DECLARE_PRINTER(PropertyCell)
9895 DECLARE_VERIFIER(PropertyCell)
9897 // Layout description.
9898 static const int kTypeOffset = kValueOffset + kPointerSize;
9899 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9900 static const int kSize = kDependentCodeOffset + kPointerSize;
9902 static const int kPointerFieldsBeginOffset = kValueOffset;
9903 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9905 typedef FixedBodyDescriptor<kValueOffset,
9907 kSize> BodyDescriptor;
9910 DECL_ACCESSORS(type_raw, Object)
9911 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9915 // The JSProxy describes EcmaScript Harmony proxies
9916 class JSProxy: public JSReceiver {
9918 // [handler]: The handler property.
9919 DECL_ACCESSORS(handler, Object)
9921 // [hash]: The hash code property (undefined if not initialized yet).
9922 DECL_ACCESSORS(hash, Object)
9925 static inline JSProxy* cast(Object* obj);
9927 MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
9930 MUST_USE_RESULT MaybeObject* GetElementWithHandler(
9934 // If the handler defines an accessor property with a setter, invoke it.
9935 // If it defines an accessor property without a setter, or a data property
9936 // that is read-only, throw. In all these cases set '*done' to true,
9937 // otherwise set it to false.
9938 static Handle<Object> SetPropertyViaPrototypesWithHandler(
9939 Handle<JSProxy> proxy,
9940 Handle<JSReceiver> receiver,
9942 Handle<Object> value,
9943 PropertyAttributes attributes,
9944 StrictMode strict_mode,
9947 static PropertyAttributes GetPropertyAttributeWithHandler(
9948 Handle<JSProxy> proxy,
9949 Handle<JSReceiver> receiver,
9951 static PropertyAttributes GetElementAttributeWithHandler(
9952 Handle<JSProxy> proxy,
9953 Handle<JSReceiver> receiver,
9956 // Turn the proxy into an (empty) JSObject.
9957 static void Fix(Handle<JSProxy> proxy);
9959 // Initializes the body after the handler slot.
9960 inline void InitializeBody(int object_size, Object* value);
9962 // Invoke a trap by name. If the trap does not exist on this's handler,
9963 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9964 Handle<Object> CallTrap(const char* name,
9965 Handle<Object> derived_trap,
9967 Handle<Object> args[]);
9969 // Dispatched behavior.
9970 DECLARE_PRINTER(JSProxy)
9971 DECLARE_VERIFIER(JSProxy)
9973 // Layout description. We add padding so that a proxy has the same
9974 // size as a virgin JSObject. This is essential for becoming a JSObject
9976 static const int kHandlerOffset = HeapObject::kHeaderSize;
9977 static const int kHashOffset = kHandlerOffset + kPointerSize;
9978 static const int kPaddingOffset = kHashOffset + kPointerSize;
9979 static const int kSize = JSObject::kHeaderSize;
9980 static const int kHeaderSize = kPaddingOffset;
9981 static const int kPaddingSize = kSize - kPaddingOffset;
9983 STATIC_CHECK(kPaddingSize >= 0);
9985 typedef FixedBodyDescriptor<kHandlerOffset,
9987 kSize> BodyDescriptor;
9990 friend class JSReceiver;
9992 static Handle<Object> SetPropertyWithHandler(Handle<JSProxy> proxy,
9993 Handle<JSReceiver> receiver,
9995 Handle<Object> value,
9996 PropertyAttributes attributes,
9997 StrictMode strict_mode);
9998 static Handle<Object> SetElementWithHandler(Handle<JSProxy> proxy,
9999 Handle<JSReceiver> receiver,
10001 Handle<Object> value,
10002 StrictMode strict_mode);
10004 static bool HasPropertyWithHandler(Handle<JSProxy> proxy, Handle<Name> name);
10005 static bool HasElementWithHandler(Handle<JSProxy> proxy, uint32_t index);
10007 static Handle<Object> DeletePropertyWithHandler(Handle<JSProxy> proxy,
10010 static Handle<Object> DeleteElementWithHandler(Handle<JSProxy> proxy,
10014 MUST_USE_RESULT Object* GetIdentityHash();
10016 static Handle<Object> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
10018 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
10022 class JSFunctionProxy: public JSProxy {
10024 // [call_trap]: The call trap.
10025 DECL_ACCESSORS(call_trap, Object)
10027 // [construct_trap]: The construct trap.
10028 DECL_ACCESSORS(construct_trap, Object)
10031 static inline JSFunctionProxy* cast(Object* obj);
10033 // Dispatched behavior.
10034 DECLARE_PRINTER(JSFunctionProxy)
10035 DECLARE_VERIFIER(JSFunctionProxy)
10037 // Layout description.
10038 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
10039 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
10040 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
10041 static const int kSize = JSFunction::kSize;
10042 static const int kPaddingSize = kSize - kPaddingOffset;
10044 STATIC_CHECK(kPaddingSize >= 0);
10046 typedef FixedBodyDescriptor<kHandlerOffset,
10047 kConstructTrapOffset + kPointerSize,
10048 kSize> BodyDescriptor;
10051 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
10055 // The JSSet describes EcmaScript Harmony sets
10056 class JSSet: public JSObject {
10058 // [set]: the backing hash set containing keys.
10059 DECL_ACCESSORS(table, Object)
10062 static inline JSSet* cast(Object* obj);
10064 // Dispatched behavior.
10065 DECLARE_PRINTER(JSSet)
10066 DECLARE_VERIFIER(JSSet)
10068 static const int kTableOffset = JSObject::kHeaderSize;
10069 static const int kSize = kTableOffset + kPointerSize;
10072 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10076 // The JSMap describes EcmaScript Harmony maps
10077 class JSMap: public JSObject {
10079 // [table]: the backing hash table mapping keys to values.
10080 DECL_ACCESSORS(table, Object)
10083 static inline JSMap* cast(Object* obj);
10085 // Dispatched behavior.
10086 DECLARE_PRINTER(JSMap)
10087 DECLARE_VERIFIER(JSMap)
10089 static const int kTableOffset = JSObject::kHeaderSize;
10090 static const int kSize = kTableOffset + kPointerSize;
10093 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10097 // Base class for both JSWeakMap and JSWeakSet
10098 class JSWeakCollection: public JSObject {
10100 // [table]: the backing hash table mapping keys to values.
10101 DECL_ACCESSORS(table, Object)
10103 // [next]: linked list of encountered weak maps during GC.
10104 DECL_ACCESSORS(next, Object)
10106 static const int kTableOffset = JSObject::kHeaderSize;
10107 static const int kNextOffset = kTableOffset + kPointerSize;
10108 static const int kSize = kNextOffset + kPointerSize;
10111 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10115 // The JSWeakMap describes EcmaScript Harmony weak maps
10116 class JSWeakMap: public JSWeakCollection {
10119 static inline JSWeakMap* cast(Object* obj);
10121 // Dispatched behavior.
10122 DECLARE_PRINTER(JSWeakMap)
10123 DECLARE_VERIFIER(JSWeakMap)
10126 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10130 // The JSWeakSet describes EcmaScript Harmony weak sets
10131 class JSWeakSet: public JSWeakCollection {
10134 static inline JSWeakSet* cast(Object* obj);
10136 // Dispatched behavior.
10137 DECLARE_PRINTER(JSWeakSet)
10138 DECLARE_VERIFIER(JSWeakSet)
10141 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10145 class JSArrayBuffer: public JSObject {
10147 // [backing_store]: backing memory for this array
10148 DECL_ACCESSORS(backing_store, void)
10150 // [byte_length]: length in bytes
10151 DECL_ACCESSORS(byte_length, Object)
10154 DECL_ACCESSORS(flag, Smi)
10156 inline bool is_external();
10157 inline void set_is_external(bool value);
10159 inline bool should_be_freed();
10160 inline void set_should_be_freed(bool value);
10162 // [weak_next]: linked list of array buffers.
10163 DECL_ACCESSORS(weak_next, Object)
10165 // [weak_first_array]: weak linked list of views.
10166 DECL_ACCESSORS(weak_first_view, Object)
10169 static inline JSArrayBuffer* cast(Object* obj);
10171 // Neutering. Only neuters the buffer, not associated typed arrays.
10174 // Dispatched behavior.
10175 DECLARE_PRINTER(JSArrayBuffer)
10176 DECLARE_VERIFIER(JSArrayBuffer)
10178 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10179 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10180 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10181 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10182 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10183 static const int kSize = kWeakFirstViewOffset + kPointerSize;
10185 static const int kSizeWithInternalFields =
10186 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10189 // Bit position in a flag
10190 static const int kIsExternalBit = 0;
10191 static const int kShouldBeFreed = 1;
10193 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10197 class JSArrayBufferView: public JSObject {
10199 // [buffer]: ArrayBuffer that this typed array views.
10200 DECL_ACCESSORS(buffer, Object)
10202 // [byte_length]: offset of typed array in bytes.
10203 DECL_ACCESSORS(byte_offset, Object)
10205 // [byte_length]: length of typed array in bytes.
10206 DECL_ACCESSORS(byte_length, Object)
10208 // [weak_next]: linked list of typed arrays over the same array buffer.
10209 DECL_ACCESSORS(weak_next, Object)
10212 static inline JSArrayBufferView* cast(Object* obj);
10214 DECLARE_VERIFIER(JSArrayBufferView)
10216 static const int kBufferOffset = JSObject::kHeaderSize;
10217 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10218 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10219 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10220 static const int kViewSize = kWeakNextOffset + kPointerSize;
10226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10230 class JSTypedArray: public JSArrayBufferView {
10232 // [length]: length of typed array in elements.
10233 DECL_ACCESSORS(length, Object)
10235 // Neutering. Only neuters this typed array.
10239 static inline JSTypedArray* cast(Object* obj);
10241 ExternalArrayType type();
10242 size_t element_size();
10244 Handle<JSArrayBuffer> GetBuffer();
10246 // Dispatched behavior.
10247 DECLARE_PRINTER(JSTypedArray)
10248 DECLARE_VERIFIER(JSTypedArray)
10250 static const int kLengthOffset = kViewSize + kPointerSize;
10251 static const int kSize = kLengthOffset + kPointerSize;
10253 static const int kSizeWithInternalFields =
10254 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10257 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10258 Handle<JSTypedArray> typed_array);
10260 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10264 class JSDataView: public JSArrayBufferView {
10266 // Only neuters this DataView
10270 static inline JSDataView* cast(Object* obj);
10272 // Dispatched behavior.
10273 DECLARE_PRINTER(JSDataView)
10274 DECLARE_VERIFIER(JSDataView)
10276 static const int kSize = kViewSize;
10278 static const int kSizeWithInternalFields =
10279 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10282 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10286 // Foreign describes objects pointing from JavaScript to C structures.
10287 // Since they cannot contain references to JS HeapObjects they can be
10288 // placed in old_data_space.
10289 class Foreign: public HeapObject {
10291 // [address]: field containing the address.
10292 inline Address foreign_address();
10293 inline void set_foreign_address(Address value);
10296 static inline Foreign* cast(Object* obj);
10298 // Dispatched behavior.
10299 inline void ForeignIterateBody(ObjectVisitor* v);
10301 template<typename StaticVisitor>
10302 inline void ForeignIterateBody();
10304 // Dispatched behavior.
10305 DECLARE_PRINTER(Foreign)
10306 DECLARE_VERIFIER(Foreign)
10308 // Layout description.
10310 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10311 static const int kSize = kForeignAddressOffset + kPointerSize;
10313 STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
10316 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10320 // The JSArray describes JavaScript Arrays
10321 // Such an array can be in one of two modes:
10322 // - fast, backing storage is a FixedArray and length <= elements.length();
10323 // Please note: push and pop can be used to grow and shrink the array.
10324 // - slow, backing storage is a HashTable with numbers as keys.
10325 class JSArray: public JSObject {
10327 // [length]: The length property.
10328 DECL_ACCESSORS(length, Object)
10330 // Overload the length setter to skip write barrier when the length
10331 // is set to a smi. This matches the set function on FixedArray.
10332 inline void set_length(Smi* length);
10334 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10336 Handle<Object> value);
10338 MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
10341 // Initialize the array with the given capacity. The function may
10342 // fail due to out-of-memory situations, but only if the requested
10343 // capacity is non-zero.
10344 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10346 // Initializes the array to a certain length.
10347 inline bool AllowsSetElementsLength();
10349 static Handle<Object> SetElementsLength(Handle<JSArray> array,
10350 Handle<Object> length);
10352 // Set the content of the array to the content of storage.
10353 static inline void SetContent(Handle<JSArray> array,
10354 Handle<FixedArrayBase> storage);
10357 static inline JSArray* cast(Object* obj);
10359 // Ensures that the fixed array backing the JSArray has at
10360 // least the stated size.
10361 static inline void EnsureSize(Handle<JSArray> array,
10362 int minimum_size_of_backing_fixed_array);
10364 // Expand the fixed array backing of a fast-case JSArray to at least
10365 // the requested size.
10366 static void Expand(Handle<JSArray> array,
10367 int minimum_size_of_backing_fixed_array);
10369 // Dispatched behavior.
10370 DECLARE_PRINTER(JSArray)
10371 DECLARE_VERIFIER(JSArray)
10373 // Number of element slots to pre-allocate for an empty array.
10374 static const int kPreallocatedArrayElements = 4;
10376 // Layout description.
10377 static const int kLengthOffset = JSObject::kHeaderSize;
10378 static const int kSize = kLengthOffset + kPointerSize;
10381 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10385 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10386 Handle<Map> initial_map);
10389 // JSRegExpResult is just a JSArray with a specific initial map.
10390 // This initial map adds in-object properties for "index" and "input"
10391 // properties, as assigned by RegExp.prototype.exec, which allows
10392 // faster creation of RegExp exec results.
10393 // This class just holds constants used when creating the result.
10394 // After creation the result must be treated as a JSArray in all regards.
10395 class JSRegExpResult: public JSArray {
10397 // Offsets of object fields.
10398 static const int kIndexOffset = JSArray::kSize;
10399 static const int kInputOffset = kIndexOffset + kPointerSize;
10400 static const int kSize = kInputOffset + kPointerSize;
10401 // Indices of in-object properties.
10402 static const int kIndexIndex = 0;
10403 static const int kInputIndex = 1;
10405 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10409 class AccessorInfo: public Struct {
10411 DECL_ACCESSORS(name, Object)
10412 DECL_ACCESSORS(flag, Smi)
10413 DECL_ACCESSORS(expected_receiver_type, Object)
10415 inline bool all_can_read();
10416 inline void set_all_can_read(bool value);
10418 inline bool all_can_write();
10419 inline void set_all_can_write(bool value);
10421 inline bool prohibits_overwriting();
10422 inline void set_prohibits_overwriting(bool value);
10424 inline PropertyAttributes property_attributes();
10425 inline void set_property_attributes(PropertyAttributes attributes);
10427 // Checks whether the given receiver is compatible with this accessor.
10428 inline bool IsCompatibleReceiver(Object* receiver);
10430 static inline AccessorInfo* cast(Object* obj);
10432 // Dispatched behavior.
10433 DECLARE_VERIFIER(AccessorInfo)
10435 // Append all descriptors to the array that are not already there.
10436 // Return number added.
10437 static int AppendUnique(Handle<Object> descriptors,
10438 Handle<FixedArray> array,
10439 int valid_descriptors);
10441 static const int kNameOffset = HeapObject::kHeaderSize;
10442 static const int kFlagOffset = kNameOffset + kPointerSize;
10443 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10444 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10447 // Bit positions in flag.
10448 static const int kAllCanReadBit = 0;
10449 static const int kAllCanWriteBit = 1;
10450 static const int kProhibitsOverwritingBit = 2;
10451 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
10453 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10457 enum AccessorDescriptorType {
10458 kDescriptorBitmaskCompare,
10459 kDescriptorPointerCompare,
10460 kDescriptorPrimitiveValue,
10461 kDescriptorObjectDereference,
10462 kDescriptorPointerDereference,
10463 kDescriptorPointerShift,
10464 kDescriptorReturnObject
10468 struct BitmaskCompareDescriptor {
10470 uint32_t compare_value;
10471 uint8_t size; // Must be in {1,2,4}.
10475 struct PointerCompareDescriptor {
10476 void* compare_value;
10480 struct PrimitiveValueDescriptor {
10481 v8::DeclaredAccessorDescriptorDataType data_type;
10482 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10486 struct ObjectDerefenceDescriptor {
10487 uint8_t internal_field;
10491 struct PointerShiftDescriptor {
10492 int16_t byte_offset;
10496 struct DeclaredAccessorDescriptorData {
10497 AccessorDescriptorType type;
10499 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10500 struct PointerCompareDescriptor pointer_compare_descriptor;
10501 struct PrimitiveValueDescriptor primitive_value_descriptor;
10502 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10503 struct PointerShiftDescriptor pointer_shift_descriptor;
10508 class DeclaredAccessorDescriptor;
10511 class DeclaredAccessorDescriptorIterator {
10513 explicit DeclaredAccessorDescriptorIterator(
10514 DeclaredAccessorDescriptor* descriptor);
10515 const DeclaredAccessorDescriptorData* Next();
10516 bool Complete() const { return length_ == offset_; }
10521 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10525 class DeclaredAccessorDescriptor: public Struct {
10527 DECL_ACCESSORS(serialized_data, ByteArray)
10529 static inline DeclaredAccessorDescriptor* cast(Object* obj);
10531 static Handle<DeclaredAccessorDescriptor> Create(
10533 const DeclaredAccessorDescriptorData& data,
10534 Handle<DeclaredAccessorDescriptor> previous);
10536 // Dispatched behavior.
10537 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10538 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10540 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10541 static const int kSize = kSerializedDataOffset + kPointerSize;
10544 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10548 class DeclaredAccessorInfo: public AccessorInfo {
10550 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10552 static inline DeclaredAccessorInfo* cast(Object* obj);
10554 // Dispatched behavior.
10555 DECLARE_PRINTER(DeclaredAccessorInfo)
10556 DECLARE_VERIFIER(DeclaredAccessorInfo)
10558 static const int kDescriptorOffset = AccessorInfo::kSize;
10559 static const int kSize = kDescriptorOffset + kPointerSize;
10562 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10566 // An accessor must have a getter, but can have no setter.
10568 // When setting a property, V8 searches accessors in prototypes.
10569 // If an accessor was found and it does not have a setter,
10570 // the request is ignored.
10572 // If the accessor in the prototype has the READ_ONLY property attribute, then
10573 // a new value is added to the local object when the property is set.
10574 // This shadows the accessor in the prototype.
10575 class ExecutableAccessorInfo: public AccessorInfo {
10577 DECL_ACCESSORS(getter, Object)
10578 DECL_ACCESSORS(setter, Object)
10579 DECL_ACCESSORS(data, Object)
10581 static inline ExecutableAccessorInfo* cast(Object* obj);
10583 // Dispatched behavior.
10584 DECLARE_PRINTER(ExecutableAccessorInfo)
10585 DECLARE_VERIFIER(ExecutableAccessorInfo)
10587 static const int kGetterOffset = AccessorInfo::kSize;
10588 static const int kSetterOffset = kGetterOffset + kPointerSize;
10589 static const int kDataOffset = kSetterOffset + kPointerSize;
10590 static const int kSize = kDataOffset + kPointerSize;
10593 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10597 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10598 // accessor can either be
10599 // * a pointer to a JavaScript function or proxy: a real accessor
10600 // * undefined: considered an accessor by the spec, too, strangely enough
10601 // * the hole: an accessor which has not been set
10602 // * a pointer to a map: a transition used to ensure map sharing
10603 // access_flags provides the ability to override access checks on access check
10605 class AccessorPair: public Struct {
10607 DECL_ACCESSORS(getter, Object)
10608 DECL_ACCESSORS(setter, Object)
10609 DECL_ACCESSORS(access_flags, Smi)
10611 inline void set_access_flags(v8::AccessControl access_control);
10612 inline bool all_can_read();
10613 inline bool all_can_write();
10614 inline bool prohibits_overwriting();
10616 static inline AccessorPair* cast(Object* obj);
10618 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10620 Object* get(AccessorComponent component) {
10621 return component == ACCESSOR_GETTER ? getter() : setter();
10624 void set(AccessorComponent component, Object* value) {
10625 if (component == ACCESSOR_GETTER) {
10632 // Note: Returns undefined instead in case of a hole.
10633 Object* GetComponent(AccessorComponent component);
10635 // Set both components, skipping arguments which are a JavaScript null.
10636 void SetComponents(Object* getter, Object* setter) {
10637 if (!getter->IsNull()) set_getter(getter);
10638 if (!setter->IsNull()) set_setter(setter);
10641 bool ContainsAccessor() {
10642 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10645 // Dispatched behavior.
10646 DECLARE_PRINTER(AccessorPair)
10647 DECLARE_VERIFIER(AccessorPair)
10649 static const int kGetterOffset = HeapObject::kHeaderSize;
10650 static const int kSetterOffset = kGetterOffset + kPointerSize;
10651 static const int kAccessFlagsOffset = kSetterOffset + kPointerSize;
10652 static const int kSize = kAccessFlagsOffset + kPointerSize;
10655 static const int kAllCanReadBit = 0;
10656 static const int kAllCanWriteBit = 1;
10657 static const int kProhibitsOverwritingBit = 2;
10659 // Strangely enough, in addition to functions and harmony proxies, the spec
10660 // requires us to consider undefined as a kind of accessor, too:
10662 // Object.defineProperty(obj, "foo", {get: undefined});
10663 // assertTrue("foo" in obj);
10664 bool IsJSAccessor(Object* obj) {
10665 return obj->IsSpecFunction() || obj->IsUndefined();
10668 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10672 class AccessCheckInfo: public Struct {
10674 DECL_ACCESSORS(named_callback, Object)
10675 DECL_ACCESSORS(indexed_callback, Object)
10676 DECL_ACCESSORS(data, Object)
10678 static inline AccessCheckInfo* cast(Object* obj);
10680 // Dispatched behavior.
10681 DECLARE_PRINTER(AccessCheckInfo)
10682 DECLARE_VERIFIER(AccessCheckInfo)
10684 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10685 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10686 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10687 static const int kSize = kDataOffset + kPointerSize;
10690 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10694 class InterceptorInfo: public Struct {
10696 DECL_ACCESSORS(getter, Object)
10697 DECL_ACCESSORS(setter, Object)
10698 DECL_ACCESSORS(query, Object)
10699 DECL_ACCESSORS(deleter, Object)
10700 DECL_ACCESSORS(enumerator, Object)
10701 DECL_ACCESSORS(data, Object)
10703 static inline InterceptorInfo* cast(Object* obj);
10705 // Dispatched behavior.
10706 DECLARE_PRINTER(InterceptorInfo)
10707 DECLARE_VERIFIER(InterceptorInfo)
10709 static const int kGetterOffset = HeapObject::kHeaderSize;
10710 static const int kSetterOffset = kGetterOffset + kPointerSize;
10711 static const int kQueryOffset = kSetterOffset + kPointerSize;
10712 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10713 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10714 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10715 static const int kSize = kDataOffset + kPointerSize;
10718 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10722 class CallHandlerInfo: public Struct {
10724 DECL_ACCESSORS(callback, Object)
10725 DECL_ACCESSORS(data, Object)
10727 static inline CallHandlerInfo* cast(Object* obj);
10729 // Dispatched behavior.
10730 DECLARE_PRINTER(CallHandlerInfo)
10731 DECLARE_VERIFIER(CallHandlerInfo)
10733 static const int kCallbackOffset = HeapObject::kHeaderSize;
10734 static const int kDataOffset = kCallbackOffset + kPointerSize;
10735 static const int kSize = kDataOffset + kPointerSize;
10738 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10742 class TemplateInfo: public Struct {
10744 DECL_ACCESSORS(tag, Object)
10745 DECL_ACCESSORS(property_list, Object)
10746 DECL_ACCESSORS(property_accessors, Object)
10748 DECLARE_VERIFIER(TemplateInfo)
10750 static const int kTagOffset = HeapObject::kHeaderSize;
10751 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10752 static const int kPropertyAccessorsOffset =
10753 kPropertyListOffset + kPointerSize;
10754 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10757 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10761 class FunctionTemplateInfo: public TemplateInfo {
10763 DECL_ACCESSORS(serial_number, Object)
10764 DECL_ACCESSORS(call_code, Object)
10765 DECL_ACCESSORS(prototype_template, Object)
10766 DECL_ACCESSORS(parent_template, Object)
10767 DECL_ACCESSORS(named_property_handler, Object)
10768 DECL_ACCESSORS(indexed_property_handler, Object)
10769 DECL_ACCESSORS(instance_template, Object)
10770 DECL_ACCESSORS(class_name, Object)
10771 DECL_ACCESSORS(signature, Object)
10772 DECL_ACCESSORS(instance_call_handler, Object)
10773 DECL_ACCESSORS(access_check_info, Object)
10774 DECL_ACCESSORS(flag, Smi)
10776 inline int length();
10777 inline void set_length(int value);
10779 // Following properties use flag bits.
10780 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10781 DECL_BOOLEAN_ACCESSORS(undetectable)
10782 // If the bit is set, object instances created by this function
10783 // requires access check.
10784 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10785 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10786 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10787 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10789 static inline FunctionTemplateInfo* cast(Object* obj);
10791 // Dispatched behavior.
10792 DECLARE_PRINTER(FunctionTemplateInfo)
10793 DECLARE_VERIFIER(FunctionTemplateInfo)
10795 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10796 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10797 static const int kPrototypeTemplateOffset =
10798 kCallCodeOffset + kPointerSize;
10799 static const int kParentTemplateOffset =
10800 kPrototypeTemplateOffset + kPointerSize;
10801 static const int kNamedPropertyHandlerOffset =
10802 kParentTemplateOffset + kPointerSize;
10803 static const int kIndexedPropertyHandlerOffset =
10804 kNamedPropertyHandlerOffset + kPointerSize;
10805 static const int kInstanceTemplateOffset =
10806 kIndexedPropertyHandlerOffset + kPointerSize;
10807 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10808 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10809 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10810 static const int kAccessCheckInfoOffset =
10811 kInstanceCallHandlerOffset + kPointerSize;
10812 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10813 static const int kLengthOffset = kFlagOffset + kPointerSize;
10814 static const int kSize = kLengthOffset + kPointerSize;
10816 // Returns true if |object| is an instance of this function template.
10817 bool IsTemplateFor(Object* object);
10818 bool IsTemplateFor(Map* map);
10821 // Bit position in the flag, from least significant bit position.
10822 static const int kHiddenPrototypeBit = 0;
10823 static const int kUndetectableBit = 1;
10824 static const int kNeedsAccessCheckBit = 2;
10825 static const int kReadOnlyPrototypeBit = 3;
10826 static const int kRemovePrototypeBit = 4;
10827 static const int kDoNotCacheBit = 5;
10829 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10833 class ObjectTemplateInfo: public TemplateInfo {
10835 DECL_ACCESSORS(constructor, Object)
10836 DECL_ACCESSORS(internal_field_count, Object)
10838 static inline ObjectTemplateInfo* cast(Object* obj);
10840 // Dispatched behavior.
10841 DECLARE_PRINTER(ObjectTemplateInfo)
10842 DECLARE_VERIFIER(ObjectTemplateInfo)
10844 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10845 static const int kInternalFieldCountOffset =
10846 kConstructorOffset + kPointerSize;
10847 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10851 class SignatureInfo: public Struct {
10853 DECL_ACCESSORS(receiver, Object)
10854 DECL_ACCESSORS(args, Object)
10856 static inline SignatureInfo* cast(Object* obj);
10858 // Dispatched behavior.
10859 DECLARE_PRINTER(SignatureInfo)
10860 DECLARE_VERIFIER(SignatureInfo)
10862 static const int kReceiverOffset = Struct::kHeaderSize;
10863 static const int kArgsOffset = kReceiverOffset + kPointerSize;
10864 static const int kSize = kArgsOffset + kPointerSize;
10867 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10871 class TypeSwitchInfo: public Struct {
10873 DECL_ACCESSORS(types, Object)
10875 static inline TypeSwitchInfo* cast(Object* obj);
10877 // Dispatched behavior.
10878 DECLARE_PRINTER(TypeSwitchInfo)
10879 DECLARE_VERIFIER(TypeSwitchInfo)
10881 static const int kTypesOffset = Struct::kHeaderSize;
10882 static const int kSize = kTypesOffset + kPointerSize;
10886 #ifdef ENABLE_DEBUGGER_SUPPORT
10887 // The DebugInfo class holds additional information for a function being
10889 class DebugInfo: public Struct {
10891 // The shared function info for the source being debugged.
10892 DECL_ACCESSORS(shared, SharedFunctionInfo)
10893 // Code object for the original code.
10894 DECL_ACCESSORS(original_code, Code)
10895 // Code object for the patched code. This code object is the code object
10896 // currently active for the function.
10897 DECL_ACCESSORS(code, Code)
10898 // Fixed array holding status information for each active break point.
10899 DECL_ACCESSORS(break_points, FixedArray)
10901 // Check if there is a break point at a code position.
10902 bool HasBreakPoint(int code_position);
10903 // Get the break point info object for a code position.
10904 Object* GetBreakPointInfo(int code_position);
10905 // Clear a break point.
10906 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10908 Handle<Object> break_point_object);
10909 // Set a break point.
10910 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10911 int source_position, int statement_position,
10912 Handle<Object> break_point_object);
10913 // Get the break point objects for a code position.
10914 Object* GetBreakPointObjects(int code_position);
10915 // Find the break point info holding this break point object.
10916 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10917 Handle<Object> break_point_object);
10918 // Get the number of break points for this function.
10919 int GetBreakPointCount();
10921 static inline DebugInfo* cast(Object* obj);
10923 // Dispatched behavior.
10924 DECLARE_PRINTER(DebugInfo)
10925 DECLARE_VERIFIER(DebugInfo)
10927 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10928 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10929 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10930 static const int kActiveBreakPointsCountIndex =
10931 kPatchedCodeIndex + kPointerSize;
10932 static const int kBreakPointsStateIndex =
10933 kActiveBreakPointsCountIndex + kPointerSize;
10934 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10937 static const int kNoBreakPointInfo = -1;
10939 // Lookup the index in the break_points array for a code position.
10940 int GetBreakPointInfoIndex(int code_position);
10942 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10946 // The BreakPointInfo class holds information for break points set in a
10947 // function. The DebugInfo object holds a BreakPointInfo object for each code
10948 // position with one or more break points.
10949 class BreakPointInfo: public Struct {
10951 // The position in the code for the break point.
10952 DECL_ACCESSORS(code_position, Smi)
10953 // The position in the source for the break position.
10954 DECL_ACCESSORS(source_position, Smi)
10955 // The position in the source for the last statement before this break
10957 DECL_ACCESSORS(statement_position, Smi)
10958 // List of related JavaScript break points.
10959 DECL_ACCESSORS(break_point_objects, Object)
10961 // Removes a break point.
10962 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10963 Handle<Object> break_point_object);
10964 // Set a break point.
10965 static void SetBreakPoint(Handle<BreakPointInfo> info,
10966 Handle<Object> break_point_object);
10967 // Check if break point info has this break point object.
10968 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10969 Handle<Object> break_point_object);
10970 // Get the number of break points for this code position.
10971 int GetBreakPointCount();
10973 static inline BreakPointInfo* cast(Object* obj);
10975 // Dispatched behavior.
10976 DECLARE_PRINTER(BreakPointInfo)
10977 DECLARE_VERIFIER(BreakPointInfo)
10979 static const int kCodePositionIndex = Struct::kHeaderSize;
10980 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10981 static const int kStatementPositionIndex =
10982 kSourcePositionIndex + kPointerSize;
10983 static const int kBreakPointObjectsIndex =
10984 kStatementPositionIndex + kPointerSize;
10985 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10988 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10990 #endif // ENABLE_DEBUGGER_SUPPORT
10993 #undef DECL_BOOLEAN_ACCESSORS
10994 #undef DECL_ACCESSORS
10995 #undef DECLARE_VERIFIER
10997 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10998 V(kStringTable, "string_table", "(Internalized strings)") \
10999 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
11000 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
11001 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
11002 V(kInternalizedString, "internalized_string", "(Internal string)") \
11003 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
11004 V(kTop, "top", "(Isolate)") \
11005 V(kRelocatable, "relocatable", "(Relocatable)") \
11006 V(kDebug, "debug", "(Debugger)") \
11007 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
11008 V(kHandleScope, "handlescope", "(Handle scope)") \
11009 V(kBuiltins, "builtins", "(Builtins)") \
11010 V(kGlobalHandles, "globalhandles", "(Global handles)") \
11011 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
11012 V(kThreadManager, "threadmanager", "(Thread manager)") \
11013 V(kExtensions, "Extensions", "(Extensions)")
11015 class VisitorSynchronization : public AllStatic {
11017 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
11019 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
11022 #undef DECLARE_ENUM
11024 static const char* const kTags[kNumberOfSyncTags];
11025 static const char* const kTagNames[kNumberOfSyncTags];
11028 // Abstract base class for visiting, and optionally modifying, the
11029 // pointers contained in Objects. Used in GC and serialization/deserialization.
11030 class ObjectVisitor BASE_EMBEDDED {
11032 virtual ~ObjectVisitor() {}
11034 // Visits a contiguous arrays of pointers in the half-open range
11035 // [start, end). Any or all of the values may be modified on return.
11036 virtual void VisitPointers(Object** start, Object** end) = 0;
11038 // Handy shorthand for visiting a single pointer.
11039 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
11041 // Visit weak next_code_link in Code object.
11042 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
11044 // To allow lazy clearing of inline caches the visitor has
11045 // a rich interface for iterating over Code objects..
11047 // Visits a code target in the instruction stream.
11048 virtual void VisitCodeTarget(RelocInfo* rinfo);
11050 // Visits a code entry in a JS function.
11051 virtual void VisitCodeEntry(Address entry_address);
11053 // Visits a global property cell reference in the instruction stream.
11054 virtual void VisitCell(RelocInfo* rinfo);
11056 // Visits a runtime entry in the instruction stream.
11057 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
11059 // Visits the resource of an ASCII or two-byte string.
11060 virtual void VisitExternalAsciiString(
11061 v8::String::ExternalAsciiStringResource** resource) {}
11062 virtual void VisitExternalTwoByteString(
11063 v8::String::ExternalStringResource** resource) {}
11065 // Visits a debug call target in the instruction stream.
11066 virtual void VisitDebugTarget(RelocInfo* rinfo);
11068 // Visits the byte sequence in a function's prologue that contains information
11069 // about the code's age.
11070 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11072 // Visit pointer embedded into a code object.
11073 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11075 // Visits an external reference embedded into a code object.
11076 virtual void VisitExternalReference(RelocInfo* rinfo);
11078 // Visits an external reference. The value may be modified on return.
11079 virtual void VisitExternalReference(Address* p) {}
11081 // Visits a handle that has an embedder-assigned class ID.
11082 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11084 // Intended for serialization/deserialization checking: insert, or
11085 // check for the presence of, a tag at this position in the stream.
11086 // Also used for marking up GC roots in heap snapshots.
11087 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11091 class StructBodyDescriptor : public
11092 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11094 static inline int SizeOf(Map* map, HeapObject* object) {
11095 return map->instance_size();
11100 // BooleanBit is a helper class for setting and getting a bit in an
11102 class BooleanBit : public AllStatic {
11104 static inline bool get(Smi* smi, int bit_position) {
11105 return get(smi->value(), bit_position);
11108 static inline bool get(int value, int bit_position) {
11109 return (value & (1 << bit_position)) != 0;
11112 static inline Smi* set(Smi* smi, int bit_position, bool v) {
11113 return Smi::FromInt(set(smi->value(), bit_position, v));
11116 static inline int set(int value, int bit_position, bool v) {
11118 value |= (1 << bit_position);
11120 value &= ~(1 << bit_position);
11126 } } // namespace v8::internal
11128 #endif // V8_OBJECTS_H_